如何使用break语句

时间:2013-05-11 16:15:31

标签: python python-2.7

我在2.7中有一个工作货币转换器,但我想确保程序没有得到用户无法处理的数据。

  1. 如何让用户输入被理解为与案例无关
  2. 如果用户输入错误,如何让程序重启;即使是休息,但我无法解决如何做到这一点,尽管搜索并测试一些方法。
  3. 我已经离开了剩下的代码,因为使用预设数字有效地复制了第一组乘法。

    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)
    

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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...