2012-10-28 25 views
3

程序的要點是詢問用戶的名字(自動大寫第一個字母)。新手卡住,容易「同時」在Python中重複

然後它會詢問年齡和性別。如果年齡超過130或負數,它會拋出一個錯誤

該程序應該打印出所有的信息,但我無法弄清楚while循環條件。任何人都可以幫我弄清楚while循環的條件嗎?

-edit-雖然Pastebin的鏈接已被編輯出來,但我認爲那裏有重要的信息。所以,我還是會給你的鏈接: http://pastebin.com/UBbXDGSt

name = input("What's your name? ").capitalize() 
age = int(input("How old are you ")) 
gender = input("From what gender are you? ").capitalize() 

while #I guess I should write something behind the "while" function. But what? 
    if age >= 130: 
     print("It's impossible that you're that old. Please try again!") 
    elif age <= 0: 
     print('''It should be logical that ages are written in positive numbers! Well, try again! =)''') 

age = int(input("How old are you? ")) 

print("Your name is ",name, ". You are ", age, "years old." "\nYou are ", gender, ".") 
+0

什麼讓你覺得在這裏需要一個循環,你期待什麼發生? –

+0

你不需要一個while循環。 if語句就足夠了。 –

+0

我認爲目標是要求用戶的年齡**,而**他們輸入了無效值,直到他們輸入了有效的值。 –

回答

1

你可以有,如果有一個有效輸入某個設定關閉/開啓的標誌。這將解決您的while循環

name = input("What's your name? ").capitalize() 
gender = input("From what gender are you? ").capitalize() 
ok = False #flag 
while not ok: 
    age = int(input("How old are you ")) 
    if age >= 130: 
     print("It's impossible that you're that old. Please try again!") 
    elif age <= 0: 
     print('''It should be logical that ages are written in positive numbers! Well, try again! =)''') 
    else: 
     ok = True 
print("Your name is ",name, ". You are ", age, "years old." "\nYou are ", gender, ".") 
+1

用'while(ok是False)'或'while ok'替換你的while條件。 – rantanplan

+0

那麼,它的工作..種。但..這是我得到的:http://pastebin.com/Rrmg4ZY1。所以它會從頭開始。但是如果我想讓它再次問這個年齡呢?如果它獲得了正確的年齡,那麼它將開始打印所有的東西。 – user1780169

+0

然後只詢問年齡@ user1780169 –

0

這裏通常使用while True的問題。

while True: 
    age = int(input("How old are you? ")) 

    if age >= 130: 
     print("It's impossible that you're that old. Please try again!") 
    elif age <= 0: 
     print('''It should be logical that ages are written in positive numbers! Well, try again! =)''') 
    else: 
     break 

這將重複的問題,直到它得到一個可以接受的答案,在這種情況下break將跳出循環。

爲了完整性,您還應該檢查他們是否輸入了任何內容,並輸入了數字。在這裏,我還將使用continue,它將從頭開始重新啓動循環,忽略其餘代碼。這是一個很好的例子:

while True: 
    age = input("How old are you? ") 
    if not age: 
     print("Please enter your age.") 
     continue 
    try: 
     age = int(age) 
    except ValueError: 
     print("Please use numbers.") 
     continue 

    if age >= 130: 
     print("It's impossible that you're that old. Please try again!") 
    elif age <= 0: 
     print('''It should be logical that ages are written in positive numbers! Well, try again! =)''') 
    else: 
     break 
+0

所以這裏是我的代碼到目前爲止: http://pastebin.com/des9qFiL(對不起,我無法將代碼複製到我的文章。此論壇似乎並沒有我會花時間學習格式化,但現在,這裏是鏈接。) 但事情是,它不會接受任何性別價值,我已經preentered。例如,如果我輸入「男性」,它會再次詢問我的性別。 – user1780169

+0

@ user1780169:這是一個不同的問題,因此是一個不同的問題。但是你使用的邏輯是完全錯誤的。編程語言不是自然語言。 –