2017-07-27 42 views
-3

嗨,我正在學習python,我卡在製作一個年齡計算器。小於符號的基本Python語法錯誤

我不得不作出它要求用戶在未來幾年進入他們的年齡年齡計算器,如果用戶是100或以上,它告訴他們「你已經變成100!」。否則,如果他們小於0,告訴他們「當你出生時再試一次!」。如果這兩種情況都不是這樣,則計算年數,直到它們變爲100,並輸出消息「您將在x年內100次!」 (其中「x」被替換爲100之前的年數)。我必須使用if/elif/else語句來解決這個問題。

我花了幾年時間研究,使用PEP8和我發現的東西,但還是無法弄清楚如何做解決這個問題,或者如果我在正確的軌道上。先謝謝你!

1. age = input("Enter your current age in years: ") 
2. if output = <100 input("You will be 100 in years!") 
3. 
+1

如果'x'小於'y',則x Zinki

回答

1
age = int(input('Enter your age')) 
if age < 0: 
    print("Try again when you are born!") 
    exit(1) 

if age > 100: 
    print("You've already turned 100!") 
else: 
    print("You will be 100 in", str(100-age) " ,years!") 
1
age = int(input("Enter your current age in years: ")) 
if age < 100: 
    output = "You will be 100 in {} years".format(100-age) 
else: 
    output = "You've already turned 100!" 

print(output) 

解釋這是什麼一樣:

  1. 這蒙上年齡爲int如果可能的話,否則它是一個字符串
  2. 然後,如果用戶是它檢查小於100歲(而不是< = <),如果是這樣創建的輸出串,並使用格式操作來代替{}
  3. 否則,輸出字符串是「你已經變成100」
  4. 它打印輸出
2

的問題是,您使用的是兩個分隔等號(=)和小於(<)空間。或者你想要做小於或等於(<=)(按該順序),或者你只想做小於(<),從而完全刪除等號。

1
age = input('Enter your age:') 
if age < 0:print("Try again when you are born!") 
elif age >= 100:print("You've already turned 100!") 
else:print("You will be 100 in" + str(100-age) + "years!") 
1

你可以按照這個過程:

def age_calculator(age): 
    if age < 0: 
     print("Try again when you are born!") 
     return 0 
    elif age >= 100: 
     print("You've already turned 100!") 
    else: 
     print("You will be 100 in", str(100 - age), "Years!") 

if __name__ == '__main__': 
    while True: 
     age = input("Enter your current age in years: ") 
     try: 
      age = int(age) 
      break 
     except: 
      print("Please input an integer") 
    age_calculator(age) 
0
age = input('Enter your age:') 
print('Try again when you are born!') if age<0 else ("You've already turned 100!") if age>=100 else ("You will be 100 in " + str(100-age) + " years!") 

我知道這是凌亂。

我很無聊。

理論上起作用。

也正好顯示PEP8不回答這個問題真的很重要。

而且你應該嘗試從某處,將引導您正確地學習。

並給予好評,並在這裏接受很好的答案(不是我的,除非你發笑)。

Byebye。

Jklol。

但並非如此。

現在再見。