为什么我在使用IF、ELIF和ELSE时出现语法错误?

2024-06-17 08:22:18 发布

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

这是我的准则

    running = True
    while running:
        print("Open Supply Drop?.")
    answer = input()
    if answer == ("Yes"):
       print("Please wait 3 seconds...")
       import time
      time.sleep(3)
      import random
      callingcard =     ['BootsOnTheGround', 'TitanBaseCamp', 'TitanFacility', 'TitanicStorm', 'TitanicCanyon', 'TitanSandstorm', 'ToTheShip', 'AsteroidMines', 'TheSteelDragon', 'C6Assembly', 'C12Patrol']
      print("You got...")
      print(random.choice(callingcard)

    elif answer == ("yes"):
      print("Please wait 3 seconds...")
      import time
      time.sleep(3)
      import random
      callingcard = ['BootsOnTheGround', 'TitanBaseCamp', 'TitanFacility', 'TitanicStorm', 'TitanicCanyon', 'TitanSandstorm', 'ToTheShip', 'AsteroidMines', 'TheSteelDragon', 'C6Assembly', 'C12Patrol']
      print("You got...")
      print(random.choice(callingcard))
    else:
      print("Please wait 3 seconds...")
      import time`enter code here`
      time.sleep(3)

如果,elif和else有语法错误?我只改变了一些东西,而且完美地工作了,但是现在不管怎样,它都是这样的,是不是和缩进有关?在


Tags: answerimporttimesleeprandomrunningsecondsprint
3条回答

如前所述,您在一行中缺少一个paren。你有几个问题,所以我写了一个干净的版本

  • 在文件顶部导入一次
  • 常量callingcard列表已从循环中拉出。它被重写为一个不可变的元组(列表暗示您计划修改)和 添加新行以保留行数<;80个字符
  • 使用break代替while中的哨兵值
  • 缩进所有4个空格
  • 代码不是为了允许Yesyes而重复的

这个例子

import time
import random

callingcard = ('BootsOnTheGround', 'TitanBaseCamp', 'TitanFacility',
    'TitanicStorm', 'TitanicCanyon', 'TitanSandstorm', 'ToTheShip',
    'AsteroidMines', 'TheSteelDragon', 'C6Assembly', 'C12Patrol')

while True:
    print("Open Supply Drop?.")
    answer = input().lower()
    if answer == "yes":
        print("Please wait 3 seconds...")
        time.sleep(3)
        print("You got...")
        print(random.choice(callingcard))
    else:
        print("Please wait 3 seconds...")
        time.sleep(3)
        break

你的缩进不一致。Python完全基于缩进语法,您需要将IF、ELIF和ELSE选项卡下的所有行设置为相同的数量。 此外,由于设置running=True,但从未将其设置为任何其他值,因此从while开始将有一个无限循环。希望有帮助。在

if answer == ("Yes"):
   print("Please wait 3 seconds...")
   import time
  time.sleep(3)
  import random
  callingcard =     ['BootsOnTheGround', 'TitanBaseCamp', 'TitanFacility', 'TitanicStorm', 'TitanicCanyon', 'TitanSandstorm', 'ToTheShip', 'AsteroidMines', 'TheSteelDragon', 'C6Assembly', 'C12Patrol']
  print("You got...")
  print(random.choice(callingcard) # <--You're missing one closing parenthesis here. Try placing the parenthesis to fix the syntax error.

以下是您代码的临时版本: 我也在猜测IF,ELSE应该在while循环下缩进??在

^{pr2}$

相关问题 更多 >