In: Computer Science
Can somebody describe what this following code does step by step.
import turtle
turtle.penup()
x = int(input("Enter x coordinate of top-left corner: "))
y = int(input("Enter y coordinate of top-left corner: "))
side = int(input("Enter side of the largest square: "))
if side >= 100:
gap = int(input("Enter gap between squares: "))
if gap < side:
turtle.goto(x,y)
turtle.pendown()
while True:
for i in range(4):
turtle.forward(side)
turtle.right(90)
side -=gap
turtle.penup()
x += gap
y -= gap
turtle.goto(x,y)
turtle.pendown()
if side<0:
exit(1)
Step by step explanation of given python code
import turtle - turtle() is a graphical library in python that gives command to a turtle to draw something over a window.
turtle.penup() - this command will tell turtle to move around the screen without drawing anything.
x = int(input("Enter x coordinate of top-left corner: "))
This will create a variable named x and store x coordinate of top-left corner of screen entered by the user. int will perform conversion as default type in python is string.
y = int(input("Enter y coordinate of top-left corner: "))
This will create a variable named y and store y coordinate of top-left corner of screen entered by the user. int will perform conversion as default type in python is string.
side = int(input("Enter side of the largest square: "))
This will create a variable named side and store side of the square entered by the user. int will perform conversion as default type in python is string
if side >= 100:
If condition will begin to check whether side is greater than 100 or not.
gap = int(input("Enter gap between squares: "))
gap is a variable that will store value of gal between squares.
if gap < side:
If gap is less than side next statement will be executed.
turtle.goto(x,y)
This command will tell the turtle to move to (x,y) coordinate position entered by the user.
turtle.pendown()
this command will tell turtle to move around the screen by drawing a line.
while True:
Until whilw condition is true loop will continue to execute next statements.
for i in range(4):
For loop will start from variable i to range 4
turtle.forward(side)
Turtle will move forward few pixels taking value of side.
turtle.right(90)
Turtle will turn to its right by 90 degrees.
side -=gap
It will compute side= side - gap
turtle.penup()
Turtle will again move without drawing anything.
x += gap
It will increase the value of x = x + gap
y -= gap
It will decrease the value of y coordinate y=y- gap
turtle.goto(x,y)
Turtle will now move to changed values of (x,y) coordinates
turtle.pendown()
Turtle will not draw anything.
if side<0:
If value of side is less than 0 than turtle will exit.
exit(1)
Program terminates.