0% found this document useful (0 votes)
87 views72 pages

Python Turtle Art Techniques

This document provides an overview of using Python and the Turtle module to create drawings and graphics through coding. It introduces for loops, while loops, functions, recursion, and lists as they apply to Turtle. Examples are given to draw shapes like polygons and spirals, as well as fractal patterns like trees and snowflakes. The document encourages playing with Turtle labs and code on your own and provides contact information for the instructor. Credit is given to various online resources that information and examples were drawn from.

Uploaded by

Manoj m emcs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views72 pages

Python Turtle Art Techniques

This document provides an overview of using Python and the Turtle module to create drawings and graphics through coding. It introduces for loops, while loops, functions, recursion, and lists as they apply to Turtle. Examples are given to draw shapes like polygons and spirals, as well as fractal patterns like trees and snowflakes. The document encourages playing with Turtle labs and code on your own and provides contact information for the instructor. Credit is given to various online resources that information and examples were drawn from.

Uploaded by

Manoj m emcs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Introduction to Python Turtle
  • Announcement
  • Learning Objectives
  • Python Coding Basics
  • Data Structures: Lists, Strings and Tuples
  • Recursion Techniques
  • Python Turtle Graphics and Recursion
  • Conclusion and Credits

Art with Python

Turtle
Announcement
Homework 2 will be posted today after TA William’s tutorial.
Learn
Iterations and recursions
Python
Just a little bit more
Coding Basics
Credit: lecture notes modeled after [Link]
html
for Loop

[Link]
Syntax

for iterating_var in sequence:


____STATEMENTS
fruit = 'apple'
for each_char in fruit:
print each_char
a
p
p
l
e
Range function
A=range(10)
B=range(2,7)
C=range(0,10,2)
D=range(-10, -30, -5)
print A
print B
print C
print D
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6]
[0, 2, 4, 6, 8]
[-10, -15, -20, -25]
a = ['I', 'love', 'Python', 'programming']
for i in range(len(a)):
print i, a[i]
0I
1 love
2 Python
3 programming
while Statement
Syntax

while EXPRESSION:
____STATEMENTS
def newyear_countdown(n):
while n > 0:
print n
n = n-1
print "Happy New Year!"
newyear_countdown(10)
10
9
8
7
6
5
4
3
2
1
Happy New Year!
def num_digits(n):
count = 0
while n:
count = count + 1
n = n / 10
return count
print num_digits(54320)
print num_digits(int('012345'))
print num_digits(int(23.45))
print num_digits(23.45)
5
5
2
And an infinite loop
def print_powers(n):
i=1
while i <= 6:
print n ** i, '\t',
i += 1
print
print_powers(2)
2 4 8 16 32 64
Lists
List is an ordered set of values.
It can contain mixed types.
A = [1, 2, 3, 4]
print A
B = ["hello", "and", "good morning"]
print B
C = ["hello", 100, 'person', 2.5, [1, 2]]
print C
[1, 2, 3, 4]
['hello', 'and', 'good morning']
['hello', 100, 'person', 2.5, [1, 2]]
empty = []
print empty
print 'this is[',empty,']'
[]
this is[ [] ]
empty = []
print empty
print 'this is[',empty,']'
print type(empty)
[]
this is[ [] ]
<type 'list'>
numbers = [1, 2, 3, 4, 5, 6]
print numbers[0]
print numbers[5]
print numbers[-1]
print numbers[-2]
1
6
6
5
rainyday = ["today", "is", "a", "rainy","day"]

i=0
while i < len(rainyday):
print rainyday[i]
i += 1

#See the flow of the program


today
is
a
rainy
day
rainyday = ["today", "is", "a", "rainy","day"]

print "today" in rainyday


print 'Today' in rainyday
print 'is' in rainyday
True
False
True
a = [1, 2, 3]
b = [10, 20, 30]
c=a+b
print c

d = a[1]*b
print d

