Python 示例在测验期间而不是结束时重复答案

标签 python

对于我的问题的简单性,我深表歉意。

我正在学习“Hello World”,面向 child 和初学者的计算机编程 - 作者: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

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

我就是不知道自己做错了什么。我已经检查了每一行,或者至少我认为我已经检查过。

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

最佳答案

正确的缩进是关键。确保缩进循环内的内容,并保留循环后的内容不缩进。

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

关于Python 示例在测验期间而不是结束时重复答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12255068/

相关文章:

python - 检测字符串列表中的年份

python - 在 numpy 中迭代两个数组,没有 nditer?

python - 无法将记录插入 table_sensor_log 表 - 语法错误 - 无法将记录插入表 - 42000

python - 使用 web2py 从 POST ajax 调用获取数据

python - 使用随机生成的变量对函数进行 doctest

python - 如何按索引对列表进行分组?

python - 使用 Python 在文本中查找超链接(twitter 相关)

python - 子进程 pid 与 ps 输出不同

python - 在 Pandas 中创建百分位桶

python - 如何使用 python 更改 couchdb 数据库的权限