如果用户输入'no'进行打印(M1),如何停止运行最后一个打印语句?我希望程序在打印M1时完成。我收到了错误 “NameError:名称'TaxCode'未定义”当用户输入'no'时,因为在if块中声明'TaxCode'。 谢谢。
~/Library/MobileDevice/Provisioning Profiles
答案 0 :(得分:1)
在if语句之前使用空值定义TaxCode
以防止NameError
。这样TaxCode =''
你可以使用exit(0)
来终止程序里面的数字()里面指的是成功/失败。与linux中的退出状态相同。所以你的代码将是
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? ")
TaxCode='' #define it before using
if Q2=="yes":
TaxCode = "M"
elif Q2=="no":
print (M1)
exit(0) # terminates program and raises success non-zero value refers failure.
print("Thanks for answering the questions.",name,"Your tax code is ",TaxCode)
如果您在函数中使用上述代码并且想要停止该函数,则可以使用return
语句通过返回None
来跳过打印最后一行,因此在这种情况下您的代码将是。< / p>
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? ")
TaxCode='' #define it before using
if Q2=="yes":
TaxCode = "M"
elif Q2=="no":
print (M1)
return None # skips print and returns to calling function.
print("Thanks for answering the questions.",name,"Your tax code is ",TaxCode)
您可以根据您的逻辑使用exit
或return
,因为您不清楚此代码是用于函数还是主要用于解释这两个。
答案 1 :(得分:0)
您应该定义&#39; TaxCode&#39;在if语句之外。
例如,
TaxCode = ""
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)
答案 2 :(得分:0)
就像@Navieclipse提到的那样,你需要在使用之前定义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
TaxCode = ""
M1 = "This program cannot determine your tax code. Please use the program for secondary income "
print("Please answer the questions with 'yes' and 'no'")
while True:
Q1=input("Do you receive an income tested benefit? ")
if Q1 == "yes":
Q2=input("Is this tax code for the income tested benefit? ")
if Q2 == "yes":
TaxCode = "Test"
print("Thanks for answering the questions, "+ name + ", " + "your tax code is " + TaxCode + ".")
break
elif Q2 == 'no':
print(M1)
break
else:
print("\nPlease enter either 'yes' or 'no'")
此外,将其复制到此处后对其进行格式化会使其更易于阅读。