gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:13 25 4
gpt4 key购买 nike

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

我正在学习“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com