e = a*4
print e
[1, 2, 3, 10, 20, 30]
[10, 20, 30, 10, 20, 30]
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
alphabet = ['a', 'b', 'c', 'd', 'e', 'f']
print alphabet[1:3]
print alphabet[:]
print alphabet[0:1]
print alphabet[0:8]
['b', 'c']
['a', 'b', 'c', 'd', 'e', 'f']
['a']
['a', 'b', 'c', 'd', 'e', 'f']
Lists are mutable.
pie = ["banana", "apple", "pear","strawberry"]
pie[0] = "peach"
pie[-1] = "chocolate"
print pie
['peach', 'apple', 'pear', 'chocolate']
if []:
print "empty"
else:
print "full"

# [] acts like 0 here


full
Lists are mutable, strings are not.
Strings are immutable.
Tuple is a sequence of items of any type.
Tuple is immutable.
my_tup = (1, 2, 3, 4, 5)
print type(my_tup)
print my_tup[0]
my_tup[0] = 6 #Assignment is not supported
<type 'tuple'>
1
TypeError: 'tuple' object does not support item assignment
Recursion
def recursive_sum(nested_num_list):
sum = 0
for element in nested_num_list:
if type(element) == type([]):
sum = sum + recursive_sum(element)
else:
sum = sum + element
return sum

print recursive_sum([1,2,3,4])
Tail Recursion
def newyear_countdown(n):
if n == 0:
print "Happy New Year!"
else:
print n
newyear_countdown(n-1)
newyear_countdown(5)
5
4
3
2
1
Happy New Year!

#see the order of execution


More Recursion Examples
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print factorial(4)
Fibonacci
number

Credit: Wikipedia
def fibonacci (n):
if n == 0 or n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

print fibonacci(3)
3
Python Turtle Review
[Link]
import turtle
johnny = [Link]()
for i in range(0,4):
[Link](100)
[Link](90)

[Link]
import turtle
def draw_polygon(sides, length):
johnny = [Link]()
for i in range(0,sides):
[Link](length)
[Link](360/sides)

draw_polygon(4,20)

draw_polygon(6,20)

Credit: [Link]
import turtle
def draw_spiral(angle, length_start, length_increase, sides):
for i in range(0,sides):
[Link](length_start+(i*length_increase))
[Link](angle)

johnny = [Link]()
draw_spiral(30, 10, 2, 20)

Credit: [Link]
import turtle
def draw_petals(length, number):
for i in range(0, number):
[Link](length)
[Link](180-(360/number)) # number divisible by 360
johnny = [Link]()
draw_petals(50,20)

Credit: [Link]
Recursion with Python Turtle
[Link]
import turtle

myTurtle = [Link]()
myWin = [Link]()

def drawSpiral(myTurtle, lineLen):


if lineLen > 0:
[Link](lineLen)
[Link](90)
drawSpiral(myTurtle,lineLen-5)

drawSpiral(myTurtle,100) Credit:
[Link]
import turtle

def tree(branchLen,t):
if branchLen > 5:
[Link](branchLen)
[Link](20)
tree(branchLen-15,t)
[Link](40)
tree(branchLen-15,t)
[Link](20)
[Link](branchLen) Credit:
[Link]
def main():
t = [Link]()
myWin = [Link]()
[Link](90)
[Link]()
[Link](100)
[Link]()
[Link]("green")
tree(75,t)
[Link]()

main() Credit:
[Link]
from turtle import *

def drawSnowFlake(length, depth):


