Mor options

In a previous section (geometri) we used turtle and input together to decide how far the turtle should walk, in what angle it should turn, in order to draw a geometric figure.

Here, we will continue on that, by also offering options to choose color and shape.

Choosing color

In order to decide what color the turtle should have we need some kind of input instruction:

import turtle 

color = input('Which color? ') 

turtle.color(color)  
turtle.forward(150)

If you enter 'red' or 'yellow' or 'blue' you get a turtle with that color. But if you enter something that isn't a color, like 'hello', the turtle will just keep its original/default color, black.

A smart app knows if something went wrong - for example if we accidentally misspelled 'yellow' - and tells us about it. Here is how it might looks like:

The If-statement says "if the color is not red, not yellow, and not green", then pick a predecided color (red). Having something specific like this in code, is usually referred to as "hardcoding" a color.

Choosing shape

In the old example, we also "hardcoded" the turtle to walk along a square:

import turtle 

turtle.color('red', 'yellow') 

distance = int(input("How far? ")) 

turtle.forward(distance) 
turtle.left(90) 
turtle.forward(distance) 
turtle.left(90) 
turtle.forward(distance) 
turtle.left(90) 
turtle.forward(distance)

With a small twist, we can let the user choose between a triangle and a square:

import turtle 

turtle.color('red')  

distance = int(input("How far?")) 
figur = input("Which kind of figure (triangle/square)? ") 

if figur == 'triangle': 
  turtle.forward(distance)  
  turtle.left(120)  
  turtle.forward(distance)  
  turtle.left(120)  
  turtle.forward(distance) 

elif figur == "square": 
  turtle.forward(distance)  
  turtle.left(90)  
  turtle.forward(distance)  
  turtle.left(90)  
  turtle.forward(distance)  
  turtle.left(90)  
  turtle.forward(distance)  

else: 
  print("I did not understand, you can only choose between triangle and square.")

Notice what happens if you enter "pentagon" for example, neither condition is satisfied and we end after the "else" and the program says "I didn't understand...". The user then also knows what went wrong!

Can you combine both examples to a smart turtle? Try it yourself first, and then watch the video.

Read page in other languages

In this video, we look at the difference between the keywords if and elif, and when either is preferred.

  • If-statement: The keyword "if" followed by a logical condition allows our program to make decisions.
  • I/O: Short for input/output. In Python we use the functions input and print.