2017-04-17 42 views
0

我覺得標題說明了一切,但我給你的代碼時,我有一些問題。試圖讓一個年齡計算器,而是試圖讓錯誤「行」

stop=0 
while stop != 'q': 
print("Age calculator") 
name = input("Name: ") 
print("Type in your age") 
age = input("Age: ") 

months = age * 12 
days = age * 365 
weeks = age * 52 
hours = days * 24 
minutes = age * 525948 
seconds = age * 31556926 

if type(age) == int: 
    print (name, "lives for", months, "months", weeks, "weeks", days, "days", hours, "hours", minutes, "minutes and", seconds, "seconds") 

else: 
    print("Please type in a number") 


print() 
print("Try again? Press ENTER") 
print("Quit? Press 'q' and then ENTER") 
print() 
stop = input() 

所以事情是,我希望它給你個月,周,日等 現在我知道如何做到這一點,但現在我想做一個行會說:請輸入在一個數字。如果用戶輸入字符而不是數字。當我每次輸入一個數字時,上面運行這段代碼時,它會給我一行「請輸入一個數字」,並且當我輸入一個字符時,它會執行相同的操作。

我在做什麼錯在這裏?

+0

'months','days'等分配了哪些值? –

+0

你是什麼意思?我很抱歉,我剛剛開始使用Python。 – Dylan

+0

'輸入()'返回字符串,而不管該輸入是否是數字或字符集。這就是爲什麼你的'if type(age)== int'失敗。 –

回答

0

輸入()語句後接受所有類型的輸入爲字符串,所以即使你輸入一個整數這將是一個字符串,如「1」,所以你需要強制轉換給定的輸入()爲INT()兩種類型的投它單獨或如果你直接在輸入(強制轉換)語句,然後它會創建異常類型的錯誤,所以你可以使用嘗試捕捉奧拓重複程序。所以如果你使用try catch,那麼代碼將會是。

status="" 
try: 
    while True: 
      print("Age calculator") 
      name = input("Name: ") 
      print("Type in your age") 
      age = input("Age: ") 
      age=int(age) 
      months = age * 12 
      days = age * 365 
      weeks = age * 52 
      hours = days * 24 
      minutes = age * 525948 
      seconds = age * 31556926 
      print (name, "lives for", months, "months", weeks, "weeks", days, "days", hours, "hours", minutes, "minutes and", seconds, "seconds") 
     print("Try again? Press ENTER") 
     status = input("Quit? Press 'q' and then ENTER") 
     if status = "q": 
       break # terminates program if "q" is entered. 
except TypeError: 
      print("Please type in a number for age") 
      continue #runs program till "q"is passed as age. 
except: 
    raise # this raises error if something goes wrong 
+0

感謝您的幫助! – Dylan

1

當您在輸入讀取它總是讀取爲字符串。你需要投你的輸入爲int喜歡

int(input("Age: ")) 

需要注意的是,如果用戶輸入一個字母而不是數字,要解決這個問題,而無需更改代碼太多,你可以讓你的輸入語句,因爲這將打破他們是否將您的if語句更改爲以下內容。

try: 
    age = int(age) 
    print statement 

except ValueError: 
    print("Please type in a number") 

要記住的另一個重要的事情是,在你的代碼中有作用於時代運營商之前,它被分配給一個int,這意味着

age * 12 

實際上給你一個STR(「555555555555 '如果年齡通過了5)而不是一個數字。爲了解決這個問題,你應該陳述移入嘗試讓他們被稱爲數轉換爲整數

+0

感謝您的幫助! – Dylan