if / elif语句和turtle命令出错

时间:2016-10-13 18:00:41

标签: python turtle-graphics

我在if / else语句中遇到了一个奇怪的错误。出于某种原因,当我使用此代码(介绍项目到龟图形)

from turtle import *
print('Hello. I am Terry the Turtle. Enter a command to make me draw a line, or ask for help.')
on = True
shape('turtle')
if on == True:
   c1 = str(input('Enter command: ')
   if c1 == 'forward':
      c2 = eval(input('How many degrees? ' ))
      right(c2)
   elif c1 == 'right':
      c2 = eval(input('How many degrees? ' ))
      right(c2)
   elif c1 == 'left':
      c2 = eval(input('How many degrees? ' ))
      left(c2)
   elif c1 == 'goodbye':
      print('Bye!')
      on = False
   else:
      print('Possible commands: forward, right, left, goodbye.')

由于某些奇怪的原因,ifelif语句会一直返回语法错误,但它们似乎没有任何明显的错误。我尝试做类似的事情,但它一直在返回语法错误。有什么方法可以解决这个问题吗?

对不起,如果这是一个愚蠢的问题,这是我第一次来这里,我真的很困惑。

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的

from turtle import *
print('Hello. I am Terry the Turtle. Enter a command to make me draw a line, or ask for help.')
on = True
shape('turtle')
# Get commands until user enters goodbye
while on:
    c1 = str(input('Enter command: '))
    if c1 == 'forward':
        # Ask how far when moving
        c2 = int(input('How far? '))
        # Use forward to move
        forward(c2)
    elif c1 == 'right':
        c2 = int(input('How many degrees? '))
        right(c2)
    elif c1 == 'left':
        c2 = int(input('How many degrees? '))
        left(c2)
    elif c1 == 'goodbye':
        print('Bye!')
        on = False
    else:
        print('Possible commands: forward, right, left, goodbye.')

这应该与Python3一起运行(例如python3 myrtle.py)。

答案 1 :(得分:0)

对于c1,您不必指示它是一个字符串,因为输入已经是字符串 并且不需要" eval"。

尝试:

from turtle import *
print('Hello. I am Terry the Turtle. Enter a command to make me draw a line, or ask for help.')
on = True
shape('turtle')
while on == True:
   c1 = input('Enter command: ')
   if c1 == 'forward':
      c2 = int(input('How far forward? ' ))
      forward(c2)
   elif c1 == 'right':
      c2 = int(input('How many degrees? ' ))
      right(c2)
   elif c1 == 'left':
      c2 = int(input('How many degrees? ' ))
      left(c2)
   elif c1 == 'goodbye':
      print('Bye!')
      on = False
   else:
      print('Possible commands: forward, right, left, goodbye.')