Python Next Steps
Python Next Steps
Chapter 1
Data types
In this chapter you will:
• make a version of MyMagic8Ball that is much shorter than the one from Python Basics.
Data types
In Python Basics you learned about strings (bits of text), integers (whole numbers) and
I’m back!
floats (numbers with a decimal point). These are examples of data types. There are more!
In this chapter we will look at some new data types: tuples, lists and dictionaries. These new
data types are all called container data types because they store more than one piece of
data. For example, they can store several strings. They do so in different ways and have their
own advantages and disadvantages.
A string is rather like a container because it stores a whole sequence of letters or numbers (or
a mixture of both). In Python Basics we learned that there are several functions we can use on
strings. We can also use many of these functions on tuples, lists and dictionaries.
Chapter 1: Data types 7
Tuples
A tuple is the simplest of our new data types. They can store strings, integers and other data
types. Here is an example of a tuple that stores four strings, each separated by a comma:
Each value in a tuple is separated by a comma. Unlike variables, we cannot change what is
stored in a given tuple.
Each value in the tuple has an index starting from 0. So, print(my_tuple[1])for the
example above produces the output two. Look at how this works below.
A tuple.
Chapter 1: Data types 8
MyMagic8Ball
In Python Basics we wrote a small application called MyMagic8Ball that used the random
module and the functions print(), input() and randint(). Here is the code:
import random
# write answers
ans1="Go for it!"
ans2="No way, Jose!"
ans3="I'm not sure. Ask me again."
ans4="Fear of the unknown is what imprisons us."
ans5="It would be madness to do that!"
ans6="Only you can save mankind!"
ans7="Makes no difference to me, do or don't - whatever."
ans8="Yes, I think on balance that is the right choice."
print("Welcome to MyMagic8Ball.")
print("shaking ...\n" * 4)
Now see how much easier and shorter the code is if we include a tuple:
import random
answers = (
"Go for it!",
"No way, Jose!",
"I'm not sure. Ask me again.",
"Fear of the unknown is what imprisons us.",
"It would be madness to do that!",
"Only you can save mankind!",
"Makes no difference to me, do or don't - whatever.",
"Yes, I think on balance that is the right choice."
)
print("Welcome to MyMagic8Ball.")
print("shaking ...\n" * 4)
# exit nicely
input("\n\nPress the RETURN key to finish.")
The tuple
We have to separate the strings in the tuple answers with commas. Starting a new line after
each comma makes the code much easier to read.
The input() function listens to the keyboard entry and waits for the return key to be
pressed. It then returns the keyboard input as a string, which we store in the variable
question.
question = input("Ask me for advice then press ENTER to shake me.\n") Are you are a bit confused
about when to use round brackets
and when to use square brackets?
variable name to access string that is printed out, Basically, when we create a tuple we
the keyboard input giving instructions to the user wrap its contents in round brackets.
Whenever we call an indexed value
from the tuple, we put the index
The randint() function (its position in the list) in square
brackets.
choice = random.randint(0, 7)
This line of code asks the randint() method in the random module to select a random
number from 0 to 7. This number is then stored in the variable called choice. (A method is
a function in a class.)
Finishing off
print(answers[choice])
This uses the random number choice as the index in the answers tuple. This line selects
the string that was randomly chosen from the tuple and prints it.
Experiment
The two scripts are available from the companion website
(www.codingclub.co.uk). Try them both out and check that they
do the same thing.
Just as with tuples, each value in the list has an index starting from 0 and each value is
separated by a comma.
You can see that both a list and a tuple provide the same output. So, when would we use a
list instead of a tuple? We would choose a list rather than a tuple if we want our program to
add, remove or change an item within the list.
or
key value
You might have noticed that dictionaries require a different structure within the brackets to
assign keys to the values. They use a colon ‘:’ to separate the value from its key.
Delving Deeper
What’s the difference?
Strings, tuples and lists are all indexed ordered containers; the values are automatically given an index
based on the order in which they were input. Dictionaries have keys that you provide and the key–value
pairs are not stored in a particular order. Strings and tuples have their content set at creation and cannot be
changed by a program directly. Lists and dictionaries are containers in which the values can be added to and
changed in a variety of ways.
It is also possible to create empty containers like this:
my_string = ""
my_tuple = ()
my_list = []
my_dictionary = {}
Useful functions
Table 1.1 provides a list of useful functions you can use on strings, tuples, lists and
dictionaries. You can also find it in Appendix 1. The table assumes the following containers
have been created:
Chapter summary
In this chapter you have:
We will explore these new data types further in this book. Here are just a few ideas
that will help you refresh your coding skills from Python Basics. (As dictionaries are the
hardest to use, we will wait until you have learned a little bit more before providing any
puzzles involving them.)
Puzzle
Write a new version of MyMagic8Ball using a list instead of a tuple. It should work in exactly
the same way if you get it right because lists can do everything tuples can and more.
Challenge
This is a challenge from Python Basics so although you may be a bit rusty you should be
able to manage it. Hopefully it brings back happy memories for you.
1 Add some code to myMagic8Ball2.py (Code Box 1.2) so that the Magic8Ball says “Hi”
and asks for the user’s name at the start of the game.
2 It should then store the input in a variable such as user_name.
3 Change the code so that the Magic8Ball talks to the user using their name. At the end
for example, it could say: “Thanks for playing, [Name]. Please press the RETURN key to
finish.”
You are destined to
There are several ways to do this. become a famous computer
To see one answer go to www.codingclub.co.uk/book2_resources.php. scientist one day!
Idea
Change the Magic8Ball game into a fortune cookie game. You could call it
myFortuneCookie.py.