Python Lesson Two
Python Lesson Two
Python Lesson Two
Python
Lesson Two
Data Types
Think back to last lesson when we learned about variables.
na m
e
Data Types
Python has four data types:
• String (text or alphanumeric information);
• Integer (a whole number, a number which is not a fraction);
• Float (a number which can be a fraction);
• Boolean (can only be one of two values, True or False).
Float 3.142
String Monty
Boolean True
Integer 47
String “1234”
Did this answer surprise
you?
Any data enclosed within
“quotes” is always a
string!
Integer -23
• type(1234)
• type(76.54)
• type(True)
• type(“Monty”)
• type(“4321”)
Type Casting
In programming, we sometimes need to change the data type of
information. This is known as type casting.
In Python, type casting is quite easy.
• input works fine with strings, but we have to take care with
numbers.
• Try entering this Python code into the script mode window,
then save and run your program:
Type Casting
According to our program, 6 + 7 = 67!
What’s gone wrong?
Python thinks that any information we
enter using input is always a string.
In other words, “6” + “7” = “67”.
Instead of adding the numbers together, the “6” and “7” are just
joined together. (The technical term for adding strings is
concatenation.)
Try your program again with different numbers just to make sure.
To fix this problem, and enable us to add our numbers together,
we simply make use of the type casting method int().
Let’s see this in action …
Type Casting
Change your program by including int as shown here.
Be careful to add an extra bracket at the end of the first two lines:
Quick now,
seconds are
ticking away!
Snakes Alive!
Possible solution – easy version:
Key Terms
Adding strings together is
called concatenation
(con - cat - en - ay - shun).
Let’s Bring It All Together
Type Casting
In programming we sometimes need to change the data
type
of information. This is known as type casting.
Annotation
Programmers use annotation to explain their code.
Annotation is useful for when programs start to get longer,
or if we come back to a program that we’ve not looked at for a
while.
In Python we use a # at the start of each line of annotation.
When we run our programs, Python ignores any lines that start
with a #.
Annotation is for humans, not computers. Using annotation is
very good programming practice, and will help you make less
errors with your code.
Rate Your Progress
Red Light: you have understood some of the
objective and you will think about it some more
later on, perhaps asking a friend or teacher for
help.
Amber Light: you have understood most of the
objective and you are happy with your progress.
Success Criteria:
• To know why programming languages use data types.
• To use type casting in Python to enable numerical
inputs.
• To understand the importance of annotating code.
Nailing It Down
We have learned a lot today about data types and annotation in
Python.