python - 在Python中的一行中读取两个单独的值

标签 python turtle-graphics

我需要你的帮助。这是我到目前为止的程序

import turtle
turtle.showturtle()

def turtle_interface():
    while True :
          n = 0
          instructions = input().split()
          i = instructions[0]
          if len(instructions) > 1:
              n = int(instructions[1])
              if i == 'forward' :
                  turtle.forward(n)
              elif i == 'backward' :
                  turtle.backward(n)
              elif i == 'left' :
                  turtle.left(n)
              elif i == 'right' :
                  turtle.right(n)
              elif i == 'quit' :
                  break
              elif i == 'new' :
                  turtle.reset()
              else :
                  continue

print('Control the turtle!')
turtle_interface()

如您所见,当字符串后面没有 [n] 时,它将被忽略。我该如何解决这个问题?

最佳答案

我认为这是因为 if len(instructions) > 1: 测试。如果字符串后面没有[n],则只有一条指令,且长度不会大于1。

你应该尝试这样的事情:

def turtle_interface():
    while True :
          n = 0
          instructions = input().split()
          i = instructions[0]
          if len(instructions) > 1:
              n = int(instructions[1])
              if i == 'forward' :
                  turtle.forward(n)
              elif i == 'backward' :
                  turtle.backward(n)
              elif i == 'left' :
                  turtle.left(n)
              elif i == 'right' :
                  turtle.right(n)
          elif i == 'new' :
              turtle.reset()
          elif i == 'quit' :
              break

请注意 if i == 'new' 行的缩进和位置。

关于python - 在Python中的一行中读取两个单独的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390264/

相关文章:

python - bibtex 到 html 与 pybtex,python 3

python - 在python turtle 绘图中隐藏 turtle

python - turtle 图形 turtle 放慢速度

python - Python Coords返回变量

python - 类型错误 : load_dotenv() got an unexpected keyword argument 'encoding'

python - 比较混合列表

python - 导入错误 : No module name libstdcxx

python - 如何让 turtle 图形在绘制时不显示 turtle ?

python turtle 形状

python - tkinter 标签的边框