#python
#python
Вопрос:
Итак, я только сегодня начал изучать программирование и попытался создать код для угадывания числа от 1 до 10. но когда я ввожу 0 или 11, он также показывает сообщение для guess > number
or guess < number
.
Вот мой код:
number = 4
running = True
while running:
guess = int(input('Guess the number from 1 to 10 :'))
if guess == number:
print('Congrats, you guessed it right')
running = False
if guess > 10:
print('Choose from only 1 to 10!, Please try again')
if guess < 1:
print('Choose from only 1 to 10, Please try again')
if guess > number:
print('Sorry, a little lower than that, Please try again')
if guess < number:
print('Sorry, a little higher than that, Please try again')
else:
print('DONE!')
Вот результат:
Guess the number from 1 to 10 :0
Choose from only 1 to 10, Please try again
Sorry, a little higher than that, Please try again
Guess the number from 1 to 10 :11
Choose from only 1 to 10!, Please try again
Sorry, a little lower than that, Please try again
Guess the number from 1 to 10 :
как вы можете видеть, он также печатает сообщение. Я ввожу для guess > number
или guess < number
(на 3-й и 6-й строке вывода). Я заметил, что проблема заключалась в том, что оно должно быть больше или равно и меньше или равно, но я не знаю, как это сделать.
Комментарии:
1. Подсказка:
else
илиelif
разрешить вам запускать только одну ветвь кода.2. Посмотрите на использование
elif
3.
guess >= number
,..<=..
… https://docs.python.org/3/reference/expressions.html#value-comparisons .. docs.python.org/3/reference/lexical_analysis.html#operators
Ответ №1:
Вы могли бы пойти на что-то вроде этого:
number = 4
guess = -1
while guess != number: # When you find the number you exit the loop to print congrats.
try:
guess = int(input('Guess the number from 1 to 10 : '))
except ValueError: # Catch the possible ValueError if the user doesn't supply a number.
print('Enter a valid number!')
continue
if guess > 10 or guess < 1:
print('Choose from only 1 to 10!, Please try again')
elif guess > number: # Use elif in order not to print multiple messages.
print('Sorry, a little lower than that, Please try again')
elif guess < number:
print('Sorry, a little higher than that, Please try again')
print('Congrats, you guessed it right')