python - 这段代码,为什么在guess错误后,没有运行六次?
PHP中文网
PHP中文网 2017-04-17 13:06:12
[Python讨论组]
import random

secret = random.randint(1, 100)
guess = 0
tries = 0

print "AHOY! I'm the Dread Pirate Roberts, and I have a secret!"
print "It is 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
PHP中文网
PHP中文网

认证0级讲师

全部回复(2)
大家讲道理

短短一段代码实在有太多地方值得吐槽了。

首先,input()输入得到的变量一定是String类型的,是无法和Number进行比较的,必须先int一下。
其次,你的逻辑写的实在是有问题。在guess<secretguess>secret判断玩之后不就剩下guess==secret的情况么,然后你再后头又判断了一次是否相等。也就是说只要是不等的情况下你的代码会返回三行字符串,最开始判断大小于会返回一行,后面的不等于又会返回两行。这应该不是你要的结果。

把判断是否相等的代码归并到一块,把判断tries的代码归并到一块就没有问题了。

  • 是否相等:大于提示大了,小于提示小了,等于提示恭喜猜中了
  • 尝试次数:还能尝试就+1,不能就提示机会用完了并跳出循环

以下是示例代码(Python3版请自行转换到Python2):

#! /usr/bin/python3
import random

secret = random.randint(1, 100)
guess = 0
tries = 0

print("""
    AHOY! I'm the Dread Pirate Roberts, and I have a secret!
    It is a number from 1 to 99. I'll give you 6 tries.
""")

while True:
    if tries < 6: tries = tries + 1
    else:
        print("""
            No more guesses! Better luck next time, matey!
            The secret number was %s
        """ % secret,)
        break

    guess = int( 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!")

阿神

我是纯新手 也是看到《和孩子一起学编程》里的这个例子
其实那里面说了 要注意缩进
python是依靠缩进判断语句块

把上面 if guess < secret: 减少一个缩进就行了

if后接的是结果判断,在while循环完成游戏后再进行

import random

secret = random.randint(1, 100)
guess = 0
tries = 0

print "AHOY! I'm the Dread Pirate Roberts, and I have a secret!"
print "It is 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号