2016-03-05 80 views
0

因此,我需要一個非常高效的代碼,它將接受用戶從0到1之間的任何數字,並不斷提示他們再次嘗試,直到他們的輸入符合此條件。 這是我到目前爲止有:只接受0和1之間的浮點數 - python

def user_input(): 
while True: 
    global initial_input 
    initial_input = input("Please enter a number between 1 and 0") 
    if initial_input.isnumeric() and (0 <= float(initial_input) <= 1): 
     initial_input = float(initial_input) 
     return(initial_input) 
    print("Please try again, it must be a number between 0 and 1") 
user_input() 

這工作,但只有在數量實際上是1或0。如果你輸入之間的小數這些(如0.6),它崩潰

+1

*如果您在這些(例如0.6)之間輸入小數,它會崩潰* ....錯誤信息是什麼? –

+0

除「未解析的屬性參考」爲「float」類的數字外,沒有錯誤消息。循環就像我輸入一個不在1和0之間的數字一樣運行(不斷請求我再試一次)@Xoce – mrzippy01

+0

將輸入轉換爲浮點兩次,一次*在*之前*嘗試調用字符串方法在上面。直到你明白每個人在做什麼爲止,逐行看看你的代碼。 – jonrsharpe

回答

-1

你首先要檢查它是否真的是一個浮動,if "." in initial_input,然後你可以去其他的轉換:

def user_input(): 
    while True:  
     initial_input = input("Please enter a number between 1 and 0").strip() 
     if "." in initial_input or initial_input.isnumeric(): 
      initial_input = float(initial_input) 
      if 0 <= initial_input <= 1: 
       print("Thank you.") 
       return initial_input 
      else: 
       print("Please try again, it must be a number between 0 and 1") 
     else: 
      # Input was not an int or a float 
      print("Input MUST be a number!") 

initial_input = user_input() 
0

你應該使用try /除返回輸入只有當它是介於0的數和1,作爲ValueError捕獲錯誤的輸入:

def user_input(): 
    while True: 
     try: 
      # cast to float 
      initial_input = float(input("Please enter a number between 1 and 0"))  # check it is in the correct range and is so return 
      if 0 <= initial_input <= 1: 
       return (initial_input) 
      # else tell user they are not in the correct range 
      print("Please try again, it must be a number between 0 and 1") 
     except ValueError: 
      # got something that could not be cast to a float 
      print("Input must be numeric.") 

此外,如果使用自己的代碼,那麼你正在使用python2沒有python3因爲你只有ISNUMERIC檢查後投這樣就意味着輸入被eval'd你"Unresolved attribute reference 'is numeric' for class 'float'".。如果是這種情況,請使用raw_input來代替輸入

相關問題