Search code examples
pythonpython-2.7python-3.xwxpythonipython

How to make the program continue/restart when there is an Error?


While I'm learning python I created this code but the problem is when someone type something different than stm or mts it just prints the error message and stops and I need it to continue and re run the code by itself so I add a while loop with a continue statement but it doesn't work properly it just keep spamming the error message, please any ideas how to make my code keep running without spamming the message or stopping after it..and thank you so much!

Here's the code:

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

Solution

  • Move usChoice = str(input("For SAR to MAD type stm and for MAD to SAR type mts: ")) inside the while loop and remove your last else statement, you should not put a return there, you could write an error message

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