2016-02-28 36 views
0

我的代碼:除非你進入初學者的Python - 到目前爲止有一個字符串或一個變量在一個循環接聽

prompt = "\nEnter 'quit' when you are finished." 
prompt += "\nPlease enter your age: " 

while True: 
    age = input(prompt) 
    age = int(age) 

    if age == 'quit': 
     break 
    elif age <= 3: 
     print("Your ticket is free") 
    elif age <= 10: 
     print("Your ticket is $10") 
    else: 
     print("Your ticket is $15") 

程序運行正常「退出」來結束循環。我明白age = int(age)將用戶輸入定義爲一個整數。我的問題是,如何將其更改爲不將「quit」視爲整數,並在輸入「quit」時結束循環。

回答

1

如果age'quit',反正你會打破。因此,您可以使用if替代下一個。只要你做到這一點,無論如何,你可以把它認爲if後一個int:

while True: 
    age = input(prompt) 

    if age == 'quit': 
     break 
    age = int(age) 

    if age <= 3: 
     print("Your ticket is free") 
    elif age <= 10: 
     print("Your ticket is $10") 
    else: 
     print("Your ticket is $15") 

你或許應該照顧的情況下,當用戶鍵入別的東西,但是,所以我建議如下:

while True: 
    age = input(prompt) 

    if age == 'quit': 
     break 
    elif not age.isdigit(): 
     print("invalid input") 
     continue 

    age = int(age) 

    if age <= 3: 
     print("Your ticket is free") 
    elif age <= 10: 
     print("Your ticket is $10") 
    else: 
     print("Your ticket is $15") 
0

我在這裏實際上會介紹一個try/except

您的應用程序的主要目標是收集年齡。所以,用一個try來包裝你的輸入,除非總是得到一個整數。如果您收到ValueError,則會進入您的例外區塊並檢查是否輸入了quit

該應用程序會告訴用戶它正在退出並爆發。但是,如果用戶沒有輸入quit,而是輸入其他字符串,則會告訴您該條目無效,並且它會繼續詢問用戶有效的年齡。另外,爲了確保您永遠不會錯過可以使用不同情況輸入的「退出」消息,您始終可以將輸入設置爲lower,以始終比較字符串中的相同套管。換句話說,當您檢查條目爲quit時,請執行age.lower

這裏是一個工作演示:

prompt = "\nEnter 'quit' when you are finished." 
prompt += "\nPlease enter your age: " 

while True: 
    age = input(prompt) 
    try: 
     age = int(age) 
    except ValueError: 
     if age.lower() == 'quit': 
      print("Quitting your application") 
      break 
     else: 
      print("You made an invalid entry") 
      continue 

    if age <= 3: 
     print("Your ticket is free") 
    elif age <= 10: 
     print("Your ticket is $10") 
    else: 
     print("Your ticket is $15") 
相關問題