###### tags: `Kiditech`
# Python Turtle Class
### 1. Common fucntions
https://docs.python.org/3/library/turtle.html
### 2. for loop , while loop
### 3. Control flow , if / else
### 4. Operatpr
### 5. Function / def , return type
```
import turtle
turtle.setup(400, 500) # Set the size and position of the main window
wn = turtle.Screen()
cody = turtle.Turtle()
def h1():
cody.forward(50)
def h2():
cody.left(50)
def h3():
cody.right(50)
def h4():
cody.backward(50)
def h5():
wn.bye()
wn.onkey(h1, "Up")
wn.onkey(h2, "Left")
wn.onkey(h3, "Right")
wn.onkey(h4, "Down")
wn.onkey(h5, "q")
wn.listen()
wn.mainloop()
```
### 6. OOP / classses
### Fun projects

```
import turtle
cody = turtle.Turtle()
for angle in range(0, 360, 20):
cody.setheading(angle)
cody.forward(100)
cody.write(str(angle) + '*')
cody.backward(100)
```

```
import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange']
cody = turtle.Turtle()
for x in range(150):
cody.pencolor(colors[x % 5])
cody.width(x/10 + 1)
cody.forward(x)
cody.left(59)
```

```
import turtle
painter = turtle.Turtle()
painter.pencolor("blue")
for i in range(50):
painter.forward(50)
painter.left(123) # Let's go counterclockwise this time
painter.pencolor("red")
for i in range(50):
painter.forward(100)
painter.left(123)
turtle.done()
```

```
import turtle
ninja = turtle.Turtle()
ninja.speed(10)
for i in range(180):
ninja.forward(100)
ninja.right(30)
ninja.forward(20)
ninja.left(60)
ninja.forward(50)
ninja.right(30)
ninja.penup()
ninja.setposition(0, 0)
ninja.pendown()
ninja.right(2)
turtle.done()
```

```
import turtle
cody = turtle.Turtle()
cody.penup()
for i in range(30, -1, -1):
cody.stamp()
cody.left(i)
cody.forward(20)
```

```
import turtle
cody = turtle.Turtle()
for i in range(500):
cody.forward(i)
cody.left(91)
```
### 1. random class
```
import turtle
import random
colors =['red','purple','blue','green','yellow','orange']
cody = turtle.Turtle()
for x in range(360):
cody.pencolor(colors[random.randrange(1,6)])
cody.width(x/100+1)
cody.forward(x)
cody.left(59)
```

### 2. random class
```
import turtle
import random
cody = turtle.Turtle()
for n in range(60):
cody.penup()
cody.goto(random.randint(-400, 400), random.randint(-400, 400))
cody.pendown()
red_amount = random.randint( 0, 30) / 100.0
blue_amount = random.randint(50, 100) / 100.0
green_amount = random.randint( 0, 30) / 100.0
cody.pencolor((red_amount, green_amount, blue_amount))
circle_size = random.randint(10, 40)
cody.pensize(random.randint(1, 5))
for i in range(6):
cody.circle(circle_size)
cody.left(60)
```

3. Advance use of random class
```
import random
print("Number guessing game")
# randint function to generate the
# random number b/w 1 to 9
number = random.randint(1, 9)
# number of chances to be given
# to the user to guess the number
# or it is the inputs given by user
# into input box here number of
# chances are 5
chances = 0
print("Guess a number (between 1 and 9):")
# While loop to count the number
# of chances
while chances < 5:
# Enter a number between 1 to 9
guess = int(input())
# Compare the user entered number
# with the number to be guessed
if guess == number:
# if number entered by user
# is same as the generated
# number by randint function then
# break from loop using loop
# control statement "break"
print("Congratulation YOU WON!!!")
break
# Check if the user entered
# number is smaller than
# the generated number
elif guess < number:
print("Your guess was too low: Guess a number higher than", guess)
# The user entered number is
# greater than the generated
# number
else:
print("Your guess was too high: Guess a number lower than", guess)
# Increase the value of chance by 1
chances += 1
# Check whether the user
# guessed the correct number
if not chances < 5:
print("YOU LOSE!!! The number is", number)
```
---
---
---
### if and else
```
answer = input("Is Python an interpreted language? Yes or No >> ")
if answer == "yes" :
print("You have cleared the test.")
else :
print("You have failed the test.")
print("Thanks!")
```
### for loop exercises
1.
```
for i in range(5):
print("I will not chew gum in class.")
```
2.
```
for i in range(5):
print("Please,")
print("Can I go to the mall?")
```
3.
```
for i in range(5):
print("Please,")
print("Can I go to the mall?")
```
4.
```
for i in range(10):
print(i)
```
5.
```
# What does this print? Why?
for i in range(3):
print("a")
for j in range(3):
print("b")
```
6.
```
for i in range(3):
print("a")
for j in range(3):
print("b")
print("Done")
```
### while loop
```
quit = "n"
while quit == "n":
quit = input("Do you want to quit? ")
```
### PonyCody Chapters
```
import turtle
cody = turtle.Turtle()
cody.shape("turtle")
print("Hello World!")
```
```
import turtle
cody = turtle.Turtle()
cody.shape("turtle")
cody.speed(10)
cody.forward(100)
```
```
import turtle
cody = turtle.Turtle()
cody.shape("turtle")
for x in range(0,6):
cody.left(60)
cody.forward(100)
```
```
import turtle
cody = turtle.Turtle()
cody.shape("turtle")
cody.color("green")
cody.stamp()
cody.forward(100)
```
```
import turtle
cody = turtle.Turtle()
cody.shape("turtle")
cody.color("green")
cody.hideturtle()
cody.forward(200)
cody.showturtle()
```
# Advance project

