if语句中的空闲语法错误

2024-04-29 15:48:00 发布

您现在位置:Python中文网/ 问答频道 /正文

IDLE正在将if语句注册为语法错误。我的代码如下:

  import random ;\
    print("Welcome to the fortune cookie simulator") ;\
    print("\n\nThe fortune cookie minus the good part..") ;\
    input("\n\n\nPress enter to recieve your fortune!") ;\
    fortune = random.randint(1, 5) ;\
    if fortune==1:  ;\
      print("You will die today") ;\

Tags: theto代码importifcookierandom语句
2条回答

您使用显式语句分隔符和行延续创建了一个大的oneliner。它很难看,而且很容易出错。我假设你在Python3号工作。在python2中,input()要求用户输入有效的python表达式。如果使用python2,请改用raw_input()。在

import random
print("Welcome to the fortune cookie simulator")
print("\n\nThe fortune cookie minus the good part..")
input("\n\n\nPress enter to recieve your fortune!")
fortune = random.randint(1, 5)
if fortune == 1:
    print("You will die today")

由于if fortune==1:不是一个完整的语句,因此不能用;来终止它。正确的if语句的一行形式是

if fortune==1: print("...")

那么,将其分成两行就可以简单地使用普通Python

^{pr2}$

为什么要把多个语句放入一个逻辑行是另一个问题。在

相关问题 更多 >