В этом коде пользователь должен угадать случайно выбранное компьютером число от 0 до 100. Проблема в том, что цикл while вообще не выполняется. Все работало, пока я не поместил этот блок кода в цикл while, чтобы он повторялся до тех пор, пока пользователь не угадает число или не закончатся попытки. Как заставить цикл while работать? Пожалуйста, я новичок в питоне.
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while number_guessed:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
Это должно работать:
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while number_guessed == False:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
Ошибка с вашим кодом заключалась в том, что когда вы используете цикл while
, такой как while somevariable
и somevariable
равно False
, цикл while
не будет выполняться. Вы также можете просто попробовать while not number_guessed
numbers_guessed
является ложным, и цикл while должен быть истинным для запуска. Поэтому измените цикл while или переменную.
Код:
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while not number_guessed:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
!number_guessed
- это не то, как вы пишете логическое отрицание в Python (это SyntaxError
). Вы хотите not number_guessed
.
Спасибо @Blckknght. Я больше привык к похожему синтаксису скрипта GD. я изменю это
Вы определяете number_guessed
как False
, поэтому цикл вообще не выполняется. Попробуйте while not number_guessed
.
в то время как not number_guessed действительно решил проблему, но он запутался в использовании флагов с циклом while. Означает ли это, что флаг всегда должен быть установлен как True? Цикл while должен продолжать работать до тех пор, пока number_guessed не станет True (пользователь получил правильное число, поэтому игра должна остановиться)
Вы всегда хотите запустить цикл с условием True
, и какое-то событие внутри цикла должно установить его в False
. Если у вас нет этого, вы будете зацикливаться навсегда!
в то время как not number_guessed действительно решил проблему, но он запутался в использовании флагов с циклом while. Означает ли это, что флаг всегда должен быть установлен как True? Цикл while должен продолжать работать до тех пор, пока number_guessed не станет True (пользователь получил правильный номер, поэтому игра должна остановиться). Я установил number_guessed как False ... поэтому, если я затем напишу while не number_guessed, я ожидал, что флаг не будет установлен как True. И если True, то это означает, что пользователь правильно угадал число, поэтому игра должна закончиться, что не так. Почему я в замешательстве, а?
@Sethoo: переменная флага может работать в любом случае. состояние (который может быть либо просто флагом, либо выражением вроде not flag
) должен быть True
, если цикл должен продолжать работать (включая запуск в самый первый раз). Вы можете называть свои переменные как хотите, стоимость выражения not
тривиальна (по сравнению с другими вещами, такими как ввод-вывод).
not number_guessed
будет намного лучше, чемnumber_guessed == False
.