简体   繁体   中英

How to ask for a boolean input from a user to qualify if statements and print a sentence using that information in Python

I'm here with my first (hopefully not last) query for you.

I'm trying to get information from the user, specifically boolean values to determine if they are male/female and tall/short, then print the correct statement of "You are a tall/short male/female"

is_tall = input("Are you tall?")
is_male = input("Are you male?")

if is_tall and is_male:
  print("You are a tall male")
elif is_tall and not(is_male):
  print("You are a tall female")
elif not(is_tall) and is_male:
  print("You are a short male, sorry")
else:
  print("You are a short female, sorry")

My code runs and always returns "You are a tall male", searching reveals this is because the user's input is considered always true as it is a string.

I've seen other examples for grabbing boolean values but not for grabbing two and using them both within if statements. Am I anywhere close here, what am I missing? I know I can't use bool() around the input to convert it.

Currently, you are checking if the string is non-zero. Instead, check the value of the string.

    if is_tall.upper() in ('YES', 'Y') and is_male.upper() in ('YES', 'Y'):
        print("You are a tall male")
    elif is_tall.upper() in ('YES', 'Y') and is_male.upper() in ('NO', 'N'):
        print("You are a tall female")

etc.

You may list as many valid strings (answers) as you like in the brackets after in , and forcing all input to either .upper() or .lower() saves you from dealing with twice as many (or more) possible responses.

you could try something like this:

tall_str = input("Are you tall? ")
while tall_str.lower() not in {'y', 'yes', 'n', 'no'}:
   tall_str = input("Are you tall [y/n] ? ")

is_tall = True if tall_str.lower() in {'y', 'yes'} else False

this will accept things like 'Yes' and 'nO' (for tall_str ) and then convert them to True or False (for is_tall ) and ask again if the given answer is not acceptable.

you could then do the same for is_male .

having cast the string to a boolean your if clauses will work.

Would this approach seem fit to you?

is_tall = True if input("Are you tall?").lower() == 'y' else False
is_male = True if input("Are you male?").lower() == 'y' else False
...

There is no easy way to get bool in input, although you can convert it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM