How to check if user input has these lines? - python

It's my second program in Python. I seem to be happy with my progress. The question is I am trying to make is:
choice=eg.ynbox(msg='wat to do')
for["true","1"] in choice:
print("yes")
for["false","0"] in choice:
print("no")
The problem is that this for condition is not working. I have seen such code while I was looking up answers for my previous question but I forget. I tried googling but I dont know how to put this in words..A little syntax help is necessary
BTW: its a gui program with easygui 0.96..

choice = eg.ynbox(msg='wat to do')
if any(word in choice for word in ["true","1"]):
print('yes')
elif any(word in choice for word in ["false","0"]):
print('no')
else:
print('invalid input')
or, if the list is short:
choice = eg.ynbox(msg='wat to do')
if 'true' in choice or '1' in choice::
print('yes')
if 'false' in choice or '0' in choice::
print('no')
else:
print('invalid input')

I assume by eg.ynbox(msg='wat to do') you mean you are creating a Yes/No dialog box. This means that the value stored in choice is an Integer where 1 represents True and 0 represents False. This is correct in both Python 2.x and Python 3.x as long as True and False have not been reassigned in Python 2.x True and False are reserved keywords in Python 3.x and thus are guaranteed not to change. Therefore, you simply have an if statement that works using this value:
if choice:
print 'Yes'
else:
print 'No'
You do not need to match on 1 and 0 since they represent both True and False.

You might try the following code in place of yours:
def is_accept(word):
return word.lower() in {'true', '1', 'yes', 'accept'}
def is_cancel(word):
return word.lower() in {'false', '0', 'no', 'cancel'}
def get_choice(prompt=''):
while True:
choice = eg.ynbox(msg=prompt)
if is_accept(choice):
print('Yes')
return True
if is_cancel(choice):
print('No')
return False
print('I did not understand your choice.')

Related

Is there an if function in python for ASCII art? [duplicate]

I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()

In python, can "!=" be used with "and", "or"? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
result = {}
question = '你叫什么名字? ' #What is your name
question_2 = '如果你能去世界上的任何一个地方度假,你想去哪? ' #If you could go to any place in the world for vacation, where would you like to go?
question_3 = '你愿意让你旁边的人也来参加这个调查吗? (yes/ no) ' #Would you like to let people next to you participate in this survey?
while True:
name = input(question)
place = input(question_2)
result[name] = place #除了yes或者no不允许输入其他字符
while True: #No other characters are allowed except "yes" or "no"
opinion = input(question_3)
if opinion.lower() != 'yes' or 'no':
print('请重新输入') #please enter again
else:
break
if opinion == 'no':
break
No matter what you enter after running, you can't jump out of the loop
if opinion.lower() not in ('yes','no'):
It's normal to change to this, but I'm still curious why something went wrong
Beginners, thanks
Consider this line:
if opinion.lower() != 'yes' or 'no':
So this is how that expression is evaluated (according to order of precedence):
if (opinion.lower() != 'yes') or ('no'):
And 'no' is always evaluated as True. Moreover, it should be option not 'yes' 'and' not 'no' (instead of 'or'). Consider changing it to:
if opinion.lower() != 'yes' and opinion.lower() != 'no':
More shortly,
if opinion.lower() not in ('yes', 'no'):
And this will fix your issue.
result = {}
question = "What is your name"
question_2 = "If you could go to any place in the world for vacation, where would you like to go?"
question_3 = "Would you like to let people next to you participate in this survey?"
while True:
name = input(question)
place = input(question_2)
result[name] = place #除了yes或者no不允许输入其他字符
while True: #No other characters are allowed except "yes" or "no"
opinion = input(question_3)
if opinion.lower() not in ('yes','no'):
print('please enter again')
else:
break
if opinion == 'no':
break
You could use a tuple to fix your problem, that's one thing first.
Now what you want is why isn't the following code working:
x != "yes" or "no"
Recall from the order of precedence that != has a higher priority than or, so x!= "yes" will be evaluated first, then it will be ORed with "no", simply to fix it, add parenthesis around the or statement:
x != ("yes" or "no")
Would do the trick for ya!

case insensitive multiple conditions checking for input

I've got written a calculator on python 3 in pycharm edu. The part of the code is here:
def again():
calc_again = input('''
Repeat?
''')
#disagreements = frozenset('N'or 'No' or 'Not')
#agreements = frozenset('Y' or 'Yes' or 'Ya')
if (calc_again.upper()=='Y' or calc_again.upper()=='Yes' or calc_again.upper()=='Ya'):
calc()
elif (calc_again=='N' or calc_again=="No" or calc_again=='Not'):
print('Exit')
again()
else:
print('Type y/n')
The problem appears when I'm trying to input any other condition except Y and N, it just doesn't respond fine, and I doubt it's case insensitive as well.
I was trying to use:
if calc_again.upper() in agreements:
do..
but it just gives me the same result.
Can somebody fix it and explain?
Also, may be it's better to use "while True" instead of "again()" (11 str)?
UPD
with last changes it looks like
def again():
possible_conditions = frozenset(['y', 'yes', 'ya', 'n', 'no', 'not'])
calc_again = input('Go again?')
agreements = frozenset(['y', 'yes', 'ya'])
if calc_again.lower() in possible_conditions:
if calc_again.lower() in agreements:
calc()
else:
print('bye')
exit()
else:
print('choose y or n')
again()
Your problem is that you are checking UPPER version of calc_again string. So you will have always uppercase letters in calc_again.upper(). To fix your code, just make your list of possible cases upper.
if (calc_again.upper()=='Y' or calc_again.upper()=='YES' or calc_again.upper()=='YA'):
calc()
elif (calc_again=='N' or calc_again=="NO" or calc_again=='NOT'):
print('Exit')
again()
else:
print('Type y/n')
Also, I think you have to put your if statements in while loop, because it have to be executed always depending on user inputs.

Python wont choose between 2 if options [duplicate]

I'm learning python and I found myself lost trying to create a an if statement that should be true if the user input y or yes.
#!/usr/bin/env python3
user_input = input('Would you like to go on?')
lowui = user_input.lower
if lowui == ('y' or 'yes'):
print('You want to go on')
else
print('See you later, bye')
The problem is that it becomes true only if I type y but not for yes. If I remove the parenthesis it becomes always false. Ok, I can do a workaround like
if lowui == 'y' or lowui == 'yes':
but I was wondering if there is any trick that don't force me to write so many times tha variable.
Thank you in advance.
Change it to
if lowui in ('y', 'yes'):
Also this is wrong:
lowui = user_input.lower
it should be:
lowui = user_input.lower() # Actually call the lower function

Python will not accept user inputs [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 7 years ago.
I managed to get this code to work before, but I've changed something accidentally and can't figure out what.
The code that will not work is:
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
When I run the code and put in one of the answers, the program will not run the next part and gives no error message.
In case it is necessary, I have put the code for the entire program below:
import random
import sys
while True:
answer = input ("Would you like to play this game? Type yes if you would like to. Type no to end the program")
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
elif answer == 'yes' or 'y' or 'Yes' or 'Y':
code = input("Input a three digit code. Must be more than 001 and less than 100.")
try:
value = int(code)
except:
print ("Invalid code")
continue
if 1 <= value <= 100:
print (code)
print ("Valid code")
print ("I will now try to guess your number")
number = random.randint(1, 100)
while number > int(code) or number < int(code):
print ("Failed attempt. Number guessed is")
number = random.randint(1, 100)
print (number)
else:
if number == int(code):
print ("Your code is")
print (code)
else:
print ("Invalid code")
EDIT: Thank you so much, the yes option is working now, but the program will still not exit when selecting any of the no options, as it did before. The edited code is:
if answer in ('no', 'n', 'No', 'N'):
sys.exit()
elif answer in ('yes', 'y', 'Yes', 'Y'):
I checked by printing the answer value, and i believe it is registering the no input but not executing the command that follows for some reason.
EDIT: I'm still a bit fuzzy on the logic, but changing it to exit() fixed the problem. It asks for confirmation when closing now, when it didn't before, but otherwise sorted.
Problem causing silent exit:
if answer == 'no' or 'n' or 'No' or 'N':
sys.exit()
That test is testing answer == 'no' as one test, then 'n' as a separate test, and so on. or chains return when any test returns a "truthy" value (or the last evaluated value if none are truthy), so the test always ends up evaluating as "truthy" because a non-empty string like 'n' is truthy. If you're trying to test for any one of those values, you'd do an "is contained in" test to see if answer is one of a recognized group of values, e.g.:
if answer in ('no', 'n', 'No', 'N'):
The reason is due to this expression:
if answer == 'no' or 'n' or 'No' or 'N':
In python, the above is exactly the same as this:
if (answer == 'no') or ('n' != '') or ('No' != '') or ('N' != ''):
Since all but the first expression evaluates to true, the whole expression is true.
The simplest solution is to convert your input to lowercase and trim off any extra space, then check if the answer is in a list of allowable answers so that you can easily compare for "n", "N", "no", "NO", "No", "nO".
if answer.strip().lower() in ("n", "no"):

Categories