[英]How to stop python from running certain 'if' code when the variable value doesn't match
尝试在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
当第一个提示给出“未定义pc”时,以kilograms
输入
如果您先输入pounds
,然后输入kilograms
,则该程序只能正确运行
您的代码中有一个“错误”。
仅当第一个提示== 'pounds'
时才定义变量pc
。 因此,您得到的错误消息pc is not defined
在第7行中pc is not defined
,因为只有在键入“磅”时才定义该错误消息。
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!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.