这是我正在阅读的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
答案 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)
此代码存在一些问题。
elif
和if
应具有相同的缩进级别。tries
。input()
返回一个字符串;你应该把它转换成一个整数。<
和>
后,==
是多余的。<
,>
和==
涵盖了所有案例,因此您永远无法访问else
:这是逻辑的改写:
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