Reading two separate values in one line in python

我的未来我决定 提交于 2019-12-02 08:09:14

问题


I need your help. This is my program so far

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()

As you can see, when the string has no [n] after it, it's being ignored. How can I fix this?


回答1:


I think it is because of the if len(instructions) > 1: test. If the string has no [n] after it, then there will only be one instruction, and the length will not be greater than 1.

You should try something like this:

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

Note the indentation and placement of the line for if i == 'new'.



来源:https://stackoverflow.com/questions/13390264/reading-two-separate-values-in-one-line-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!