Variables Strike Back!

Learning Objectives

  • Revise the difference between the data types string, int, char float and bool
  • Trace the value stored in a variable throughout a program.
  • Concatenate Strings.
  • Create and manipulate Substrings.

Learning Outcomes

All must use different types of variable in a program, understanding the differences between these variables

Most should complete the above, and swap values between variables, predicting the values stored at any point of a simple program. Also cast variables where approriate.

Some could complete the above, and start to manipulate strings effectively, returning substrings and concatenating.

 

Starter

In our second Python revision session, we’ve got even more to do, so the starter is  to open up IDLE (or Visual Studio if your teacher tells you to)!

Main
Let’s start looking at variables.

Open IDLE(Python GUI) as you did last lesson,  and open a new window.

You’ve realised now that whatever you throw inside-

print()

is sent to the Python shell as Output.
If you want to display a sentence, you would run

print(“This is a sentence”)

or
print(“Hello”)

or

print(5)

Save your code as “dataTypes.py” and run it.
Wait a minute…   Why did “Hello” have speech  marks, while 5 didn’t?


 

Data Types.

Exercise

  1. Write down answers to the following:
    1. First name
    2. Surname
    3. Date of birth
    4. Age in years
    5. Have you seen “The Maze Runner”?
    6. Shoe size
    7. Date of last visit to the dentist
    8. Place of birth
    9. Number of books in bag
    10. Height (in metres)Look at your answers.  There are different TYPES of data here, some of which repeat.  Can you sort them into 4 (or 5) categories?

You will find your answers fall into different categories: numbers (some with decimal places), Words, “Yes” or “No” type answers, Dates etc. You could say there is a correct “Type” of answer to each question.  “Harry” is not your date of birth, and and you wouldn’t say there are 1.82 books in your bag.

In programming there are several very common data types, which are repeated frequently.

We’re going to look at just 5:

int, float, char, string and boolean.

Click here to open a worksheet, and fill in the table (question 1) with your teacher’s help.  If you aren’t too sure, all the answers can be found in the Python documentation.

So each data type has a very different use.  We’ll look at them individually.


Char.

A Character (char) is simply a character/symbol/number in fact it is easiest to think of a char as something you can “produce” with a keyboard.  In Python it should be enclosed in single quotes e.g  ‘a’


 

Integer.

Integers (int) are whole numbers, so we can perform calculations on them, as we saw last lesson.  We can store integers in variables and still perform calculations.

Look at this code:

scs1

Write down what you think the output will be.  Try the code and see if you’re right.

What would happen if you added more code:
number3 =numberOne * numberTwo
print(numberThree)

Try the code and find out.

Now add this code:
number3 =numberOne / numberTwo
print(numberThree)

What will the result be?  Run the code and…
Oh dear!  That wasn’t quite what we expected.  So in a division, we can’t split up a whole number.

**Click here for more information**


Float.

A float, or floating point number lets us use a decimal point.  Change your code so that numberOne is now 5.0 and numberTwo is 3.0

Now run the code, and you should see a more predictable result.

Unfortunately, this turns everything into floating point numbers,  which look more confusing.  We were happy with integers, until we tried a division.
We need a way to turn the answer into a float, without affecting everything else.  This is called casting.

Change your code so that numberOne and numberTwo are both integers again.

Now change the line containing the division to read:

number3 = float(numberOne)/float(numberTwo)

Success!

So you can’t just mix and match data types as you wish.  If you want one to behave like another, you must cast the variable.  To do this (as above) write the name of the data type you want, followed by the variable name in brackets.

Go back to the worksheet, and try to trace the values in the program in question 2.

**More information can be found here**

Now let’s have a look at Strings.


Strings

A string is a collection of characters.  If you’re not sure what character refers to, think of anything you can produce on a keyboard ( letters, numbers, punctuation )  we always enclose a string in either single quotation marks:

‘ a nice string ‘

or speech marks:

” a nice string “

As a string is a collection, all the characters go in a specific order (think – it wouldn’t be much good if “hello” was output as “lolhe”!).  This is really useful because it means that each character has a number, starting at 0.

the string “HELLO” would be counted like this:

H |E |L |L |O
0 |1  |2 |3 | 4

Why is this useful? Well, with these index numbers,  we can print single characters.  Try this code:

testString=”this is a string”
print(testString[4])
print(testString[8])

so, using square brackets [ ] we can refer to a single character in a String.  Now add these lines:
print(testString[0:4]) 
What happens?  How about:
print(testString[10:15])

So, using a colon between two index numbers we can print out a segment of the string.  This smaller string is called a substring.

**Click here for more information**


Variables

You’ll see we’ve started to store values of each data type as variables. Remember this simply refers to a block of memory which we label with a name so that we can access the contents, or change it within our program.

Python is a dynamically typed language.  This means that we don’t have to say what Type of variable we are going to make.  Python can tell that:

name = “Sam”

Will create a variable to reference (contain or hold) a String.  It will then place the value  “Sam” in that variable.

After this line of code, whenever we mention name the program will “see” the value “Sam” (until the program changes that value!!)

So we make, or declare  a variable by typing a sensible name for the variable.  We then add or assign a value after the equals “=” sign.

Sensible names?

To start with, the name we choose for a variable must have something to do with the value we’re storing in the variable.

  • name, speed, biscuits, time  are all great examples.  x, thing, b2, one are pretty bad examples.
  • Don’t start your variable name with a capital letter!
  • You mustn’t have any spaces in your variable name, or characters (except the underscore).  If your name has two or more words, use “camelCase” eg:
    numberOfFish, dinnerTime, robotActuatorOne
  • Avoid numbers(1,2,3 etc) in variable names.  If you must include them, NEVER start the name with a number
  • some words in Python are reserved for special functions.  These can’t be used as variable names.  print, if, else, while, return, break are all examples.   As a general rule, a keyword will change colour when typed in, so you’ll know not to used it as a variable name.

 


Mixing it up

We have learned that int and string are two different types, and therefore can’t be mixed in one statement without casting.  Luckily Python gives us a good way to do this in a print() statement. We can separate strings and other types by commas, and Python will automatically concatenate everything to one big string.

Confused? Try this:

scs2

Of course, this only works with a print statement.  Anywhere else, you must cast strings.

Challenge:

Write a program which:

  • asks the user for her name and stores it in a variable
  • asks the user to choose a number and stores this in a variable.
    **Hint** if you use input(), the input data from the keyboard is automatically a string.  You will need to cast this data
  • The program will now print:
    “Hello, [username].  I can do the [usernumber] times table”
    ” 1 x [usernumber] is [answer] “
    ” 2 x [usernumber] is [answer] “
    ” 3 x [usernumber] is [answer] “

Print your program out and write down a quick explanation of how the code works before putting it in your folder/book.