我想在这里尝试使用 != 而不是 = (通过切换if
andelse
语句),以防我想添加一个 elif: after (如果输入的猜测值大于最大值,则可能是测试响应)。我不明白为什么它现在会引发警告/错误,或者该警告的含义。
为了澄清,代码运行并且似乎可以工作,但是我在用于编写/运行的 repl.it 中收到警告。
在第 3 行def make_guess
它说 - Redefining name 'guess' from outer scope (line 21)
<=这是什么意思?
然后在第 21 行max=int(input("Guess number between 1 and what?"))
它说Redefining built-in 'max'
[虽然我猜这不是问题,因为如果我重命名该变量maxi
,它不会显示第 21 行的警告]
原始代码:
import random
def make_guess(guess):
if guess == randomnumber:
print()
print("Congratulations, you guessed my number!")
else:
guess = int(input("Guess again?"))
make_guess(guess)
print("GUESS MY NUMBER")
print()
max = int(input("Guess number between 1 and what?"))
randomnumber = random.randint(1, max)
guess = int(input("What is your best guess?"))
make_guess(guess)
print("My number was", randomnumber)
新代码:
import random
def make_guess(guess):
if randomnumber != guess:
guess = int(input("Guess again?"))
make_guess(guess)
else:
print()
print("Congratulations, you guessed my number!")
print("GUESS MY NUMBER")
print()
max = int(input("Guess number between 1 and what?"))
randomnumber = random.randint(1, max)
guess = int(input("What is your best guess?"))
make_guess(guess)
print("My number was", randomnumber)