```
import turtle
import time
import random
delay = 0.1
# Score
score = 0
high_score = 0
# Set up the screen
wn = turtle.Screen()
wn.title("Snake Game ")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0) # Turns off the screen updates
# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"
# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
segments = []
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0 High Score: 0",align="center", font=("Courier", 24, "normal"))
# Functions
def go_up():
if head.direction != "down":
head.direction = "up"
def go_down():
if head.direction != "up":
head.direction = "down"
def go_left():
if head.direction != "right":
head.direction = "left"
def go_right():
if head.direction != "left":
head.direction = "right"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
# Main game loop
while True:
wn.update()
# Check for a collision with the border
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# Check for a collision with the food
if head.distance(food) < 20:
# Move the food to a random spot
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
# Add a segment
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
# Shorten the delay
delay -= 0.001
# Increase the score
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# Move the end segments first in reverse order
for index in range(len(segments) - 1, 0, -1):
x = segments[index - 1].xcor()
y = segments[index - 1].ycor()
segments[index].goto(x, y)
# Move segment 0 to where the head is
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
move()
# Check for head collision with the body segments
for segment in segments:
if segment.distance(head) < 20:
time.sleep(1)
head.goto(0, 0)
head.direction = "stop"
# Hide the segments
for segment in segments:
segment.goto(1000, 1000)
# Clear the segments list
segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
# Update the score display
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center",
font=("Courier", 24, "normal"))
time.sleep(delay)
wn.mainloop()
```
guessing game
```
import random
n = random.randint(1, 99)
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
print
if guess < n:
print( "guess is low")
guess = int(input(("Enter an integer from 1 to 99: ")))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("you guessed it!")
break
print
```
paper
```
import random
num = 1
yin_num = 0
shu_num = 0
while num <= 3:
if shu_num == 2 or yin_num == 2:
break
user = int(input('Enter 0(stone) 1(scissor) 2(paper)\n'))
if user > 2:
print('enter 0 , 1 or 2 only!')
else:
data = ['stone', 'scissor', 'paper']
com = random.randint(0, 2)
print("yours is {},computer's is {}".format(data[user], data[com]))
if user == com:
print('even')
continue
elif (user == 0 and com == 1) or (user == 1 and com == 2) or (user == 2 and com == 0):
print('u win')
yin_num += 1
else:
print('u lost')
shu_num += 1
num += 1
```
1. break vs continue
```
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
if count == 3:
break
print("Sum of first ",count,"integers is: ", num_sum)
```
```
n =[1,2,3,4]
sum = 0
for x in n:
if x ==2:
continue
else:
sum+=x
print(sum)
print('\n\n',sum)
```
break in while loop
```
num_sum = 0
count = 0
while(count<10):
num_sum = num_sum + count
count = count + 1
if count== 5:
break
print("Sum of first ",count,"integers is: ", num_sum)
```
```
for x in range(7):
if (x == 3 or x==6):
continue
print(x)
```
2. Function
```
def my_function():
print("Hello from a function")
```
```
def swap(x, y):
temp = x;
x = y;
y = temp;
```
```
# A simple Python function to check
# whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
# Driver code
evenOdd(2)
evenOdd(3)
```
# More
1.
```
Two sum problem:
----------------
for i in range(0,len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
```
```
2.
nums = ['oscar','james','even','bob']
print(nums.index('james'))
```
3.
https://docs.python.org/3/library/random.html
print (random.randrange(50,100))
4.
