将其转换为数字
#Write a short program that will do the following
#Set a value your favorite number between 0 and 100
#Ask the user to guess your favorite number between 0 and 100
#Repeat until they guess that number and tell them how many tries it took
#If the value they guessed is not between 0 and 100
#tell the user invalid guess and do not count that as an attempt
我的问题是,即使用户猜测0到100之间的数字,它仍然打印出"无效猜测"。再试一次"。我如何控制我的循环跳过打印语句和问题重复,如果它是可接受的输入(1-100)?提前感谢!
favoriteNumber = 7
attempts = 0
guess = raw_input("Guess a number between 0 and 100: ")
if (guess < 0) or (guess > 100):
print "Invalid guess. Try again"
guess = raw_input("Guess a number between 0 and 100: ")
attempts1 = str(attempts)
print "it took " + attempts1 + "attempts."
使用input而不是raw_input,所以你得到的是整数而不是字符串
favoriteNumber = 7
attempts = 0
while True:
guess = input("Guess a number between 0 and 100: ")
if (guess < 0) or (guess > 100):
attempts=attempts+1
print "Invalid guess. Try again"
else:
attempts=attempts+1
break
attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."
在Python 2.7.10中,如果你不将字符串转换为整数,它会接受它,但所有适用于数字的规则都会返回false。下面是一个工作示例:
favoriteNumber = 7
attempts = 0
guess = raw_input("Guess a number between 0 and 100: ")
if (int(guess) < 0) or (int(guess) > 100):
print "Invalid guess. Try again"
guess = raw_input("Guess a number between 0 and 100: ")
attempts1 = str(attempts)
print "it took " + attempts1 + " attempts."
在Python 3.4中,原始代码会产生一个错误,告诉您它是字符串而不是整数。但是,正如Paul所说,您可以将raw_input放在int()命令中。
你raw_input返回一个字符串,它总是>
100。使用int(raw_input())