当变量值不匹配时如何阻止python运行某些'if'代码

尝试在 python 2.7 中创建决策菜单。


不能让选项是个人的,而不是按顺序排列的。


除了if给出语法错误之外的任何东西


pc = 英镑换算


kc = 千克换算


cont = 1

while cont == 1:


    if input("Would you like to convert to pounds or kilograms?") == 'pounds':

        pc = 1


    if pc == 1:

        kilograms = float(input("Enter the amount of kilograms:  "))

        pounds = kilograms / 2.205


        print('The amount of pounds you entered is ', kilograms,

                  ' This is ', pounds, ' pounds ')

        pc = 0

        if input('Do you want to go again? (y/n) ') == 'n':

            cont = 0


    if input("Would you like to convert to pounds or kilograms?") == "kilograms":

        kc = 1


    if kc == 1:

        pounds = float(input("Enter the amount of pounds:  "))

        kilograms = pounds * 2.2

        grams = kilograms * 1000


        print('The amount of pounds you entered is ', pounds,

                  ' This is ', kilograms, ' kilograms ', 'and', grams,

                  'grams' )

        kc = 0


    if input('Do you want to go again? (y/n) ') == 'n':

        cont = 0

在kilograms第一次提示时输入“PC未定义”


并且程序只有在您输入poundsfirst, kilogramssecond时才能正常运行


一只斗牛犬
浏览 153回答 2
2回答

斯蒂芬大帝

while True: #generic while statement, only way to exit is break    choice = input("Would you like to convert to pounds or kilograms: ") #store our choice in a variable for later    if choice == 'pounds':        kilograms = float(input("Enter the amount of kilograms:  "))        pounds = kilograms / 2.205        print('The amount of killograms you entered is ', kilograms,                  ' This is ', pounds, ' pounds ')    elif choice == "kilograms": #use an elif and define a different specific statement        pounds = float(input("Enter the amount of pounds:  "))        kilograms = pounds * 2.2        grams = kilograms * 1000        print('The amount of pounds you entered is ', pounds,                  ' This is ', kilograms, ' kilograms ', 'and', grams,                  'grams' )    elif choice == "quit":        print("Goodbye!")        break #use break to break out of a loop    else: #use an else to define a generic statement        print "%s is not a valid choice"%choice        continue #use continue to return to the beginning of the loop without doing anything after    do_continue = input('Do you want to go again? (y/n) ')    if do_continue == 'y':        pass #do nothing and continue    elif do_continue == 'n':        print("Goodbye!")        break    else:        print("What language is that? We will go again anyways!")

慕莱坞森

您的代码中有一个“错误”。该变量pc仅在第一次提示时才定义 == 'pounds'。因此,您会pc is not defined在第 7 行收到错误消息,因为它仅在您输入“磅”时才被定义。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python