关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。
想改进这个问题?将问题更新为 on-topic对于堆栈溢出。
2年前关闭。
Improve this question
请让我知道我的 if 语句中出现无效语法错误的原因。该错误特别指向“如果”下方。
random_integer = random.randint(0,10)
i=3
while (i != 0):
try:
number = int(input("Enter your number between 0 to 10: "))
if number > random_integer:
print("Your number is greater than my number.")
i -= 1
print("You have now {} chance(s) left".format(i))
elif number < random_integer:
print("Your number is smaller than my number.")
i -= 1
print("You have now {} chance(s) left".format(i))
elif number == random_integer:
print("Congratulations! you guessed the correct number. You won the Game.")
print("Thanks for playing.")
break
except:
print("please enter an integer number from 0 to 10. Try again")
最佳答案
您得到的语法错误(正如其他人所提到的)是因为您的代码中有缩进(或缺少)。
Python 与其他语言的不同之处在于它不使用分号 (;) 或花括号 ({}) 来标记行尾或代码块的开始/结束。
它所做的是根据每行之前的空格数量来识别代码行。
通常,这意味着当您打开一个代码块时,您需要缩进它后面的行,以表明以下代码行与该特定代码块相关。
在您的情况下,您已经启动了一个 try/catch block ,但没有在其后缩进代码,因此您的 IDE 不知道它是 try/catch block 的一部分。
您可以通过按 Tab 一次或按空格键四次来缩进与您的 try/catch block 相关的行来解决此问题。
while (i <= 3):
try:
number = int(input("Enter your number between 0 to 10:" ))
if number > random_integer:
print("Your number is greater than my number.")
print("You have now {} chance(s) left".format(i-1))
elif number < random_integer:
print("Your number is smaller than my number.")
print("You have now {} chance(s) left".format(i-1))
elif number == random_integer:
print("Congratulations! you guessed the correct number. You won teh Game.")
print("Thanks for playing.")
break
关于python-3.x - Python IF 语句给出 "invalid syntax"错误。请让我知道可能是什么原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59711416/