2013-05-11 66 views
0

我在2.7有一个工作货币转换器,但我想确保程序不会获取它无法处理的用户输入的数据。如何使用break语句

  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) 
+2

有没有循环。你不能从非循环中突破。 – Makoto 2013-05-11 16:21:48

+0

无关:'str(raw_input(...))'是多余的,因为'raw_input'返回一个字符串。 'int(input())'应该是'int(raw_input())'。 – bereal 2013-05-11 17:31:00

回答

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... 
2

1)您可以使用相同的情况下,无论

if currency.lower() == 'gbp'

if currency.upper() == 'GBP'

2)你可以在一段时间运行您的程序比较用户输入的字符串循环,这样,如果条件不满足,你可以continue到循环的下一个迭代(wh ICH将从头开始重新启动程序)

while True: 
    # get user input 
    # validate user input 
    # if input not valid continue, which will "restart" your program 
+0

感谢关于第二部分的答案是否有一个函数可以说没有错误?所以例如true = errors:重启程序 – userwill 2013-05-11 17:00:54