我是一名初学程序员,学习Python(使用版本2.7.4)并且我已经制作了这个数字猜谜游戏。到目前为止,这是我的代码:
import random
name = raw_input("Hi there! What\'s your name?\n")
print "Well, " + name + ", I am thinking of a number between 1 and 100"
number = random.randint(1,100)
guess = int(raw_input("Take a guess:\n"))
count = 1
while guess != number:
if guess < number:
print "Sorry, your guess is too low."
if guess > number:
print "Sorry, your guess is too high."
count += 1
guess = int(raw_input("Take another guess\n"))
print "Good job, %s! You guessed my number in %d guesses!" % (name ,count)
答案 0 :(得分:2)
对于第一个问题,请使用set跟踪以前的输入值:
seen = set()
while guess != number:
if guess < number:
print "Sorry, your guess is too low."
if guess > number:
print "Sorry, your guess is too high."
count += 1
while True:
guess = int(raw_input("Take another guess\n"))
if guess in seen:
print "Oops, you have guess than one before"
continue
else:
seen.add(guess)
break
对于第二个问题,您可以使用isinstance()函数,但没有太多需要。 int()函数将为您检查输入,如果没有得到整数输入,将引发异常。如果您愿意,可以捕获该异常并添加一条很好的错误消息:
try:
guess = int(raw_input("Take another guess\n"))
except ValueError:
print "Sorry, I expected an integer"
答案 1 :(得分:0)
问题一的答案列出了一个清单:
while run:
geusslist = []
number = raw_input("Make A Geuss")
geusslist.extend((number))
if print_nums:
print "You Have Guessed:"
print geusslist
如果此代码已运行并且播放器猜测10,20,30,40,50应返回
>>> You Have Geussed:
>>> [10, 20, 30, 40, 50]
关于问题二我认为&#39; Raymond Hettinger&#39;上面回答的非常好。