Programming with Python
What is Python?
Python is a programming language. It is called a high level language because it is easier to read than many other languages (assembly is a low level language). Python is a text based language. This means you can only display text or get some text from the user1.
Python Turtle
Python turtle is a pre-installed Python library that allows you to create pictures and shapes by providing them with a virtual canvas. The onscreen pen that you use for drawing is called the turtle and this is what gives the library its name.
Python SandBox
Python Sandbox was started in early 2016 in order to provide students a place to learn and practice programming with the Python language. Click here to open sandbox. You should see some example code. Press the play button. The code will run in the canvas on the right hand side. You can save your code by pressing the disk. You should also copy and paste it to a text file to ensure that it doesn't get lost.
Save your Python Code
Python Turtle Commands - Getting Started
Python turtle is a simple way to begin coding. Instruct the turtle to move around the canvas with these commands. You need these two lines of code first. This sets up your turtle.
import turtle
t = turtle.Turtle()
Commands for Movement
move forward 100 spaces
t.forward(100)
move backward 50 spaces:
t.backward(50)
turn right 90 degrees:
t.right(90)
turn left 45 degrees:
t.left(45)
Move around circle of radius 50
t.circle(50)
Set the position of turtle. This is the x and y coordinates. 0 is the middle of the canvas for both x and y.
t.setpos(-100,100)
Drawing Commands
Put the pen on the canvas:
t.pendown()
Lift the pen off of the canvas:
t.penup()
Change the pen color to red:
t.pencolor("red")
Show and Hide
Show the turtle:
t.showturtle()
Hide the turtle:
t.hideturtle()
Clearing the screen
Clear the canvas to start again:
t.clear()
Advanced - repeating code
If you want to repeat the same lines of code you can use a for loop. Don't worry about what this code means. All you need to know is that the number is the number of times to repeat. So the example code below makes a square by turning left then going forward four times.
Note: the code has to be exactly as it is here. After the semi-colon press enter. The next lines of code should automatically indent.
for i in range(4):
t.left(90)
t.forward(150)
Filling a shape with Colour
Before you start drawing your shape type the following two lines:
t.begin_fill()
t.fillcolor("red")
After you draw out a shape, type:
t.end_fill()
The example code below creates a blue square.
t.begin_fill()
t.fillcolor("blue")
for i in range(4):
t.left(90)
t.forward(150)
t.end_fill()
The example here creates a yellow star.
t.fillcolor("yellow")
for i in range(5):
t.forward(150)
t.left(144)
t.endfill()
Here is the code for both shapes together.
t.begin_fill()
t.fillcolor("blue")
for i in range(4):
t.left(90)
t.forward(150)
t.end_fill()
t.begin_fill()
t.fillcolor("yellow")
for i in range(5):
t.forward(150)
t.left(144)
t.end_fill()
...and the result:
Iteration - While Loops
While loops will continue until a condition is satisfied The following code will repeat 10 times and make 10 small circles. Each circle will be a little bigger than the last.
count = 1;
while count <=10:
t.circle(count)
count = count + 1
This code will make 10 circles. Each will be noticeably bigger than the last:
count = 10;
while count <=100:
t.circle(count)
count = count + 10
Functions
Functions allow you to group code together and use it more than once. You have to:
- Create the function
- Call (use) the function.
Step 1: Create the Function
Use the keyword def and give the function a name. This should include a verb and summarise its purpose. In the example below the function draws a square, so it is called DrawSquare
. The function below will draw a square but only when it is called - see step 2.
# create the function
def DrawSquare():
t.begin_fill();
t.fillcolor("ted")
for i in range(4):
t.forward(50)
t.right(90)
t.end_fill()
Step 2: Call the function
Call the function to make it do something.
# call (use) the function
DrawSquare()
Full Code - Create a function and call it twice.
The following code shows the function and it being called twice to make two squares.
A Complete Python Tutorial
Click here and try out some of the other commands.
Watch the following tutorial to find out more. Try out the code in Python Sandbox.
Draw the USA Flag in Python Turtle
Watch the following video for an example of how to drag the flag for the USA. This is for advanced Python turtle programmers.
Tutorial Sites
Python Turtle Tutorial | HolyPython.com
Advanced Graphics
Click here to learn how to create more advanced shapes.
Draw a House with Python Turtle
Draw house using Turtle programming in Python
Create a Racing Game
Click here to learn how to create a racing game.
Python - Text Mode
Although it's great for learning professional programmers would not use Python turtle. They would use a text editor to write a console program (one that just uses text). Here are some of the basic commands.
Display Text
The print
command will display text:
print("hello")
Get Text from the User
Variables are used to store data. In the code below the variable username
will store the name typed in by the user. To display data from the variable, type the variable name.
username = input("Enter username:")
print("Username is: " + username)
In the code below there are two variables: order and quantity. Input is used to get data from the user. Once the data is stored it can be used. For example below print is used to display variable name.
print('Welcome to Costa Cafe')
print('1. Cheese Burger - $4')
print('2. Hot Dog - $3')
order = input("Please enter your first order")
print("Your first order is: " + order)
quantity = input("Please enter the quantity")
print("You have ordered: " + quantity + " items")
Using IF
- Use IF to check for a certain value. Look at the example code below. When the user types in their order, it is stored in the variable called order.
- On line 10 IF is used to check if the order contains the value 1. If it does then the user ordered a cheese burger. So a message is displayed saying "You have ordered a cheese burger".
- If the user types in 2 then 2 is stored in the variable called order.
- On line 13 IF is used to check if order contains 2. If it does the message "You have ordered a hot dog" is displayed.
print('Welcome to Costa Cafe')
print('1. Cheese Burger - $4')
print('2. Hot Dog - $3')
order = input("Please enter your first order")
print("Your first order is: " + order)
quantity = input("Please enter the quantity")
print("You have ordered: " + quantity + " items")
if order == '1':
print('you ordered a cheese burger')
if order == '2':
print('you ordered a hot dog')
Calculating Total Price
If we already have variables storing the price and the quantity we are ready to calculate the total price. The code below multiples price by quantity and stores the result in the variable total.
- Anything typed into the program is stored as text. So quantity must be cast (converted) into a number first.
- Since total is a number we have to cast it to a text before it can be displayed.
- Note: if you are interested casting is changing the data type by adding a data type and round brackets. You can find out more here: Python Casting (w3schools.com)
total = int(quantity)*price
print('Your total is ' + str(total))
Calculations - Using Operators
The following code will add two numbers together and display the answer:
print(10 + 5)
The code above only works for the numbers 10 and 5. We call this hard coded because the numbers are always the same. It is better to store the numbers in variables so that they can be changed. The following code will add and then display the two numbers stored in the variables a
and b
.
a = 3
b = 5
print(a + b)
You could also store the result (8 in this example) into a separate variable:
a = 3
b = 5
result = a + b
print(result)
For those curious, it is possbile to make programs with a GUI (Graphical User Interface) in python with the use of Bindings to other languages that can make GUIs, but you do not need to know about this for your studies.