Chapter 5

More turtle and function fun


In [10]:
import turtle


def draw_multi_color_shape(t_turtle, size):
    """Make turtle t_turtle draw a multi-colour shape based on size passed in."""
    
    colors = ['#2424FF', '#aaa', '#FF2424', '#ccc', '#24FF24', '#000']
    
    for color in colors:
        t_turtle.color(color)
        t_turtle.forward(size)
        t_turtle.left(135)

        
def create_turtle(speed, pensize):
    """Returns a configured turtule"""
    
    turt = turtle.Turtle()
    turt.speed(speed)
    turt.pensize(pensize)
    
    return turt


def move_turtle(t_turtle, forward, right):
    """Move t_turtle forward and then right"""
    t_turtle.forward(forward)
    t_turtle.right(right)

# Setup the screen for drawing
wn = turtle.Screen()
wn.bgcolor("#ffffff")

# Create our turtle
tess = create_turtle(0, 3.5)

# Lift turtle and move it
tess.up()
tess.goto(0, 0)
tess.down()

# Start coloring for the turtle
tess.begin_fill()

# Begin actually drawing
square_size = 30
square_rotation = 8
for i in range(45):
    draw_multi_color_shape(tess, square_size)
    square_size += square_rotation
    move_turtle(tess, square_size, square_rotation)

tess.end_fill()

wn.exitonclick()

In [9]:
def absolute_value(number):
    """
    Return the absolute value of a number. 
    The argument may be an integer or a floating point number. 
    If the argument is a complex number, its magnitude is returned.
    """
    return abs(number)

print(absolute_value.__doc__)

value = 10
print(value)

value = 11
print(value)

print(absolute_value(-10))

value = 5
print(value)

value += 15
print(value)

def add_to(number, amount):
    return number + amount

print(add_to(value, 5))


    Return the absolute value of a number. 
    The argument may be an integer or a floating point number. 
    If the argument is a complex number, its magnitude is returned.
    
10
11
10
5
20
25

Functions calling themselves

This is known as recursion


In [23]:
import math

def factorial(n):
    for number in range(n, 1, -1):
        return number * factorial(number - 1)
    
    return 1

print(factorial(3))
print(3 * 2 * 1)
print(math.factorial(3))

print(factorial(9))
print(9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1)
print(math.factorial(9))


6
6
6
362880
362880
362880

Function Defaults

By default a function without a return statement will give the result None.


In [22]:
def add_all(*numbers):
    number = 0
    
    for num in numbers:
        number += num
        
    return number

print(add_all(1, 2, 3, 4, 5, 6, 7, 8, 9))

def multiply_and_sum(x, *args):
    """
    Returns the results of multiplying x by all 
    passed arguments and then adding the results
    of each multiplication together
    """
    all_by_x = [arg * x for arg in args]
    return sum(all_by_x)

def multiply_and_sum_no_return(x, *args):
    """
    Same as mutiply_and_sum only returns nothing
    and is therefore useless
    """
    multiply_and_sum(x, *args)

values = [1,2,3,4]
result = multiply_and_sum_no_return(3, *values)

print("The result of no return is:", result)

result = multiply_and_sum(3, *values)
print("\nThe result of a return is: ", result)


45
The result of no return is: None

The result of a return is:  30

Writing Code

Be sure when writing code to follow PEP-0008 https://www.python.org/dev/peps/pep-0008/

This is the defacto Python style guide for writing code. You can think of it how English writers might think of MLA or ALA.

Studio: Wagon Wheel

Thanks James!

WEbsite for running: https://trinket.io/python


In [ ]:
import turtle
import random


def draw_square(turt,sideLength):
   """Returns nothing draws a square """
   turt.color(random.choice(["red","orange","yellow","blue","purple"]))
   turt.begin_fill()
   for _ in range(4):
       turt.forward(sideLength)
       turt.left(90)
   turt.end_fill()
       
def draw_four_square(turt,sideLength):
   """Return None draws a group of four squares that form a larger square"""
   for index in range(4):
       if(index == 0):
           draw_square(turt,sideLength)
       elif(index == 1):
           turt.penup()
           turt.backward(sideLength)
           turt.pendown()
           draw_square(turt,sideLength)
       elif(index == 2):
           turt.penup()
           turt.right(90)
           turt.forward(sideLength)
           turt.left(90)
           turt.pendown()
           draw_square(turt,sideLength)
       elif(index == 3):
           turt.forward(sideLength)
           draw_square(turt,sideLength)
   reset_turtle_to_origin(turt)   
   
def draw_square_rotate(turt,sideLength,num):
   """Returns None draws four square and regular intervals over 360 based on num """
   for angle in range(0,360,360//num):
       turt.left(angle)
       draw_four_square(turt,sideLength)
           
def reset_turtle_to_origin(turt):
   turt.penup()
   turt.setheading(0)
   turt.goto(0,0)
   turt.pendown()

def main():
   # Create window
   wn = turtle.Screen()
   
   # Create turtle
   turt = turtle.Turtle()
   turt.speed(0)
   
   # draw square
   draw_square_rotate(turt,100,5)
   
main()

In [1]:
print(8//3)


2

In [14]:
print(-7//3)


-3

In [13]:
print(-7/3)

import math

print(round(-7/3))


-2.3333333333333335
-2

Thanks for another wagon wheel

Garret


In [ ]:
import turtle

def drawSquare():
   for i in range(4):
       alex.forward(100)
       alex.left(90)
       
def drawWindow():
   for i in range(4):
       drawSquare()
       alex.left(90)
       
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.speed(9)
alex.color("blue")

for i in range(5):
   drawWindow()
   alex.left(18)