if depth > 0:
for i in range(6):
forward(length)
drawSnowFlake(length // 3, depth - 1)
backward(length)
left(60)

drawSnowFlake(60,2)
drawSnowFlake(60,3)
William’s tutorial
on his Python Turtle
Play with Python
labs on your own!
thanks!
Any questions?
You can find me at
beiwang@[Link]

[Link]
Credits
Special thanks to all the people who made and released
these awesome resources for free:
Presentation template by SlidesCarnival
Photographs by Unsplash

Common questions

Powered by AI

The 'range' function in Python is used to generate a sequence of numbers, which is often utilized in loop iterations to execute a statement multiple times. It can generate sequences with a specified start, stop, and step. For example, A=range(10) produces numbers from 0 to 9, B=range(2,7) generates 2 to 6, C=range(0,10,2) results in an even number sequence from 0 to 8, and D=range(-10, -30, -5) produces -10 to -25 in decrements of 5 .

Python's list operations, given their dynamic typing and variable features, play a crucial role in memory management strategies in application development. Lists allow in-place modifications which reduce memory usage and processing time over creating new lists for every change. However, managing list sizes and types is vital, as inadvertent large dynamic operations could cause memory bloating. Proper use of list comprehension and generator expressions can minimize memory overhead by producing elements on demand rather than holding entire data structures in memory, aligning with optimal memory usage practices .

The drawSpiral function using Python Turtle visually demonstrates recursion by progressively drawing smaller sections of a spiral, with each recursive call reducing the line length by a fixed amount. This visually highlights the recursive nature, as each step is a smaller version of the previous ones, reinforcing the principle of self-similarity used in recursion by visually representing the reduction in scale through a spiraling pattern .

Tail recursion in Python is a form of recursion where the recursive call is the last operation in the function, allowing certain optimizations by reducing the call stack. It helps students understand recursion's mechanism by learning to break down problems into repeatable tasks with less emphasis on retaining prior stack data. Using tail recursion, such as in the newyear_countdown function, simplifies the recursive process while focusing on the recursive call as the last action for efficiency .

Python's list slicing can be effectively combined with other data structures to manipulate subsets of data without altering the original list structure. For instance, when working with nested lists, copying segments using slicing can be a powerful technique to work on specific parts of data sustainably. Slicing allows for accessing parts of lists to integrate with dictionaries or tuples without mutating the original collections, thus aiding in implementing changes or examinations on certain list sections while maintaining integrity .

Using turtle graphics for teaching programming offers an engaging way to visualize concepts such as loops and conditionals. As students see the immediate results of their code in the form of graphics, it reinforces the understanding of iterative control structures and conditional execution. The visual feedback loop allows learners to experiment with parameters in real-time, solidifying abstract constructs like repetition and decision-making through tangible results. For example, drawing shapes requires loops that iterate a specific number of times, immediately demonstrating loop functionality when altering loop parameters visibly changes the output .

In Python, lists are mutable, meaning they can be changed after creation, allowing items to be updated or removed. On the other hand, strings and tuples are immutable; once they are created, their content cannot be changed. For example, a list pie = ['banana', 'apple', 'pear','strawberry'] can be altered to pie[0] = 'peach', resulting in ['peach', 'apple', 'pear', 'chocolate']. Tuples, like my_tup = (1, 2, 3, 4, 5), do not allow assignment to their items after creation, and attempting to do so would result in a TypeError .

Traditional recursion for calculating Fibonacci sequences can be inefficient due to the exponential growth of recursive calls, leading to the recalculations of the same Fibonacci numbers multiple times, significantly increasing computation time. In Python, this is demonstrated in the fibonacci function, where each call to fibonacci(n) recursively calls fibonacci(n-1) and fibonacci(n-2), resulting in a large number of redundant computations for higher values. This illustrates the drawbacks of naive recursion without optimization strategies like memoization .

A 'for' loop in Python iterates over a sequence, executing the block of code for each item. It is best suited for iterations where the number of iterations is defined in advance using constructs such as ranges, lists, or strings. For instance, iterating over a string to print each character uses a 'for' loop effectively. A 'while' loop, however, is based on a conditional expression and will run until this condition becomes false, making it suitable for scenarios where the number of iterations is unknown beforehand. 'While' loops are often used for indefinite sequences, such as reading lines from a file until reaching EOF .

The Python Turtle module, along with recursive functions, allows for the creation of intricate geometrical patterns such as fractals. Recursive functions, which call themselves under certain conditions, enable the repetition and scaling necessary for fractals. For instance, Turtle is used to draw snowflakes by deductively reducing complexity; the function drawSnowFlake recursively draws smaller segments, achieving the intricate detail characteristic of fractals through layers starting from a simple loop structure .

Art with Python
Turtle
Announcement
Homework 2 will be posted today after TA William’s tutorial.
Learn
Iterations and recursions
Python 
Just a little bit more 
Coding Basics
Credit: lecture notes modeled after http://www.openbookproject.net/thinkcs/pyth
for Loop
http://www.pythontutor.com/index.html
for iterating_var in sequence:
____STATEMENTS
Syntax
fruit = 'apple'
for each_char in fruit:
    print each_char
a
p
p
l
e
Range function
A=range(10)
B=range(2,7)
C=range(0,10,2)
D=range(-10, -30, -5)
print A
print B
print C
print D

You might also like