第一次询问后,代码给我错误的输出结果

时间:2019-03-26 04:07:06

标签: python

为什么每当我要求输入时,我都会将其放入并给出正确的输出,但是之后无论如何它都会给出相同的输出?例如,我输入5作为输入,然后它给我正确的输出,但是之后它再次要求输入,当我输入例如10的输入时,它给我5而不是10的输出。 >

def menu():


        print()
       # display the menu
        print('Select from the following option:')
        print('\t1) Category')        
        print('\t2) Item')
        print('\t3) Serving Size')
        print('\t4) Calories')
        print('\t5) Calories From Fat')
        print('\t6) Total Fat')
        print('\t7) Cholesterol')
        print('\t8) Sodium')
        print('\t9) Carbohydrate')
        print('\t10) Protein')
        print('\t11) Sugars')
        print('\t12) Quit')
       # Ask the user to a number.
        item = input('Enter Number Command:')
        return item

item = menu()

while item != '12':

        if item == '1':
                print('\t1) Category')
        elif item == '2':

                print('\t2) Item')
        elif item == '3':
                print('\t3) Serving Size')

        #more elif statements I didn't put in so it wouldn't be too much
        else:   
                print('..invalid number...please put valid number')
        item != menu()

menu()

即使在第一次要求输入后,它也应该放置正确的输出。

1 个答案:

答案 0 :(得分:2)

您永远不会在行中更改item的值:

item !=menu()

您正在运行menu(),这就是为什么您看到菜单打印,但是item的值从未更新的原因。只需将不等式更改为相等:

def menu():


        print()
       # display the menu
        print('Select from the following option:')
        print('\t1) Category')        
        print('\t2) Item')
        print('\t3) Serving Size')
        print('\t4) Calories')
        print('\t5) Calories From Fat')
        print('\t6) Total Fat')
        print('\t7) Cholesterol')
        print('\t8) Sodium')
        print('\t9) Carbohydrate')
        print('\t10) Protein')
        print('\t11) Sugars')
        print('\t12) Quit')
       # Ask the user to a number.
        item = input('Enter Number Command:')
        return item

item = menu()

while item != '12':

        if item == '1':
                print('\t1) Category')
        elif item == '2':

                print('\t2) Item')
        elif item == '3':
                print('\t3) Serving Size')

        #more elif statements I didn't put in so it wouldn't be too much
        else:   
                print('..invalid number...please put valid number')
        item = menu() # item will be updated and assigned a new value

menu()