0

我在 2.7 中有一个可用的货币转换器,但我想确保程序不会获取用户输入的无法处理的数据。

  1. 如何让用户输入与大小写无关
  2. 如果用户输入错误,如何让程序重新启动;即休息一下,但尽管搜索并测试了一些方法,但我无法弄清楚如何做到这一点。

我留下了其余的代码,因为它与使用预设数字的第一组乘法实际上是微不足道的。

currency = str(raw_input ("""what currency would you like to covert: GBP, EURO, USD OR YEN?
"""))
exchange = str(raw_input("""what currency would you like in exchange? : GBP, EURO, USD OR YEN?
                              """))
amount = int(input("""how much would you like to convert?
                      """))
decision = str(raw_input("""Please enter u for user input exchange rate or s for the preset exchange rate
"""))

if decision == "u" :
    user_rate = raw_input("Please enter the current exchange rate")
    exchange_value = int(amount) *  int(user_rate)
    print ("At the user found exchange rate you will receive",exchange_value,exchange)

elif decision == "s" :
    if currency  == "GBP" and exchange == "USD":
        exchange_value= int(amount) * 1.6048
        print ("At the preset exchange rate you will receive",exchange_value,exchange)

    if currency  == "GBP" and exchange == "EUR":
        exchange_value= int(amount) * 1.2399
        print ("At the preset exchange rate you will receive",exchange_value,exchange)
4

2 回答 2

2

1)您可以使用相同的大小写比较用户输入字符串,无论

if currency.lower() == 'gbp'

或者

if currency.upper() == 'GBP'

2)您可以在while循环中运行您的程序,这样如果不满足条件,您可以continue进入循环的下一次迭代(这将从头开始重新启动您的程序)

while True:
  # get user input
  # validate user input
  # if input not valid continue, which will "restart" your program
于 2013-05-11T16:23:00.447 回答
0

这样的事情将帮助你开始

    valid_input = ('EUR', 'GBP', 'USD', 'JPY')

    while True:
        # Obtain user data

        # Make sure all its in caps
        currency = currency.upper()
        exchange = exchange.upper()

        if currency in valid_input and exchange in valid_input:
            break 

         print ("Error Invalid input, try again...")

    # Proccess data...
于 2013-05-11T17:13:28.400 回答