简体   繁体   中英

Python menu code move to next line of code

I am trying to make a simple menu in python for class, although, whenever I enter a choice in, for example, 1 - 5, I keep ending up getting my next if statement in my code which is "wrong choice,start over" my question is why does python keep printing the next if statement in my code("wrong answer, start over") when I enter a choice from one through 5 instead of saving it and moving to the next line in my code which should be the input for income

def main():
    print("\t\t\tMain Menu")
    print("\t\t\t=========")
    print ("\n\t\t1- Single")
    print ("\t\t2- Jointley (Married)")
    print ("\t\t3- Married Filing Seperatley")
    print ("\t\t4- Head of HouseHold")
    print ("\t\t5- Quit")


    choice = input("\n\n\t\t\tEnter your choice : ").upper()[0]
    if (choice == '1'):
        choice = 'S'
    elif (choice == '2'):
        choice = 'J'
    elif (choice == '3'):
        choice = 'M'
    elif (choice == '4'):
        choice = 'H'
    elif (choice == '5'):
        choice = 'Q'
    if (choice != 'S' or choice != 'J' or choice != 'M' or choice != 'H' or  choice != 'Q'):
        print("wrong Choice, Start over")
    else:
        income = float (input("Enter your Gross Income from Your W-2 form:   "))


main()
input("Press Enter to Continue")

For your condition here:

if (choice != 'S' or choice != 'J' or choice != 'M' or choice != 'H' or  choice != 'Q'):

You are looking to simply check whether choice is not any of the letters you expect, so you should be doing this with a not in :

if choice not in ('S', 'J', 'M', 'H', 'Q'):

Furthermore, for what you are doing here:

input("\n\n\t\t\tEnter your choice : ").upper()[0]

Don't have them enter the entire choice. Just the number. So you just take the input, and since it will be the string representation of a number, no need to upper either:

input("\n\n\t\t\tEnter your choice : ")

The reason that your code is moving to the last if statement is because of the or .

if (choice != 'S' or choice != 'J' or choice != 'M' or choice != 'H' or  choice != 'Q'):

For example, if choice == 'S' is true, that means choice != 'J' is also true, so no matter what choice is, that line will result true. Changing to and will fix the issue.

if choice != 'S' and choice != 'J' and choice != 'M' and choice != 'H' and choice != 'Q':

Small example to test it:

>> choice = 'S'

>> print(choice == 'S')
>> print(choice != 'Q')
>> print(choice == 'Q')
>> print(choice != 'S' or choice != 'Q')

True
True
False
True

Also, no need for parentheses for your if statements in Python, they're redundant.

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