## Drawing With Turtle in Python

Turtle allows you to do basic drawing in python. Turtle was intended to be used as an introductory lesson to programming but you might find it useful if your are teaching trigonometry, algebra and other computer math subjects.

Turtle is programmed by instructing the cursor(turtle) to move forward or backward by a distance in units of pixels. You can also instruct it to turn left or right in term of degrees angle.

In the video below I’ll wall you through the basics of turtle.

Below are the source code that I have used in the demo:

Example #1. The basic turtle code

```#************************Example 1: Drawing Box*************************************************************** import turtle turtle.pendown() input('Press enter to continue: ') turtle.speed(0) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) #*************************************************************************************** ```

Example #2.  Applying Loop to do repetitive task

```#************************Example 2: Box using for control loop *********************************************** import turtle turtle.pendown() input('Press enter to continue: ') turtle.speed(1) for i in range (4): # repeat below indented commands 4x' turtle.forward(50) turtle.left(90) #************************Example 2*************************************************************** ```

Example #3. Filled Box

```#************************Example 3: Filled Box*************************************************************** import turtle turtle.pendown() input('Press enter to continue: ') turtle.speed(1) turtle.color('red', 'blue') turtle.begin_fill() for i in range (4): # repeat below indented commands 4x' turtle.forward(50) turtle.left(90) turtle.end_fill() #************************Example 3*************************************************************** ```

Example 4.Building basic of Fractals by introducing variables.

```#************************Example 4: fractal basic***************************************************************
import turtle
turtle.pendown()
input('Press enter to continue: ')
turtle.speed(1)
x=0
for i in range (20):   # repeat below indented commands 4x'
turtle.forward(50+x)
turtle.left(90)
x=x+5

#************************Example 4***************************************************************
```

Example 5. Solving Basic Trigonometry

```#************************Example 5***************************************************************
##prove that 95 and 85 are suplementary angle. Angle when add up together forms 180 degress
import turtle
turtle.pendown()
input('Press enter to continue: ')
turtle.speed(1)

turtle.speed(1)
turtle.forward(100) #this is angle 0
turtle.backward(100)

turtle.left(95)    #this is angel 75
turtle.forward(200)
turtle.backward(200)

turtle.left(85)   #adding 285+75 = 360 degrees turn
turtle.forward(200)
#************************Example 5***************************************************************

```

Example 6. Drawing  Symetrical Objects

```#Sourcecode from turtle documentaion: https://docs.python.org/3.3/library/turtle.html?highlight=turtle
from turtle import *
color('red', 'yellow')
pendown()
input('Press enter to continue: ')
speed(0)
begin_fill()
while True:
forward(200)
left(47)
if abs(pos()) < 1:
break
end_fill()
done()

```

Example 7. Basic Fractals

```##*********************************************************************************************************
## example 7 reference https://repl.it/@lucia0101/Looping-Circles-with-PythonTurtle

import turtle         # You must include this line for any turtle commands to work
import random
turtle.pendown()
input('Press enter to continue: ')

colors  = ["red","green","blue","orange","purple","pink","yellow","black"]

turtle.speed(0)      # Sets the drawing speed. 1 is slowest, 10 highest. 0 will draw eveything without seeing the turtle move.

x=0
# This loop will draw 8 circles in a circle.
for i in range (200):   # This line means 'do all these lines of code 8 times'
color = random.choice(colors) #Choose a random color
turtle.color(color)
turtle.circle(30+x)   # This line creates a circle with a diameter of 30
turtle.penup()      # This lifts the pen up so that when the turtle moves it does not draw.
turtle.forward(50)  # Moves the turtle forward 50
turtle.right(45)    # Turns the turtle 45 degrees right
turtle.pendown()    # Puts the pen back down ready to draw the next time we go through the loop
x=x+1

##************************************************************************************************************

```

Example 8.  Fractal Plant

```##******************************* Fractal plant **********************************************************
## As described in http://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant
##source https://gist.github.com/HansNewbie/9808789

import turtle
turtle.pendown()
input('Press enter to continue: ')

turtle.speed(0)

ruleInput = ['F', 'X']
ruleOutput = ["FF", "F-[[X]+X]+F[+FX]-X"]
start = "X"
front = 5
turn = 30
stack = []
dirstack = []
turtle.left(90)
turtle.penup()
turtle.setpos(0, -350)
turtle.pendown()
turtle.shape("turtle")

def generate(iteration):
result = start
temp = ""
for i in range(iteration):
for j in range(len(result)):
for k in range(len(ruleInput)):
if (result[j] == ruleInput[k]):
temp += ruleOutput[k]
break
if (k == len(ruleInput)-1):
temp += result[j]
result = temp
temp = ""
return result

def draw(input):
for x in input:
if (x == 'F'):
turtle.forward(front)
elif (x == '-'):
turtle.left(turn)
elif (x == '+'):
turtle.right(turn)
elif (x == '['):
stack.append(turtle.pos())
elif (x == ']'):
turtle.penup()
post = stack.pop()
direc = dirstack.pop()
turtle.setpos(post)
turtle.pendown()
turtle.hideturtle()
turtle.done()
draw(generate(6))
```

