Andrew McCarthy
Andrew McCarthy

Reputation: 11

Error with if/elif statements and turtle commands

I have been having an odd error with if/else statements. For some reason, when I use this code (intro project to turtle graphics)

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.')

For some odd reason, the if and elif statements keep returning syntax errors, yet they do not seem to have any visible errors. I tried doing similar things, but it kept on returning syntax errors. Is there any way to fix this?

Sorry if this is a dumb question, this is my first time here and I am just really confused.

Upvotes: 1

Views: 409

Answers (2)

willer2k
willer2k

Reputation: 546

For c1, you don't have to indicate it is a string as inputs are already strings And no need for "eval".

Try:

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.')

Upvotes: 0

user3657941
user3657941

Reputation:

I think this is what you want

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.')

This should be run with Python3 (e.g. python3 myrtle.py).

Upvotes: 1

Related Questions