我为我的问题的简单性而道歉。
我正在通过“Hello World”,为孩子和初学者进行计算机编程 - 由Warren和Carter Sande工作。
第一章的第二个例子是这个数字例子,是一个盗版数测验。编程语言是Python。
它应该允许6次猜测,除非首先猜到正确的数字。我想对你们来说,代码可以自我解释。
import random
secret = random.randint(1,99)
guess = 0
tries = 0
print "AHOY! I'm the dread Pirate Roberts, and I have a secret!"
print "It's a number from 1 to 99. I'll give you 6 tries."
while guess != secret and tries < 6:
guess = input("What's yer guess? ")
if guess < secret:
print "Too low, ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries +1
if guess == secret:
print "Avast! Ye got it! Found my secret, ye did!"
else:
print "No more guesses! Better luck next time, matey!"
print "The secret number was", secret
但是当我运行它时,它会告诉我每次猜测后的答案是什么,这是不应该的。它应该等到最后。
我无法弄清楚我做错了什么。我检查了每一行,或者至少,我认为我有。
如果有人能够指出我出错的地方,那就太棒了。
答案 0 :(得分:3)
正确的缩进是关键。确保你缩进循环内的东西,并在循环后缩进后留下东西。
while guess != secret and tries < 6:
guess = input("What's yer guess? ")
if guess < secret:
print "Too low, ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries + 1
if guess == secret:
print "Avast! Ye got it! Found my secret, ye did!"
else:
print "No more guesses! Better luck next time, matey!"
print "The secret number was", secret
答案 1 :(得分:0)
更好的方法是写这个。然后,您不必在循环外将guess
设置为0
for tries in range(1, 6):
guess = input("What's yer guess? ")
if guess < secret:
print "Too low, ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
else:
print "Avast! Ye got it! Found my secret, ye did!"
break
else:
print "No more guesses! Better luck next time, matey!"
print "The secret number was", secret