<<

Lesson 4 - Printing and variables In this lesson we are going to take a step back from Python Turtle and look at regular Python. We are going to learn more about the print statement and use it to learn about variables.

We have previously learned about the print statement. This command will print a message put between double quotation marks (“”) or single quotation marks (‘’) to the console.

By default the console will move to a new line after every print statement. The code on the left will produce the output on the right.

This default can be changed by adding a second argument/parameter to the print command. The code below will now end the first line with a comma and the second line with a full stop, creating the output on the right.

Tasks 1. Print your name to the console. 2. Change the ending of your print statement to an exclamation point.

1 Special (escape) characters

The text in our print statement between quotes is called a string. This string represents what will be printed to the console. In Python the \ () symbol is known as a special or an escape character.

The escape character when added to a second character is used to represent certain whitespace symbols and allows us to use certain symbols without confusion.

\n New line

\t Tab

\b Backspace

\\ Backslash

\’ Single quote

\” Double quote

Tasks 1. Write a print statement for each of the special characters 2. Print out the message following message in one print statement a. 3. Use *, \n and \t to print out the pattern below

a.

2 Printing numbers

Numbers can be printed in a similar way to strings. To print a single number simply write print(15). We can also use the print statement to complete simple math and print the result.

If we in fact want to print out the math equation we can do this in two ways. The first way is to change the numbers into a string.

The second method simply splits up each part of the equation using a comma.

Note how there is an additional space between the numbers in the second method. This can be ​ changed by adding in a final argument. This argument specifies what symbols to put after each comma separated argument and works similarly to the end argument we saw previously.

Tasks 1. Print the answer to 157-49. 2. Print the equation 157-49. 3. Print the equation 157-49 and change the separator to a tab.

3 Variables

We have already learned a small amount about variables, but we will recap variables here and learn more about them.

A variable is used to store information in our program. You can think of a variable like a box that we can put information into. This box then has a name and if we want the information, we write the name of the box and the program will get the information stored in the box.

The information in the box can change or vary and this allows us to use variables to do many different things in our program.

Creating a variable

To create a variable in Python we first need to give it a name. It is important that we choose a name that makes sense and that reminds us of the information the variable will store.

Variables names must ● Not start with a number ● Not include spaces ● Not contain special characters such as @, /, -

In Python the convention when creating a variable name is to write the name in lower Camel case format or using underscores.

Lower Camel case is when the first word begins with a lowercase letter and any subsequent words begin with an uppercase letter. For example, houseNumber, horizontalPosition.

Using underscores would look like this. house_number, horizontal_position.

In these notes I will be using lower Camel case format.

Correct Names Incorrect Names

aVariable A variable

item27 27item

grade_7 grade-7

atSpace @Space

4 Assigning a value to a variable

Once we have created a name for our variable we need to assign it a value. To assign a value to a variable we use the = symbol. Some examples of this are below.

The code above creates four variables and assigns each one a different variable type. The four variable types are, in order; Integer int Whole number

Float float Floating point numbers (decimal numbers)

String str Text, collections of characters

Boolean bool True or false

We can use the print function with the type function to find out the type of any variable. The code below shows how this is done and the output we get.

Python is unusual in programming languages as it allows you to change the type of a variable as the program is running.

We are also able to change the variable type using functions such as float() and int(). This is called casting.

5 When you are casting a value it is important to check that it is doing what you expect. When we run the program below, we can see that we are losing accuracy when we cast 5.1 to an integer and it is important to consider this.

Below are some more examples of casting and their results.

Tasks 1. Create a variable of each variable type. 2. Print all of the variables in a single print statement. 3. Change each of the variables to a new variable type and print out the new type. 4. Cast the string “5.51s” to a float and see what happens. 5. Cast the string “5.51s” to a boolean and see what happens. 6. Cast a blank string “” to a boolean and see what happens.

6 Arithmetic operations

Python can perform many different calculations on numbers (ints and floats). Below is a table of the basic operations.

Operator Symbol Example Result Example Result

