Solutions

Solutions to workshop challenges

Challenge 1: String Formatting

Solution

name = "Robert"
age = 19

print("Hi! My name is {} and I'm {} years old.").format(name, age)

Challenge 2: Conditional Statements

Solution without extension

print('''
Choose any of the three following ice cream flavours...
1. Chocolate
2. Strawberry
3. Vanilla

If you enter none of the above, you will be given mint.
''')

choice = int(input("Pick your choice (enter number 1-3) > "))

if (choice == 1):
    flavour = "chocolate"
elif (choice == 2):
    flavour = "strawberry"
elif (choice == 3):
    flavour = "vanilla"
else:
    flavour = "mint"

print("You chose {} flavoured ice cream.").format(flavour)

Solution with extension

print('''
Choose any two of the three following ice cream flavours...
1. Chocolate
2. Strawberry
3. Vanilla

If you enter only one or none, you will be given mint.
''')

options = ["chocolate", "strawberry", "vanilla"]

choices = input("Pick your choice (enter numbers 1-3) > ").split('&')

giveMint = False

if len(choices) < 2:
  giveMint = True

if giveMint:
  print("You chose mint flavoured ice cream.")
else:
  firstChoice = options[int(choices[0])-1] # must subtract 1 as indexing starts at 0
  secondChoice = options[int(choices[1])-1]
  print("You chose {} and {} flavoured ice cream.").format(firstChoice, secondChoice)

Challenge 3: Using Libraries

Solution

import turtle

t = turtle.Turtle()

def drawSquare():
    for i in range(4):
        t.forward(100)
        t.right(90)

def drawTriangle():
    for i in range(3):
        t.forward(100)
        t.right(120)

print('''
Choose any of the three following shapes to draw...
1. Square
2. Triangle
3. Circle

If you enter none of the above, a line will be drawn.
''')

choice = int(input("Pick your choice (enter number 1-3) > "))

if (choice == 1):
    drawSquare()
elif (choice == 2):
    drawTriangle()
elif (choice == 3):
    t.circle(50) # no need for a function - it's one line
else:
    t.forward(100) # same reasoning here - it's one line

Last updated