2013-10-01 10 views
-1

저는 문자 맞추기 게임을 파이썬으로 완성했습니다. 사용자가 선택할 수있는 문자는 "a, b, c 및 d"입니다. 나는 그들에게 5 번 시도하는 법을 알고 있지만 올바른 편지 중 하나를 추측 할 때, 나는 그 루프를 깨고 그 선수를 축하 할 수 없다.루프를 벗어나는 방법을 알아낼 수 없습니다.

g = 0 
    n = ("a", "b", "c", "d") 

    print("Welcome to the letter game.\nIn order to win you must guess one of  the\ncorrect numbers.") 
    l=input('Take a guess: '); 
    for g in range(4): 

    if l == n: 
     break 

     else: 
      l=input("Wrong. Try again: ") 


    if l == n: 
      print('Good job, You guessed one of the acceptable letters.') 

    if l != n: 
      print('Sorry. You could have chosen a, b, c, or d.') 
+4

들여 쓰기를 수정하십시오. – TerryA

답변

0

먼저 문자를 튜플과 비교합니다. 예를 들어 if l == n을 입력하면 if 'a' == ("a", "b", "c", "d")이 표시됩니다.

원하는 것은 여기 루프가 while입니다.

guesses = 0 
while guesses <= 4: 
    l = input('Take a guess: ') 
    if l in n: # Use 'in' to check if the input is in the tuple 
     print('Good job, You guessed one of the acceptable letters.') 
     break # Breaks out of the while-loop 
    # The code below runs if the input was wrong. An "else" isn't needed. 
    print("Wrong. Try again") 
    guesses += 1 # Add one guess 
    # Goes back to the beginning of the while loop 
else: # This runs if the "break" never occured 
    print('Sorry. You could have chosen a, b, c, or d.') 
0

이 코드의 대부분을 유지하지만 목표에 부합하도록 재 배열 : 우리는 정말하기 위해, 루프 변수의 값에 대한 상관 없어

n = ("a", "b", "c", "d") 
print('Welcome to the letter game. In order to win') 
print('you must guess one of the correct numbers.\n') 

guess = input('Take a guess: '); 
for _ in range(4): 
    if guess in n: 
     print('Good job, You guessed one of the acceptable letters.') 
     break  
    guess = input("Wrong. Try again: ") 
else: 
    print('\nSorry. You could have chosen a, b, c, or d.') 

을 우리가 '사용이 명시 적 _ '을 입력하십시오.

관련 문제