Add + answer = x+y 5+7 12

Subtract - answer = x-y 5-7 -2

Multiply * answer = x*y 5*7 35

Divide / answer = x/y In Python 3 it is always 13/2 6.5 a float. In Python 2 it can produce an integer

Floor divide // answer = x//y The number before the 13//2 6 decimal point after division. Always an integer

Modulus % answer = x%y The remainder in 13%2 1 whole numbers after division

Exponent ** answer = x**y X to the power of y 2**3 8

As in maths the order of operations is important. The table below shows the order.

Order Operator Operation

1 () Brackets

2 ** Indices (also known as exponent or to the power of)

3 *, /, //, % Multiplication, division, floor, division, remainder

4 +, - Addition, subtraction

7 User input

This is input from the user of the program. We can use the input() function to collect this information. This function will print out a message and wait for the user to type a reply and hit enter.

Once we have the reply we need to do something with it. The simplest thing is to store it in a variable for future use. Using the name example, the code might look like this.

We are going to use the input function to allow the user to perform some simple calculations. If we ask the user for a number and we want to use this in an equation we will need to cast it to a float.

This code requires the user to input two numbers and will output the sum of those numbers.

Task 1. Write a program that asks the user for two numbers and then calculates the sum, the average and the remainder after division of these numbers. 2. Write a program to convert a fahrenheit temperature given by the user into celsius. Use the formula: Celsius = (5/9) * (Fahrenheit - 32) 3. The weight of something on the moon is 16.5% of what it is on Earth. Write a program that asks the user for their weight and displays what their weight on the moon is. 4. Write a program that first calculates the size of a garden, given the width and length. Returns the value, then asks the user how many square meters they can mow in an hour and calculates the time to mow the whole garden. Finally ask the user how much they charge per hour and work out how much it would cost to mow the whole garden.

8 For loops

We have used for loops previously, but we are going to cover them again here and learn a little more about them.

The code above shows what a basic for loop might look like. We have used these previously in Python Turtle and should know that the for loop above will run 6 times. The part we haven’t talked about is the letter i. The i is a variable that counts through the numbers in range. In this ​ ​ ​ ​ example it begins at 0 and prints out all the numbers upto, but not including 6.

We can also add a second argument to the range that will tell us what number i should start at. ​ ​

A for loop must always consist of: 1. The word for ​ 2. A loop control variable 3. The word in ​ 4. A way of setting the number of times that the loop will run, e.g. range() 5. A colon ​ 6. A next line of code that must be indented

Tasks 1. Write a for loop to print the numbers from 0 to 3 (including 3) 2. Write a for loop to print the numbers from 0 to 9 (excluding 9) 3. Write a for loop to print the numbers from 1 to 9 (including 9) 4. Write a for loop to print the numbers from 10 to 20 (including 20)

9 What happens when we only want to print out even numbers? One solution is to perform a little bit of maths and multiply each number by 2. The code below will print out all even numbers.

The second solution is to add a third parameter to the range function. This parameter controls the step size. The solution below will also print out only the even numbers.

We can also easily change this to print out only odd numbers. If we try doing this with maths it starts getting a little more complicated. The two pieces of code below produce the same output.

Finally, what if we want to start at a big number and count down? We can easily do this, we just need to change some of the arguments. The code below starts at 10, counts down in 2’s and stops before it prints 0.

range() Explanation

One argument range(5) - Lists the integers from 0 upto but not including 5.

Two arguments range(1,5) - Lists the integers from the first argument (1) upto but not including the second argument (5)

Three arguments range(1,10,2) - Lists the integers from the first argument (1) upto but not including the second argument (10) in steps of the third argument(2). Also works counting down.

10 Tasks 1. Print the even numbers between 0 and 20 (including 20) 2. Print the odd numbers between 20 and 40 3. Print every 5th number between 0 and 100 (including 100) 4. Print every number between 10 and 0, counting down 5. Print every third number starting at 30 and counting down (including 0) 6. Print every 7th number between 100 and 70 counting down

11