Python Course 3: Data Types and Integers

Good Practice

Which of the following is better programming practice? Why?

x = 35.51*1.17
print(x)

or

pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate

print("£", pounds ,  " = " , euros , " euros")
print("at a rate of " , euroRate , " euros to the pound")

Formatting

Take a look at the output from the second piece of code

£ 35.51  =  41.546699999999994  euros
at a rate of  1.17  euros to the pound

This would be better if it read 41.55 euros, rather than 41.546699999999994

Also, take a look at this line

print("£", pounds ,  " = " , euros , " euros")

All those commas and speech marks are confusing. It’s easy to make a mistake when entering them.

There’s a better way to format your data.

pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate

print("£ {} = {} euros".format(pounds, euros))
print("at an rate of {} euros to the pound".format(euroRate))

The above does the same as the original code. It has the advantage of being slightly easier to enter and read. As an added bonus, you can format the number of decimal places

pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate

print("£ {} = {:.2f} euros".format(pounds, euros))
print("at an rate of {} euros to the pound".format(euroRate))

Notice the {:.2f}. This says “format the number as a float (a decimal) to 2 decimal places”

This produces the following output

£ 35.51 = 41.55 euros
at a rate of 1.17 euros to the pound

Much more user friendly!

Loop Question

Use a while loop to produce the sequence 0.1, 0.2, 0.3, …1.0

number = 0.1
while number <=1:
    print(number)
    number = number + 0.1

Produces

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Format the number for a neater answer

number = 0.1
while number <=1:
    print("{:.1f}".format(number))
    number = number + 0.1

0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

Number bases

You can format numbers into different bases as follows

print("{:d}".format(17))
print("{:b}".format(17))
print("{:X}".format(17))

The numbers are printed in denary, binary and hexadecimal.

17
10001
11

Remember that the input command reads strings. You have to convert strings to integers (whole numbers) or floats (decimals) if you want to use them to perform calculations.

Examples

1) Write a program that prompts the user to enter the length and width of a rectangle. Output the area of the rectangle

length = int(input("Enter the length of the rectangle"))
width = int(input("Enter the width of the rectangle"))
area = length*width
print("The rectangle has an area of {}".format(area))

2) To convert miles to kilometers, you multiply the number of miles by 1.609. Write a program that prompts the user to enter the number of miles, and then output the answer converted to kilometers

Note the use of float as a user may input 12.5 miles, for example.

miles = float(input("Enter the number of miles"))
kilometers = miles * 1.609
print("{} miles = {:.2f} kilometers".format(miles,kilometers))

Exercise

  1. Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
  2. At the time of writing, the exchange rate for pounds to euros is 1 GBP = 1.19984 Euros. Write a program that will convert pounds to euros. Test it using the data GBP4.50 (Don’t forget to convert the input to a float!)
  3. Now write a program to convert euros to pounds. Test it using the data Euro 7.40
  4. Prompt the user to input a number. Output the square of that number.
  5. Prompt the user to input two numbers. Output the average of those two numbers.
  6. Prompt the user to input three numbers. Output the sum and the average of those three numbers.
  7. Assume pi = 3.1415. Prompt the user to input the radius of a circle. Output the circumference and the diameter of that circle

Extension: Fahrenheit to Celsius

Here are the formulas to convert from Fahrenheit to Celsius and back again.

°F to °C Deduct 32, then multiply by 5, then divide by 9 °C to °F Multiply by 9, then divide by 5, then add 32

  1. Now write a program to convert Celsius to Fahrenheit. Use the test data to check your program.
  2. Write a program to convert Fahrenheit to Celsius. Again, use the test data below to check your program.

Test data

CF
032
1254
100212
-327
-180
-23-10

Python Course 2: Bracelets and Snakes

The following code draws a snake

import turtle

SIDE = 50

def triangle():
    turtle.begin_fill()
    for n in range(3):
	turtle.forward(SIDE)
	turtle.right(120)
    turtle.end_fill()

def black_triangle():
    turtle.fillcolor("black")
    triangle()

def white_triangle():
    turtle.fillcolor("white")
    triangle()

