如何在发生错误时让程序继续/重新启动?
问题描述:
当我学习python时,我创建了这段代码,但问题是当某人输入与stm或mts不同的东西时,它只是输出错误信息并停止,我需要它继续并自行运行代码,因此我添加了一个while循环与继续声明,但它不能正常工作,它只是保持垃圾邮件的错误信息,请任何想法如何使我的代码保持运行没有垃圾邮件的信息或停止后..非常感谢你!如何在发生错误时让程序继续/重新启动?
下面的代码:
print("Welcome to MoroccanDirham_SaudiRiyal converter program!")
def mConv():
def rial_saudi_to_moroccan_dirham(sar):
amount = sar * 2.67
print("Here is the result: ", amount, "MAD")
def moroccan_dirham_to_rial_saudi(mad):
amount = mad * 0.37
print("Here is the result: ", amount, "SAR")
usChoice = str(input("For SAR to MAD type stm and for MAD to SAR type mts: "))
while True:
if usChoice == str("stm"):
x = int(input("Type the amount of money you want to convert: "))
rial_saudi_to_moroccan_dirham(x)
return False
elif usChoice == str("mts"):
y = int(input("Type the amount of money you want to convert: "))
moroccan_dirham_to_rial_saudi(y)
return False
elif usChoice != str("stm") or usChoice != str("mts") :
print("Error! Please choose between stm and mts.")
continue
return False
else:
return True
mConv()
答
移动usChoice = STR(输入( “对于特区MAD型STM和MAD到SAR型MTS:”)) while循环中,并删除你的最后别的声明中,你不应该放回到那里,你可以写一个错误信息
打印(“欢迎来到MoroccanDirham_SaudiRiyal转换程序!”)
def mConv():
def rial_saudi_to_moroccan_dirham(sar):
amount = sar * 2.67
print("Here is the result: ", amount, "MAD")
def moroccan_dirham_to_rial_saudi(mad):
amount = mad * 0.37
print("Here is the result: ", amount, "SAR")
while True:
usChoice = str(input("For SAR to MAD type stm and for MAD to SAR type mts: "))
if usChoice == str("stm"):
x = int(input("Type the amount of money you want to convert: "))
rial_saudi_to_moroccan_dirham(x)
return False
elif usChoice == str("mts"):
y = int(input("Type the amount of money you want to convert: "))
moroccan_dirham_to_rial_saudi(y)
return False
else:
print("Invalid choice. Allowed choices");
print("stm - rial to dirham");
print("mts - dirham to rial");
mConv()
太谢谢你了它的工作原理,我应该把usChoice = str(输入(“SAR for MAD type stm和MAD to SAR type mts:”))放在while循环中,就像你告诉我的,我真的没有注意到它,但我确实知道我的代码应该在每次与之前的2次没有太大关系时重新获得其他变量,您清除了很多错误先生,我非常感谢! –