## Python Dictionary

Python dictionary is the key-value pair implementation in python. It is used to store and retrieve information using a key. It is also called associative array.

In the video below, I demonstrated how you can make use of dictionary to build a simple events management program.

The source code I used in this example are found below:

```import sys
import re
print(sys.version)

print ('****mynew events****')
MyEvents={'Name':"Aware-IT.org Python Conference" , 'EventDate':'6/12/018' }
print (MyEvents)

print ('****mynew events with venue****')
MyEvents['Venue']= 'Makati Shangrila'
print (MyEvents)

###Change the venue
print ('****mynew events with updated venue****')
MyEvents['Venue']='Edsa Shangrila'
print (MyEvents)

#print ('****mynew events with spekers****')
MyEvents['Speaker 1']='Luke Warm'
MyEvents['Speaker 2']='Baker Dozen'
MyEvents['Speaker 3']='Andy players'
print (MyEvents)
del MyEvents["Speaker 2"]
print (MyEvents)
#MyEvents.pop('Speaker 3')
#print (MyEvents)

MyEvents['Speaker 2']=MyEvents.pop('Speaker 3')
print (MyEvents)

print()
##print (MyEvents)
x=0
##print ('****Myevents printed horizontally****')
for key,values in MyEvents.items():
print(key,":",values )
if  (key[0:7])=="Speaker":
x=x+1

print()
print ("Total number of Speakers:",x)

print()
MyEvents['Participant 1']='Sarah Lance'
MyEvents['Participant 2']='Kara Danvers'
MyEvents['Participant 3']='Barry Allen'
MyEvents['Participant 4']='Oliver Queen'
MyEvents['Participant 5']='Laurel Lance'
#MyEvents['Participant 6']='Laurel Lance'

y=0
for key,values in MyEvents.items():
print(key,":",values )#python3 , if in python2 use print item, instead.
if  (key[0:11])=="Participant":
y=y+1

print()
print ("Total number of PArticipants:",y)

```

## Python Lists, Tuples and Sets

List, tuples and sets are some of the  data structures that are available on python.

List contains comma separated element that are changeable. List are enclosed in square brackets []

Tuples contains comma separated elements that are not changeable. Tuples elements are enclosed in parenthesis ()

Set contain elements that are unique. Set can be changed but uniqueness is maintained. Set elements are enclosed in braces{}

In the video below, I discussed these data structures:

Below are the codes I used for the demo:

``` import sys print (sys.version) print ("************ List ************") print("List is a collection of comma separated values which are changeable") print ("List allows duplicate members. It is enclosed in a square bracket") list1=[1,2,3,4] print(list1) print() print ("************ Tuple ************") print("Tuple is a collection of comma separated values which is not changeable") print ("Tuple allows duplicate members. It is enclosed in a parenthesis") tuple1=(4,5,6,7) print (tuple1) print() print ("************Sets ************") print("Sets is a collection of comma separated values which are changeable and unique") print ("Set does allows duplicate members. It is enclosed in a brackets {}") set1={8,9,10,11} print (set1) print() print ("************use of index************") print("you cn make use of index on list and tuple. set doe not support indexing") print ("to get the element of the index make use of the systax print (list1[3])") print ("the index is zero based which means the first element is list1[0]") print (list1[0]) print (tuple1[0]) #print (set1[0]) ## this will cause an error print ("************Slicing list and tuples************") print("you can extract data from list and tuples using slicing") print ("the format is list1[0:3] ") print (list1[0:3]) print (tuple1[0:3]) print ("************Slicing List and tuples with step interval************") print("you can make use of steps when slicing your data") print ("the format is list1[0:3:2] ") print (list1[0:3:2]) print (tuple1[0:3:2]) print ("************Changing the value of list using index************") print("you can change the value in the list using index. you cannot modify the value in tuples") print ("the format is list1[0]=9 ") list1[0]=9 #tupple1[0]=9 #this will cause an error print (list1[0:]) print ("************creating a big list with range ********************") list2=list(range(0,150)) tuple2=tuple(range(0,100,5)) print("listing 0 to 150") print (list2) print("tuples 0 to 100 step 5") print (tuple2) print ("************Getting last element with negative index********************") print (list2[-1]) print (tuple2[-1]) print ("************slicing with negative index*******************") print (list2[:-1]) print (tuple2[:-1]) print ("************last five element ******************") print (list2[-6:-1]) print (tuple2[-6:-1]) set2=set(range(1,5)) print (set2) list2=list(range(0,150)) tuple2=tuple(range(0,100,5)) print ("************add element to list and set ****************") list2.append(170) print (list2) set2.add(20) print (set2) print ("************Removing from the list and set ****************") list2.remove(170) print (list2) set2.remove(20) print (set2) print ("************Removing from the list and set with discard ****************") #list2.discard(170) 'there is no discard method in the list print (list2) set2.discard(25) print (set2) print ("************ Reversing****************") list3=list(range(1,20)) print(list3) list3.reverse() print (list3) print ("************sum and average****************") list4=list(range(1,20)) print (list4) print("sum of the list",sum(list4)) print("average of the list",sum(list4)/len(list4)) print("minimum value", min(list4)) print("maximum value", max(list4)) print("********set operation *********************") set3=set(range(1,10)) print(set3) set4=set(range(5,15)) print (set4) print("****intersection****") print(set3.intersection(set4)) print("****union****") print(set3.union(set4)) print("****difference****") print(set3.difference(set4)) print("repition") list4=list(range(1,5))*3 print(list4) ```

