Question

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..

Was it helpful?

Solution 2

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.

OTHER TIPS

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')

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.')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top