def snake():
    black_triangle()
    turtle.forward(SIDE)
    turtle.right(60)
    white_triangle()
    turtle.left(60)

snake()

Exercise

  1. Copy the code into your IDE and run it.
  2. Draw a snake 6 segments long
  3. Draw a red and green snake, 6 segments long.
  4. Draw pink and yellow snake, 6 segments long, but half the size of the previous snake.
  5. Use a for loop to simplify your code.
  6. Now draw a snake 10 segments long

Extension

Modify your code to draw a bracelet, as shown below.

Functions and Turtle Graphics

The following code is the start of a solution to the problem of  drawing a chessboard. It uses functions to help make the code  understandable

import turtle

# Declare this at the top.  Put it in capitals to show it shouldn't be changed
SIDE = 50

def square():
    turtle.begin_fill()
    for n in range(4):
	turtle.forward(SIDE)
	turtle.right(90)
    turtle.end_fill()


def black_square():
    turtle.fillcolor("black")
    square()

def white_square():
    turtle.fillcolor("white")
    square()

def move_one_square_right():
    turtle.penup()
    turtle.forward(SIDE)
    turtle.pendown()

def move_one_square_down():
    turtle.penup()
    turtle.right(90)
    turtle.forward(SIDE)
    turtle.left(90)
    turtle.pendown()

def white_black_line():
    for n in range(4):
	white_square()
	move_one_square_right()
	black_square()
	move_one_square_right()

# Speed up the turtle
turtle.speed(0)

# Draw two lines of the chessboard
white_black_line()
turtle.home()
move_one_square_down()
move_one_square_down()
white_black_line()

Exercise

  1. Copy the code into your IDE. Watch out for indents!
  2. Run the code and see what it does.
  3. Add a function to draw a black_white() line
  4. Draw a chessboard using the functions provided
  5. Can you make you code more efficient, perhaps by using a for loop?
  6. What happens if you change the value of SIDE?
  7. Draw a 10×10 chessboard

Extension

The following function draws a hexagon:

def hexagon():
  for n in range(6):
      turtle.forward(50)
      turtle.left(60)
  1. Use the function to draw a honeycomb pattern
  2. Can you make the honeycomb cover the whole screen?

Python Course 1: Turtle Graphics

Useful Code

Moving the Turtle

turtle.forward(100)
turtle.back(50)
turtle.right(90)
turtle.left(45)
turtle.goto(10,10)
turtle.home()
turtle.setheading(0)

Changing the Pen

turtle.pencolor('red')
turtle.penup()
turtle.pendown()
turtle.pensize(4)

Changing the Board

turtle.reset()
turtle.bgcolor('blue')
turtle.showturtle()
turtle.hideturtle()

Exercise

Draw the following

  1. A square with sides of length 100
  2. An equilateral triangle with sides of length 80
  3. A noughts and crosses board
  4. Draw a star by turning an angle of 144 degrees.
  5. A red hexagon on a blue background.

Lesson 2

The following program draws a purple square with a black border. Note the use of begin_fill() and end_fill()

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.end_fill()

The above requires a lot of cut and paste code: always a sign that there is a better way of doing things. Here’s one way:

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()

for times in range(4):
    turtle.forward(100)
    turtle.left(90)

turtle.end_fill()

We are going to be drawing lots of squares. We can define the  code to draw a square as a function, that way we can reuse it. (Learning  to use functions is the main reason we are using turtle graphics!)

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
square()
turtle.end_fill()

We can add a size parameter to the function. Now we can draw squares of different sizes.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

square(50)
square(100)
square(200)

Exercise

1) Enter the following code and run it. Make sure you understand what it’s doing.

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

for n in range(8):
    square()
    turtle.right(45)

2) What do you think the following code will do? Enter it and run it.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

for n in range(8):
    square(20*n)

3) Define a function to draw a triangle.
4) Use your triangle function to draw the following shape

Extension

  1. Write a function to draw a pentagon
  2. Write a function to draw a hexagon
  3. Draw a function that accepts a parameter number_of_sides that draws a  polygon with that number of sides
  4. Write a function to draw a chessboard
  5. Write a function to draw a honeycomb