【问题标题】:The code skips a command in Python. Can anyone tell me why?代码跳过 Python 中的命令。谁能告诉我为什么?
【发布时间】:2021-03-06 14:12:45
【问题描述】:

所以,基本上,我只是在编写代码,这样如果你写了一个游戏的名字,它就会打开它。

print('You can play games here!')
time.sleep(1.5)
print('Snake')
time.sleep(0.5)
print('Maze')
time.sleep(1.5)
print('Type the name of one of the games to open it!')

game = input()

if game == 'Snake':
        import Snake
else:
    if game == 'Maze':
            import Maze

print('This Program Is Still In Development')

当我选择“Snake”时,它可以完美运行。但是当我选择“迷宫”时,它只是跳到print('This Program Is Still In Development') 部分。

有人可以帮忙吗?我在 MAC OS X 顺便说一句

编辑:如果我这样做elif,它不会改变。函数也没有。出于某种原因,唯一有效的游戏是 Snake。

编辑 2:奇怪的是,当我单独打开 Maze.py 时,它可以工作。怎么样?

【问题讨论】:

  • 当您import Maze 时是否应该发生任何可见的事情? (顺便说一句,约定是在 Python 中使用小写的模块名称)
  • import Maze 在终端中打开一个新游戏。比如,当我输入“迷宫”时,它应该会打开游戏
  • 我认为您的程序不会跳过任何内容,只需检查 Maze 模块的功能...顺便说一句,不知道是否只是 sn-p 但我看到那里有一些缩进泄漏
  • 那我们能看到 Maze.py 模块吗?顺便说一句,
  • 我建议在文件顶部导入所有模块并创建主要功能(例如main()run()),这样您就可以使用Maze.main() 而不是import Maze。以这种方式检测导入问题会更容易,因为它们都会在开始时被调用

标签: python macos macos-catalina


【解决方案1】:

改变这个:

else:
    if statement:
        # code

进入这个:

elif statement:
    # code

这有效(添加print 以查看its working):

import time
print('You can play games here!')
time.sleep(1.5)
print('Snake')
time.sleep(1.5)
print('Maze')
time.sleep(1.5)

game = input('Type the name of one of the games to open it!')

# lowercase the user input to have less conditions
# and to make sure that we skip conditions because of case sensitivity
game = game.lower()

if game == 'snake':
   # do stuff
   print("snake")

elif game == 'maze':
   # do stuff
   print("maze")

print('This Program Is Still In Development')

【讨论】:

  • 您能否解释一下您认为这会产生什么影响并解决 OP 的问题?
  • 不是真的,但我什至尝试过这样做: if: (code) if: (code)
  • 我认为,在 python3 中,如果您不使用“elif”,它只会运行任何条件。但如果你使用它,它会检查条件。我试过了,它奏效了。
  • 为什么要打印???我的脚本应该打开另一个,而不是打印文本!
  • 不好意思,因为我没有Maze或者Snake,所以尝试打印测试一下,这里复制代码
猜你喜欢
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 1970-01-01
  • 2013-05-29
  • 2023-03-24
  • 1970-01-01
  • 2015-12-29
相关资源
最近更新 更多