首页 > 这段代码,为什么在guess错误后,没有运行六次?

这段代码,为什么在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

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

首先,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!")


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