If string statement: What am I missing? [duplicate] - python

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 7 years ago.
I've created a simple code which looks like this:
name = str(input ("What is your name?"))
gender = str(input ("What is your gender?"))
if gender == 'male' or 'Male':
print ("Hello Mr %s" % (name))
elif gender == 'female' or 'Female':
print ("Hello Mrs %s" % (name))
else:
print ('Invalid gender. Please try again.')
However, no matter what gender I type (even random words like test), it always prints out the if statement, which means it satisfy the gender == male portion. Like if I key in female, the if statements still prints out. What am I missing here?

In steps
Use the right variable name first:
gender = input("What is your gender?")
Second, the use of or is wrong:
>>> 'male' or 'Male'
'male'
Use:
if gender == 'male' or gender == 'Male':
Alternatively use:
if gender.lower() == 'male':
Whole program
name = input("What is your name?")
gender = input("What is your gender?")
if gender.lower() == 'male':
print("Your are %s" % (gender))
elif gender.lower() == 'female':
print("Your are %s" % (gender))
else:
print('Invalid gender. Please try again.')
Shorter version
name = input("What is your name?")
gender = input("What is your gender?")
if gender.lower() in ('male', 'female'):
print("Your are %s" % (gender.lower()))
else:
print('Invalid gender. Please try again.')

When comparing to more than one string, you need to do it differently:
if gender == 'male' or gender == 'Male':
Or, more simply:
if gender in ['male', 'Male']:
Or with a set:
if gender in {'male', 'Male'}:
Not much difference in speed with only two items, but with a lot of
items a set will be faster because it uses a hash table, while the list
uses linear search.
Now, as for what is happening with your code. If you do this:
if gender == 'male' or 'Male':
you are saying:
if (gender == 'male') or ('Male'):
So, no matter what gender is, if the first comparison is False, it
will just go on to 'Male'. That is a non-empty string, so it’s always
True and the conditional always ends up True as well.

Related

How to make while loop run when a variable returns false? [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 months ago.
My code works without errors however if I type something random it still continues and does not print "Error" and rerun the code? How would I fix this?
gender = True
while gender == True:
gender = input("Enter Gender: ")
if gender == "Male" or "male" or "Female" or "female" :
gender = False
else:
print("Error")
gender = True
You can use lower() and a correct if statement condition to fix the output error:
gender = True
while gender == True:
gender = input("Enter Gender: ").lower()
if gender in {"female", "male"}:
gender = False
else:
print("Error")
gender = True

Keep prompting user for boolean input using while loop but it still repeats after parameter is met

I'd like to keep asking for the user for isMale if they don't enter True or False.
However, the while loop keeps asking even when I enter True or False. I don't know why.
name = input("Name: ")
age = int(input("Age: "))
isMale = bool(input("Male? "))
while (isMale != True) or (isMale != False): #Is this correct?
print("Wrong Input. Please type True/False")
isMale = bool(input("Male? "))
if(isMale == True):
print("His name is "+ name)
print("He is {input} years old.".format(input= age))
print("He is a Male")
elif(isMale == False):
print("Her name is " + name)
print("She is {input} years old.".format(input= age))
print("She is a Female")
Here is the simple solution but let me give some explanation when you cast an input to boolean will be like if an input is empty will be false and if an input contains something will be true no matter how the string is will always be true so that in that case I decided to create variable and initialize it to false and if one of the condition evaluates to true the variable called notValid will be false.
And I added some string method that will help you to format an input which are strip() to remove extra white spaces and tittle() which will capitalize an input.
and also all of the conditions are not checking between and input which is the form of string and boolean no I changed isMale == True to isMale == 'True' because both are string will be easy to compare them.
Example
name = input("Name: ")
age = int(input("Age: "))
isMale = input("Male? ").strip().title()
notValid = True
if(isMale == 'True'):
print("His name is "+ name)
print("He is {input} years old.".format(input= age))
print("He is a Male")
notValid = False
elif(isMale == 'False'):
print("Her name is " + name)
print("She is {input} years old.".format(input= age))
print("She is a Female")
notValid = False
while notValid:
if (isMale != 'True') or (isMale != 'False'):
print("Wrong Input. Please type True/False")
isMale = input("Male? ").strip().title()
else:
notValid = False

what syntax I need to use for while loop and placement?

I start to learn python a couple of days ago,Im trying to make some kind of login interface with multiple passwords options but can't figure out the right way to make it loop until I enter the right password ,I tried to use "while" but cant seem to figure out the syntax and placement with it in my code,I want it to repeat the first block of code if "else" is the result so I can try and type the password again,please help?
import random
male = random.choice([True, False])
import random
num = random.choice(["1", "0"])
name = "joe"
user_input= input ("insert Password here ")
if ((user_input == "joey") or (user_input == "loki")):
if male == True: print("hello")
if male == False: print("wellcome")
if name == "joe":
if num == "1":
print("hi world")
if name == "joe":
if num == "0":
print("nice")
if name + num == ("joe" + "0"):
print("thats working")
else:
print ("Wrong Password,Please try again.")
First of all I would like to point out that you only need to import your libraries once. Second if you want your code to repeat you will require a loop, in python there are 2 types of loops - for loop and while loop. For your requirement I would suggest using a while loop as given below. I couldn't really understand what you were trying to accomplish but I have improved your code a bit.
import random
male = random.choice([True, False])
num = random.choice(["1", "0"])
name = "joe"
while True:
user_input= input("insert Password here ")
if (user_input == "joey") or (user_input == "loki"):
if male == True:
print("hello")
elif male == False:
print("wellcome")
else:
break
if name == "joe" and num == "1":
print("hi world")
elif name == "joe" and num == "0":
print("nice")
if name + num == ("joe" + "0"):
print("thats working")
else:
break
else:
print ("Wrong Password,Please try again.")
Another method of having it run repeatedly is to use recursive functions, however since you are just starting out with python I would suggest learning loops before you get into recursive functions.
You can use the following general syntax to validate input:
input_to_validate = input(message_on_input)
while not is_valid(input_to_validate):
print(message_on_error)
input_to_validate = input(message_on_input)
where is_valid() your method for determining if the input is valid or not
Before coding anything please do learn the language properly and do look up proper syntax conventions. The following code is much more readable and conforms more to coding standards:
import random
male = random.choice([True, False])
num = random.choice(["1", "0"])
name = "joe"
def is_valid(password):
return password in ["joey", "loki"]
user_input = input("insert Password here: ")
# this while-loop runs as long as the user_input is not valid
while not is_valid(user_input):
print("Wrong Password, please try again.")
user_input = input("insert Password here: ")
# this part of the code is reached only when user_input is valid
if male:
print("hello")
else:
print("welcome")
if name == "joe":
if num == "1":
print("hi world")
else:
print("nice")
if name + num == "joe0":
print("that's working")

Can you only have one string after !=

I'm just writing some small code and I'm not able to make this work, I am only able to have one string which is e.g boy or girl but I would like to have both, do I have to make a separate elif statement or can I somehow put girl in there as well
gender = input("Are you a boy or a girl? : ")
if (gender != "boy"):
print("Get out of here you mutant")
exit()
You would need to have 3 conditions:
if gender == 'boy':
print ('You are a boy')
elif gender == 'girl':
print ('You are a girl')
else:
print("Get out of here you mutant")
Or you can do like that:
if gender in ('boy', 'girl'):
print('You are a {}'.format(gender)
else:
print("Get out of here you mutant")
In the second script you check if gender is a girl or a boy and if so it puts gender variable in the print output string.

Is this code simplified? Should I use more functions?

So I'm working on this program that opens an external file and then runs through it to see if it contains specific information. Is there a way to simplify it or is the way it is now the most efficient way write this?
def printGender(alist):
if "Female" in alist:
print(alist)
print("Female Students")
def maleInfo(blist):
if "2010" in blist:
print(blist)
print("Students who enrolled in 2010")
def csc2010(clist):
if "CSC" in clist and "2010" in clist and "Female" in clist:
print(clist)
print("Female students who registered in CSC in 2010")
def main():
ref = open("file1.txt","r")
studentList = ref.readlines()
ask = 10
while ask != 0:
print("1) print all female info")
print("2) display all male info from 2010")
print("3) display female students who registered for CSC in 2010")
ask = int(input("Enter option 1, 2, 3 or 0 to quit: "))
if ask == 1:
for i in range(len(studentList)):
alist = studentList[i]
printGender(alist)
elif ask == 2:
for i in range(len(studentList)):
blist = studentList[i]
maleInfo(blist)
elif ask == 3:
for i in range(len(studentList)):
clist = studentList[i]
csc2010(clist)
elif ask == 0:
print("You chose to quit")
break
else:
print("Not a Valid input")
continue
ref.close()
main()
Is there a way to simplify this code so that I don't create three seperate list in the main function.
if ask == 1:
for i in range(len(studentList)):
alist = studentList[i]
printGender(alist)
elif ask == 2:
for i in range(len(studentList)):
blist = studentList[i]
maleInfo(blist)
elif ask == 3:
for i in range(len(studentList)):
clist = studentList[i]
csc2010(clist)
elif ask == 0:
print("You chose to quit")
break
else:
ect...
I was curious to see if there was a shorter way to get the same result. Maybe using a function that runns that section of code but I'm not sure how to do that.
Some problems to be aware of:
the construct
for i in range(len(studentList)):
alist = studentList[i]
printGender(alist)
is pretty nasty; if you actually need i you should use
for i, student in enumerate(student_list):
print_gender(student)
otherwise
for student in student_list:
print_gender(student)
Your functions are poorly named; they don't do what they say they do! printGender prints female students, printMale prints students from 2010, etc. Similarly, your variable names are poorly chosen; alist is not a list of students, it is a single student.
You seem to have a text string per student, at a guess something like 2009, 176915, Jones, Susan, Female, CSC; but you make no attempt to separate out fields. This will lead to annoying problems with students like 2009, 292010, Male, Jill, Female, RCSCA who will be reported as a student in both 2009 and 2010 (false match on student number), and both female and male (false match on last name), and in CSC (false match on course name). You really need to use a better data format - whether .csv or .json or a database, anything which returns named fields - to solve this problem.
Your search options are non-orthogonal and limited to pre-coded options; you have no way of searching, for example, for all CSC students in 2007 without rewriting your program.
Fixing these problems leads you to something like
import json
def record_print_format(record):
return "{Year:4} {Id:6} {Gender:6} {Firstname:>20} {Lastname:<20} {Course:6}".format(**record)
def show_records(records, format_fn=record_print_format):
for r in records:
print(format_fn(r))
num = len(records)
print("{} records:".format(num))
def filter_records(records, field, value):
return [r for r in records if r[field] == value]
def match_year(records, year):
return filter_records(records, "Year", year)
def match_gender(records, gender):
return filter_records(records, "Gender", gender)
def match_course(records, course):
return filter_records(records, "Course", course)
def main():
with open("student_list.json") as studentfile:
all_students = json.load(studentfile)
records = all_students
while True:
print("1: Filter by year")
print("2: Filter by gender")
print("3: Filter by course")
print("8: Show results")
print("9: Clear filters")
print("0: Exit")
option = input("Please pick an option: ").strip()
if option == "1":
year = input("Which year? ").strip()
records = match_year(records, year)
elif option == "2":
gender = input("Which gender? [Male|Female] ").strip()
records = match_gender(records, gender)
elif option == "3":
course = input("Which course? ").strip()
records = match_course(records, course)
elif option == "8":
show_records(records)
elif option == "9":
records = all_students
elif option == "0":
print("Goodbye!")
break
else:
print("I don't recognize that option.")
if __name__=="__main__":
main()

Categories