为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只斗牛犬 2022-05-19 18:38:03
尝试在 python 2.7 中创建决策菜单。不能让选项是个人的,而不是按顺序排列的。除了if给出语法错误之外的任何东西pc = 英镑换算kc = 千克换算cont = 1while 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时才能正常运行
查看完整描述

2 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

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!")


查看完整回答
反对 回复 2022-05-19
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

您的代码中有一个“错误”。

该变量pc仅在第一次提示时才定义 == 'pounds'。因此,您会pc is not defined在第 7 行收到错误消息,因为它仅在您输入“磅”时才被定义。


查看完整回答
反对 回复 2022-05-19
  • 2 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号