elif语句出错

时间:2011-12-23 13:18:45

标签: python if-statement

这是我正在阅读的Python书中的一个例子。当我尝试运行该程序时出现错误,当我检查错误elif的代码时,会以红色突出显示。我正在使用Python 2.5进行编程。

import random

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

print "It is a number between 1 and 99. I'll give you six tries. "

while guess != secret and tries < 6:
    guess = input("What's your guess? ")
    if guess < secret:
        print "Too low!"
        elif guess > secret:
            print "Too high"
            tries = tries + 1
            if guess == secret:
                print "Correct! You found my secret!"
                else:
                    print "No more guesses! Better luck next time!"
                    print "The secret number was", secret 

3 个答案:

答案 0 :(得分:5)

Python是缩进敏感的。

import random

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

print "It is a number between 1 and 99. I'll give you six tries. "

while guess != secret and tries < 6:
    guess = input("What's your guess? ")
    if guess < secret:
        print "Too low!"
    elif guess > secret:
        print "Too high"
        tries = tries + 1
    elif guess == secret:
        print "Correct! You found my secret!"
    else:
        print "No more guesses! Better luck next time!"
        print "The secret number was", secret 

编辑:我知道这里仍然存在错误,例如tries = tries + 1应该是代码中的其他位置。但是这个版本至少没有给出语法错误。

答案 1 :(得分:1)

问题出在你的缩进上。

而不是:

if foo:
    foobar()
    elif bar:
        barbaz()

应该是:

if foo:
    foobar()
elif bar:
    barbaz()    

已修复,您的代码将如下所示(注意,我还在最后修复了else以正常工作):

import random

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

print "It is a number between 1 and 99. I'll give you six tries. "

while guess != secret:
    if tries < 6:
        guess = input("What's your guess? ")
        if guess < secret:
            print "Too low!"
        elif guess > secret:
            print "Too high"
            tries = tries + 1
        elif guess == secret:
            print "Correct! You found my secret!"
    else:
        print "No more guesses! Better luck next time!"
        print "The secret number was", secret
        break

答案 2 :(得分:1)

此代码存在一些问题。

  1. elifif应具有相同的缩进级别。
  2. 您只会在过高的情况下增加tries
  3. input()返回一个字符串;你应该把它转换成一个整数。
  4. 在测试<>后,==是多余的。
  5. 由于<>==涵盖了所有案例,因此您永远无法访问else
  6. 这是逻辑的改写:

    while guess != secret and tries < 6:
        guess = int(input("What's your guess? "))
        if guess < secret:
            print "Too low!"
        elif guess > secret:
            print "Too high"
        tries = tries + 1
    
    if guess == secret:
        print "Correct! You found my secret!"
    else:
        print "No more guesses! Better luck next time!"
        print "The secret number was", secret