Python错误:缩进不匹配任何外部缩进限制

0 投票
2 回答
1267 浏览
提问于 2025-04-16 19:01

如你所见,我是编程新手,刚开始学习Python。上面提到的错误发生在代码中标记的那一行。
我该如何解决这个问题呢...

import random

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

print "AHOY! I am the dead pirate Roberts, and I ahve a secret!"
print  "It is a number from 1 to 99. I will give you six tries."

while guess  !=secret and tries <6:
    guess= input("what's yer guess? " )
    if  guess < secret :
                 print "Too Low, ye curvy 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" 

2 个回答

0

在Python中,你的代码块之间必须保持一致的缩进。

if guess < secret:这个代码块中,缩进的空格比在while代码块中要多很多。

正确的代码是:

while guess  !=secret and tries <6:
    guess= input("what's yer guess? " )
    if  guess < secret :
        print "Too Low, ye curvy 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" 
2

在Python中,缩进用来表示代码块。你的代码缩进不正确(提到的if的缩进和之前的任何代码块都不对齐;从代码的快速浏览来看,至少还有一个错误)。

下面是一个简短明了的解释,讲述了Python中缩进是如何工作的:http://diveintopython.net/getting_to_know_python/indenting_code.html

撰写回答