[英]How to make a greater/less than or equal to on python?
So I just started studying programming today and I tried to make a code about guessing the number from 1 to 10. but when I input 0 or 11, it also shows the message for guess > number
or guess < number
.所以我今天刚开始学习编程,我试图编写一个关于猜测从1到10的数字的代码。但是当我输入0或11时,它也显示
guess > number
或guess < number
的消息。
Here's my code:这是我的代码:
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!')
Here's the output:这是 output:
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 :
as you can see, it also prints the message.如您所见,它还会打印消息。 I input for the
guess > number
or guess < number
(on the 3rd and 6th line of the output).我输入
guess > number
或guess < number
(在输出的第 3 行和第 6 行)。 I noticed that the problem was that it should be greater than or equal to and less than or equal to, but I don't know how to do that.我注意到问题是它应该大于或等于和小于或等于,但我不知道该怎么做。
You could go for something like this:您可以拨打 go 进行以下操作:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.