玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python源码在guess错误后没按照预设效果执行

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

我是纯新手 也是看到《和孩子一起学编程》里的这个例子
其实那里面说了 要注意缩进
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

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

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

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

以下是示例代码(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!")

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd19626.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月24日 - 17时41分40秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules