2014-10-31 47 views
0

我試圖編寫一個簡單的代碼塊,讓用戶輸入一個利率。該數字必須爲0或更大,其他任何值都將被拒絕,必須輪詢用戶直到輸入有效數字。如果該數字大於10%,則必須詢問用戶是否真的預期利率高,如果用戶回答是肯定的,則使用該號碼,否則將要求用戶輸入價值再次和上述檢查將作出。我無法理解這個嵌套的循環方面。任何幫助是極大的讚賞!Python嵌套循環輸入值並確認答案

def main(): 

    while True: 
     try: 
      interest_rate = int(input("Please enter an interest rate: ")) 
     except ValueErrror: 
      print("Entered value is not a number! ") 
     except KeyboardInterrupt: 
      print("Command Error!") 
     else: 
      if 0 <= interest_rate < 10: 
       break 
      elif interest_rate > 10: 
       print("Entered interest rate is greater than 10%. Are you sure? (y/n): ") 

main() 
+1

如果輸入的利率是10,該怎麼辦? – davidc 2014-10-31 00:35:14

+0

10很好。以上任何情況都應該要求確認。 – Ben 2014-10-31 00:38:15

+0

和利率真的是整數? – davidc 2014-10-31 00:43:09

回答

1

做這一切的嘗試,if inp > 10,詢問用戶是否是快樂,如果它們不,ELIF用戶輸入閾值之內只是打破循環:

def main(): 
    while True: 
     try: 
      interest_rate = int(input("Please enter an interest rate: ")) 
      if interest_rate > 10: 
       confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ") 
       if confirm =="y": 
        break 
      elif 0 <= interest_rate < 10: 
       break 
     except ValueError: 
      print("Entered value is not a number! ") 
    return interest_rate 

main() 
+0

事後看來,一氣呵成做事更有意義。我對編程相當陌生,所以我傾向於嘗試在塊之後的塊之後進行塊處理。這看起來更有效率。謝謝! – Ben 2014-10-31 00:45:20

+0

@本,沒有問題,不客氣,應該會更容易閱讀和做你需要的東西。 – 2014-10-31 00:46:53

0

三件事跳出:

1)ValueErrrorValueError

2)你不處理的最終測試用戶輸入

3)你可能想將< 10更改爲<= 10

0

使print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")輸入

answer = int(input("Are you sure?")) 
if answer == "y": 
    break 
0
else: 
    if 0 <= interest_rate < 10: 
     break 
    elif interest_rate > 10: 
     print("Entered interest rate is greater than 10%. Are you sure? (y/n): ") 

可以是:

if 0 <= interest_rate <= 10: 
    break 
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ") 

除了最後一行必須採取的應對和處理它。

else沒有後break

0

我通常喜歡打破解決方案和驗證到不同的模塊相關的if

elif是不必要的。請檢查下面的代碼,看看我如何分解它們。所以在調試和測試時很容易。

def validating_user_input(num): 
    """ 
    """ 
    return num > 0 

def getting_user_input(): 
    """ 
    """ 
    user_input = int(raw_input("Enter the number that is greater than 0: ")) 
    return user_input 

def confirming_choose(): 
    """ 
    """ 
    try: 
     user_choose = int(raw_input("Can you confirm your input? [0|1]? ")) 
    except ValueError: 
     return False 
    return user_choose == 1 



def main(): 
    """ 
    """ 
    initial_cond = True 
    while initial_cond: 
     user_input = getting_user_input() 
     if validating_user_input(user_input): 
      if user_input > 10: 
       confirmation = confirming_choose() 
       while not confirmation: 
        getting_user_input() 
       #do you operating here 
      initial_cond = False 
     else: 
      print "It is not valid input." 


if __name__ == "__main__": 
    main()