Is there a program to shorten this?

Viewed 85

I'm new to python, started doing it in quarantine just for fun. I was working on some Python code the other day, and decided to create an image with the turtle program. I'm seeing a lot of repetition here, so I was wondering if there was a way I could shorten it. Here's the code:

import turtle
wn = turtle.Screen()
House = turtle.Turtle()

House.forward(150)
House.left(90)
House.forward(110)
House.left(45)
House.forward(110)
House.left(90)
House.forward(110)
House.left(45)
House.forward(110)

wn.mainloop()

Thanks!

5 Answers

For this explicit example, you can try this:

House.forward(150)
for iter in range(2):
    for left_pos in [90,45]:
        House.left(left_pos)
        House.forward(110)
wn.mainloop()

You can do something like:

left_vals = [90, 45, 90, 45]
House.forward(150)
for v in left_vals:
  House.left(v)
  House.forward(110)

You can always use a for loop to reduce code repetition. If there is a pattern, you can use a function instead of putting values in the list. Here for example it seems like you call 90 and 45 in order. So you can do this:

House.forward(150)
for i in range(4):
  House.left(45 * (2 - i%2))
  House.forward(110)

import turtle


wn = turtle.Screen()
house = turtle.Turtle()

# function table for the turtle (fill up with other functions)
draw = {
    'F': house.forward,
    'L': house.left,
}

# direction, value
instructions = (
    ('F', 150),
    ('L', 90),
    ('F', 110),
    ('L', 45),
    ('F', 110),
    ('L', 90),
    ('F', 110),
    ('L', 45),
    ('F', 110),
)

for dir, val in instructions:
    draw[dir](val)  # call each function from the dict with the value

wn.mainloop()

First, let's correct the initial forward() distance to match the roof size. Then the program breaks down to four repetitions of the same left() and forward() motion with an alternating angle:

from turtle import Screen, Turtle

turtle = Turtle()
turtle.forward(110 * 2 ** 0.5)

angle = 90

for _ in range(4):
    turtle.left(angle)
    turtle.forward(110)

    angle = 135 - angle

screen = Screen()
screen.mainloop()

Here's something:

import turtle
wn = turtle.Screen()
House = turtle.Turtle()

for n in [(150,90),(110,45),(110,90),(110,45)]:
    House.forward(n[0])
    House.left(n[1])
House.forward(110)

wn.mainloop()
Related