【问题标题】:How to make the program continue/restart when there is an Error? [duplicate]出现错误时如何使程序继续/重新启动? [复制]
【发布时间】:2017-04-21 23:12:42
【问题描述】:

虽然我正在学习 python,但我创建了这段代码,但问题是当有人键入不同于 stm 或 mts 的内容时,它只会打印错误消息并停止,我需要它继续并自行重新运行代码,所以我添加带有 continue 语句的 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()

【问题讨论】:

    标签: python python-2.7 python-3.x wxpython ipython


    【解决方案1】:

    Move usChoice = str(input("对于 SAR 到 MAD 类型 stm 和对于 MAD 到 SAR 类型 mts:")) 在while循环中并删除最后一个else语句,你不应该在那里放一个return,你可以写一个错误消息

    print("欢迎来到摩洛哥迪拉姆_沙特里亚尔转换器程序!")

    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(input("For SAR to MAD type stm and for MAD to SAR type mts: ")) 放在 while 循环中告诉我我真的没有注意它,但我确实知道我的代码每次与之前的 2 没有太大关系时都应该重新获取另一个变量,您清除了很多错误先生,我非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2014-05-21
    • 2019-01-11
    相关资源
    最近更新 更多