[英]I'm really new to Python, and I was wondering why my “Else:” isn't working
import random
number = 50
guess = raw_input("Try to guess my number...")
while guess!=number:
if guess>number:
print "Lower"
elif guess==number:
print "Correct, you win!"
else:
print "Higher"
guess = raw_input("Try again...")
I'm really new, and I'm wondering why it won't display "Higher" when the number I input is less than the number, plus, how can I make the number random, since randrange(1,100) won't work 我真的很新,我想知道为什么当我输入的数字小于数字时,为什么它不会显示“高”,再加上我如何使数字随机,因为randrange(1,100)无法正常工作
It's not working because raw_input
returns a string. 它不起作用,因为
raw_input
返回一个字符串。
"50" == 50 # False!
You will need to ensure you are checking for equality of the same types. 您将需要确保检查相同类型的相等性。 Try converting to an int first:
首先尝试转换为int:
int(raw_input("Try to guess my number..."))
Of course this will throw an exception if you try to convert a non-numeric string to an int, so you will need some error-handling as well: 当然,如果您尝试将非数字字符串转换为int,这将引发异常,因此您还需要一些错误处理:
valid_num = False
while not valid_num:
guess = raw_input()
try:
guess_num = int(guess)
valid_num = True
except ValueError:
print "Please enter a valid number"
while guess!=number:
if guess>number:
print "Lower"
elif guess==number:
print "Correct, you win!"
else:
print "Higher"
First of all when you use raw_input("Try to guess my number...")
ir returns a string and str!=int
in any case so you were running an infinite while guess!=number:
loop, as the condition would always hold true for comparison of a string and an integer. 首先,当您使用
raw_input("Try to guess my number...")
ir会返回字符串和str!=int
,因此您在无限期运行while guess!=number:
循环,因为条件总是对于字符串和整数的比较,为true。
Another thing was contradicting statements of while
and elif
, when you are running a while condition with while guess!=number:
then how can you expect this elif guess==number:
statement to run inside the while statement , So the answer would be handle this case outside the while
loop. 另一件事是
while
和elif
语句矛盾,当您运行带有while guess!=number:
的while条件时while guess!=number:
那么如何期望这个elif guess==number:
语句在while语句中运行,所以答案将是handle这种情况在while
循环之外。
import random
number = 50
guess = int(raw_input("Try to guess my number..."))
while guess!=number:
if guess>number:
print "Lower"
else:
print "Higher"
guess = int(raw_input("Try again..."))
print "Correct, you win!"
raw_input returns a string. raw_input返回一个字符串。 You will want to convert that to an int for your comparison:
您将需要将其转换为int以便进行比较:
guess = int(raw_input("Try to guess my number..."))
a str
will never == an int
一个
str
永远不会==一个int
About your randrange problem: 关于您的randrange问题:
You should use random.randint(a,b) instead. 您应该改用random.randint(a,b)。 It chooses a random integer between the number a and b (exclusive, I think.)
它在数字a和b之间选择一个随机整数(我认为是排他的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.