2

我为我的问题的简单性质道歉。

我正在通过“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

但是当我运行它时,它会告诉我每次猜测后的答案是什么,这是不应该的。应该是等到最后。

我只是想不通我做错了什么。我已经检查了每一行,或者至少,我认为我已经检查了。

如果有人能指出我哪里出错了,那就太好了。

4

2 回答 2

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
于 2012-09-03T23:32:28.253 回答
0

写这个的更好的方法可能是。然后你不必设置guess0循环之外

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
于 2012-09-03T23:43:02.353 回答