为啥我会收到此语法错误? (Python)
Posted
技术标签:
【中文标题】为啥我会收到此语法错误? (Python)【英文标题】:Why am I getting this syntax error? (Python)为什么我会收到此语法错误? (Python) 【发布时间】:2022-01-23 08:53:32 【问题描述】:这里是 Python 菜鸟。今天下午参加了“猜数字游戏”。 对我来说一切都很好,但我在第 26 行不断收到语法错误:
else player_number >= secret_number:
我已经尝试了所有方法,但我根本无法弄清楚。 感谢您的帮助。
import random, sys
secret_number = random.randint(1, 99)
countdown_timer = 7
print("This is a number guessing game.")
print("You have to guess a number between 1 and 99!")
print("You have 7 attempts to guess the correct number")
print("Good luck!")
print("\n")
print("Your first guess is: ")
while countdown_timer != 0:
player_number = int(input())
countdown_timer = (countdown_timer - 1)
if player_number == secret_number:
print("\n")
print("That's it!! The number was: " + secret_number)
print("\n")
print("Congratulations!")
print("Please try again.")
quit()
elif player_number <= secret_number:
print("Higher!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
else player_number >= secret_number:
print("Lower!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
print("You are out of guesses, sorry.")
print("The correct number was: " + secret_number)
print("Please try again.")
【问题讨论】:
什么是语法错误? 【参考方案1】:将 else 语句更改为 elif。 else 语句不带任何表达式。因此:
elif player_number >= secret_number:
print("Lower!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
在实际运行代码后,我看到您正在尝试连接整数和字符串,但这不起作用。要使其工作,请使用 f' 打印。
代码如下:
import random
secret_number = random.randint(1, 99)
countdown_timer = 7
print("This is a number guessing game.")
print("You have to guess a number between 1 and 99!")
print("You have 7 attempts to guess the correct number")
print("Good luck!")
print("\n")
print("Your first guess is: ")
while countdown_timer != 0:
player_number = int(input())
countdown_timer = (countdown_timer - 1)
if player_number == secret_number:
print("\n")
print(f"That's it!! The number was: secret_number") # f' print here
print("\n")
print("Congratulations!")
print("Please try again.")
quit()
elif player_number <= secret_number:
print("Higher!")
print(f"You have countdown_timer guesses left.") # here
print("Please enter your next guess: ")
elif player_number >= secret_number:
print("Lower!")
print(f"You have countdown_timer guesses left.") #here
print("Please enter your next guess: ")
print("You are out of guesses, sorry.")
print(f"The correct number was: secret_number") # and here
print("Please try again.")
【讨论】:
已解决!!!谢谢!【参考方案2】:我会用“else:”替换整行并添加注释:
if player_number == secret_number:
...
elif player_number <= secret_number:
...
else:
# player_number >= secret_number
...
【讨论】:
以上是关于为啥我会收到此语法错误? (Python)的主要内容,如果未能解决你的问题,请参考以下文章
为啥我会收到这个语法错误(false syntax error pyflakes)
为啥我会出现此错误:“数组”第 2 行或附近的语法错误:值数组?