2014-02-10 185 views
1

運行這兩個選項所以我很新的編程,我使用Python(v3.33),以創建像這樣的小程序:在猜謎遊戲

option = input('What Game Would You Like To Play? A, B, C, or D? ') 
option == 'A' 
guess = int(input('Guess a number: ')) 
while True: 
    while guess != 100: 
     if guess > 100: 
      print('Too High... Try Again') 
     if guess < 100: 
      print('Too Low... Try Again') 
     guess = int(input('Guess a number: ')) 
    if guess == 100: 
     print('You Win') 
     break 

option == 'B' 
guess = int(input('Guess a number: ')) 
while True: 
    while guess != 50: 
     if guess > 50: 
      print('Too High...Try Again') 
     if guess < 50: 
      print('Too Low... Try Again') 
      guess = int(input('Guess a number: ')) 
    if guess == 50: 
     print('You Win') 
     break 

這是我problem-我想要的用戶可以選擇'A'或'B'(我會加入'C'和'D',但想先解決問題),但程序會自動通過'A'然後到'B' :我如何得到它,以便用戶可以選擇'A'和'B'。 另外,我該如何做到這一點,以便用戶如果想再次運行,可以選擇「是」或「否」。 感謝

+3

添加代碼,如果你想要更多的人來幫助,改變你的問題與有關問題相關的標題。 –

+0

if option =='A':may be? –

+0

沒錯,是的 - 謝謝。 – user3291108

回答

1

包住整個事情在一個while循環:

while True: 

    option = input('What Game Would You Like To Play? A, B, C, or D (Q to quit)? ').upper() # this can accept both lower and upper case input 

    if option == 'Q': 
     break 

    elif option == 'A': 
     Do some code 

    elif option == 'B': 
     Do some code 

    elif option == 'C': 
     Do some code 

    elif option == 'D': 
     Do some code 

    else: 
     print ("You didn't enter a valid choice!") 

關於你的代碼:

option == 'A' 

該行只是簡單地測試選項是否等於 'A'。它返回一個TrueFalse。 您想要測試選項的實際值。因此,上面的if陳述。

你的代碼只是運行所有場景,因爲你沒有提供應該發生事情的條件。只有當option == 'A'應該代碼適合這種情況下運行。只有當option == 'D'應該代碼運行。只有當option == 'Q'應該主循環中斷。這是什麼時候使用if聲明的一個很好的例子。

編輯:

至於你的評論,你可以做到以下幾點:

option = input('What Game Would You Like To Play? A, B, C, or D (Q to quit)? ') 
if option == 'a': # upper is gone, you can specify upper or lower case 'manually' 
    do this 
if option == 'A': 
    do this 

或者

if option in ['a', 'A']: # this basically same effect as my original answer 
     do something 

退房的str.upper()方法是如何工作的here

+0

謝謝。很快,'.upper()'是什麼意思? – user3291108

+0

這意味着即使有人輸入小寫字母,它也會轉換爲大寫字母以進行檢查。所以如果他們輸入'b'或'q'。它變成'B'或'Q'。 – Totem

+0

@ user3291108,嘗試習慣像http://docs.python.org/3/search.html?q=upper&check_keywords=yes&area=default這樣的網站,他們會不時地提供幫助。 – icedwater

1

它會帶您通過這兩個選項,因爲您沒有使用該選項的檢查。

當你的代碼是技術上檢查option == 'A'再後來option == 'B',它不檢查一個或另一個,而不是與支票做任何事情。

相反,你會想:

option = input('What Game Would You Like To Play? A, B, C, or D? ') 

if option == 'A': 
    guess = int(input('Guess a number: ')) 
    .... 
    break 
elif option == 'B': 
    guess = int(input('Guess a number: ')) 
    .... 
    break 

elif在那裏,而不是else,所以你有空間,爲選項C和D.

+0

謝謝你的幫助 – user3291108