## Numeric Data types and Mathematical Operations in Python

Learning numeric data type in Python is essential to learning the Language. I created a training episode below for this basic fundamentals of learning python and i’m surprised to see a lot of mathematical functions available in the language though this is just the basic of them. The link to the video is below:

The code for the demo is published below. Good luck and Happy coding!
``` import sys import math print (sys.version) print () #print a new line```

``` #integer example print("a whole number is an example of integer m=1") m=1 print ("m="+repr(m)) print () #print a new line #float example print("a number with decimal is an example of float example m=2.16") m=2.16 print ("m="+repr(m)) print () #print a new line print("a number with decimal is an example of float example c=1j") c=1.j print ("c="+repr(c)) print ("cx2="+repr(c*2)) print () #print a new line x=9;y=25;z=3 print("x="+repr(x)+" y="+repr(y)+" z="+repr(z) ) print () #print a new line print ("******") print("x+y=") print(x+y) print () #print a new line print ("******") print( "X divided by y is x/y") print (x/y) print () #print a new line print ("******") print( "X divided by 2 is x/2") print (x/2) print () #print a new line print ("******") print( "X divided by 2 and get the int part only (floor division) is x//2") print (x//2) print () #print a new line print ("******") print( "X mod 2. Get the remainder of x/2 is X%2 ") print (x%2) print () #print a new line print ("******") print( "get the integer division and mod using is divmod(x,2)") print (divmod(x,2)) print () #print a new line print ("******") print( "X Times y is x*y") print (x*y) print () #print a new line print ("******") print( "x squared is x**2 or pow(x,2)") print (x**2) print (pow(x,2)) print () #print a new line print ("******") print ("The squareroot of x is math.sqrt(x)") print (math.sqrt(x)) print () #print a new line print ("******") print ("this is also square root of x. x**(1/2)") print (x**(1/2)) print () #print a new line print ("******") print ("this is the cube root of x. x**(1/3)") print (x**(1/3)) print () #print a new line print ("******") print ("the value of pi is math.e") print (math.pi) print () #print a new line print ("******") print ("the value of e that we use with log math.e") print (math.e) print () #print a new line print ("******") print ("log of x is math.log(x)") print (math.log(x)) print () #print a new line print ("******") print ("sine of x is math.sin(x)") print (math.sin(x)) print () #print a new line print ("******") print ("cosine of x is math.cos(x)") print (math.cos(x)) print () #print a new line print ("******") print ("factorial of x") print (math.factorial(x)) ```

## Strings And String Processing in Python

If you are learning a new programming language, usually string manipulation exercise are among the first thing to do. Python has a wide library of functions for string manipulation. Please watch my video below for the presentation

Here are the code that I have used for the demo:

```print ("Hello World") ## this is a comment # String Variables```

``` str1="This is a string" print (str1) #string is a zero based array of characters print(str1[0]) print(str1[1]) print(str1[3]) #print ("****the first six charachter*****") print (str1[0:5]) #print ("****the 2nd to 8th*****") print (str1[1:7]) #print ("****6th characters and onward *****") print (str1[5:]) str4='"this a string created with single qoute"' print(str4) str5="this's a string created with double qoute" print(str5) str5='this\'s a string created with single qoute and escape charater' print(str5) #long strig using three single quotes str6=''' this is a lOnG... long... span manyline string''' print(str6) #long strig using three double quotes str7="""this is a lOnG... long... span manyline string ex2""" print(str7) print (str7.count("s")) print (str7.find("s")) print (len(str7)) print (str7.upper()) print("*") print (str7.lower()) print("*") print(str7.capitalize()) print("*") print (str7.title()) str2 = "thisisyear 2009" print (str2.isalnum()) print (str2.isupper()) print(str2.istitle()) print(str2.isnumeric()) str3 = "non alphanumeric"; print (str3.isalnum()) #concatenation print("*** string concatenation demo***") A="I have two hands." B="the left and the right" print(A+B) #repr() Return a string containing a printable representation of an object. print("****repr demo****") x=6.0 print (repr(x)) X=7 ```

```print ("The value of small x="+repr(x)) print ("The value of X="+repr(X))```

## Developing Python on Visual Studio 2017

Python is now one of the emerging programming language. Just like any other programming language you can build different kinds of applications using it such as web application, desktop and command line base applications.

Developing it with visual studio make it more easy and classy. Visual studio has been used by a lot of developers since it first comes to being. Developers enjoy the IDE with its intellisense and centralized code repository among others. The advantage of developing python in Visual Studio is that you will probably need a learning curve with the IDE and if you are new to visual studio you can make use of if for other development purposes.

Please watch the video below for more details: