当出现错误时,如何使程序继续/重新启动?

2024-05-23 17:43:24 发布

您现在位置:Python中文网/ 问答频道 /正文

当我学习python时,我创建了这个代码,但问题是当有人键入与stm或mts不同的内容时,它只是打印错误消息并停止,我需要它继续并重新运行代码,所以我添加了一个While循环,其中包含一个continue语句,但它不能正常工作,它只是不断发送错误消息,请任何想法如何使我的代码继续运行,而不是垃圾邮件或停止后,它..谢谢你这么多

代码如下:

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()

Tags: theto代码returndefmtsamountprint
1条回答
网友
1楼 · 发布于 2024-05-23 17:43:24

Move usChoice=str(输入(“对于SAR to MAD type stm和对于MAD to SAR type mts:”)) 在while循环中,删除最后一条else语句,不应该在那里输入return,您可以编写一条错误消息

print(“欢迎来到Morocandirham\u 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")


    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()

相关问题 更多 >