如果用户输入“no”来打印(M1),如何停止最后一个print语句的运行?我希望程序在打印M1时完成。我得到了错误 由于在if块中声明“TaxCode”,用户输入“no”时出现“NameError:未定义名称“TaxCode”。 非常感谢。你知道吗
name = input("What is your name? ")
while True:
try:
income = int(input("What is your income? ($) "))
break
except ValueError:
print ("Invalid input\nPlease enter a figure")
continue
else:
break
M1 = "This program cannot determine your tax code. Please use the program for secondary income "
print("Please answer the questions with 'yes' and 'no'")
Q1=input("Do you receive an income tested benefit? ")
while Q1 != "yes" and Q1 != "no":
print("\nPlease enter either 'yes' or 'no'")
Q1=input("Do you recieve an income tested benefit? ")
if Q1=="yes":
Q2=input("Is this tax code for the income tested benefit? ")
while Q2 != "yes" and Q2 != "no":
print("\nPlease enter either 'yes' or 'no'")
Q2=input("Is this tax code for the income tested benefit? ")
if Q2=="yes":
TaxCode = "M"
elif Q2=="no":
print (M1)
print("Thanks for answering the questions.",name,"Your tax code is ",TaxCode)
在if语句之前用空值定义
TaxCode
,以防止NameError
。这样TaxCode =''
您可以使用
exit(0)
终止程序,这里的数字()表示成功/失败。与linux中的退出状态相同。所以你的代码是如果在函数中使用上述代码,并且希望停止函数,则可以使用
return
语句通过返回None
跳过最后一行的打印,因此在这种情况下,您的代码将被删除。你知道吗您可以根据您的逻辑使用
exit
或return
,因为您不清楚这段代码是用在函数中还是用在main中,我解释了两者。你知道吗您应该在if语句之外定义“TaxCode”。你知道吗
例如
就像@Navieclipse提到的那样,在使用之前需要定义TaxCode。你知道吗
另外,在这里复制之后格式化它会使它更容易阅读。你知道吗
相关问题 更多 >
编程相关推荐