CHAPTER 7 - Platform Technologies
CHAPTER 7 - Platform Technologies
PLATFORM TECHNOLOGIES
Lecture Notes
Prepared by:
Romnick G. Canta
2
Course Topics
CHAPTER 7
PYTHON SEQUENCES
Python Tuples
In an earlier section, you learned about the Python list. Closely related to the list is something
called a tuple. The difference is that a tuple can't be added to after you've set one up. You can't
delete items from your tuple, either. They are immutable.
Note that the items in your tuple go between round brackets. A list goes between square ones.
Print the both of them out:
print(person)
print("==========")
print(finalist)
candidates.append('Idris')
candidates.insert(0, 'Able')
Here, the zero means insert 'Able' at the start of the list. If you wanted to insert an item into, say,
the third position, you'd do this:
candidates.insert(2, 'Cara')
print("==========")
print(person)
However, you can't use append or insert with a tuple. You can use the usual slice operations on
a tuple, though:
And you can create a new tuple from the one you already have:
If you need a data structure that can't be added to or subtracted from, use a tuple. In the next
lesson, you'll learn about the Python dicitionary.
Python Dictionaries
A dictionary in Python is a way to store Key/Value pairs. They are called associative arrays in
other programming languages. Let's see how they work.
You set up a dictionary using curly brackets. The following would set up an empty dictionary:
empty_dictionary = {}
The good thing about dictionaries is that they can store a mixture of values. You can store strings
and numbers, for example.
This sets up a dictionary with one item. The key is Name. The value for that key is Kranach.
Notice that the key is a string and therefore surrounded with quote marks. You need a colon next.
The colon comes after your quote marks. The value you want for this key comes next. Here, we're
storing a person's name as the value for the key.
You add other items in your dictionary after a comma. Add this to your player dictionary:
The new key is Role. The value for the key is Warrior. We now have a dictionary with two keys.
Both values for the two keys are strings. But your dictionary can also hold numbers. Add a third
item to your dictionary:
The new key is called Strength. The value for the key is a number, this time.
Your dictionary can hold as many items as you need. Add two more items:
The new keys are Luck and Stamina. The value are also numbers, 6 and 8.
Let's print something out and see what we've got. Add this for loop:
We can use the items methods on our player dictionary. This allows you to cycle through all the
items in your dictionary. The parts we need can then be stored in the two variables that we've
called key and value. We are then printing theses out, separated by a colon.
Run your code and you should see this in the output window:
Name : Kranach
Role : Warrior
Strength : 7
Luck : 6
Stamina : 8
5
print(key)
print("=========")
print(player[value])
Notice how the value is printed above - with a pair of square brackets after the dictionary name:
player[value]
player.get('Role')
Between round brackets, you type the name of the key whose value you want to access.
You can add items to a Python dictionary. They are not immutable like tuples. Try this. Set up an
empty dictionary called enemy:
enemy = {}
To add a new item, you need the dictionary name followed by a pair of square brackets. In
between the square brackets, type a new key in quote marks. The value for your new key goes
after an equals sign:
enemy['Name'] = "Vilor"
(NOTE: PyCharm will complain about the enemy = {} line. It will underline it in grey and say, "The
dictionary creation could be rewritten as a dictionary literal". It's trying to tell you to set up your
dictionaries as we did before. You can switch the warning off by going to File > Settings > Editor
> Inspections. In the list in the middle, uncheck the item for "Dictionary creation … ". Click Apply
and the warning should go away.)
Now add the other dictionary items:
enemy['Role'] = "Warlock"
enemy['Strength'] = 8
enemy['Luck'] = 9
enemy['Stamina'] = 6
print("=========")
You can delete an item from your dictionary. The syntax is this:
del dictionary_name["KEY_NAME"]
So if you wanted to remove the Luck key from the enemy dictionary, it would be this:
del enemy["Luck"]
You can compare one dictionary value to another. In the code below, we'll compare the Stamina
keys and see which one is the greater.
print("------------------------")
print(enemy.get('Role') + " versus " + player.get('Role'))
print("------------------------")
The output would be this, from the three lines of code above:
------------------------------------
Warlock versus Warrior
-------------------------------------
We're using get to get the Role key from both the enemy and player dictionaries.
We can use an if statement to test if the value from the enemy Stamina key is greater than the
value from the player Stamina key:
We can test if they are both equal and display a suitable message:
print("Draw")
If neither of these are true then the player must have won:
else:
Add the if statement to your code and it will look like this:
When you run the program, the output would be this with our values:
------------------------
Warlock versus Warrior
------------------------
Warrior Wins Stamina Battle
In a previous section, you set up a function that printed a simple error message:
def error_message()
We could then call this function if we felt something was going to go wrong. There is another way
to check for errors, though. With a try … except block.
The idea is to try some code. If something codes wrong, you catch it in an except part. The
except keyword is short for exception. Let's see how it works.
Start a new project for this. In a new Python file, enter the following:
So the user enters a number, which is then placed in the number variable. We try to convert that
number to an integer with int(number) inside of the print statement.
9
Run your code. In the output window, type the text 'one' instead of the number one:
Press the enter key on your keyboard and you should see this error message:
If you get an error like that it's called an exception. This one tells you which line is causing the
problem. It also says this:
This type of error this is called a ValueError. You normally see it when Python has a problem
with the numbers you enter. Our ValueError was because we tried to convert the string 'one' to
an integer. The string was coming from the input box. We didn't check to see if it was a digit or
not, like we did before. Other types are ZeroDivisionError, when you try to divide a number by
zero, and NameError when Python can't recognise a variable name you used in your code.
You can check for exceptions like the one above with a try … except block. The format is this:
try:
except exception_type:
So you need the word try followed by a colon. The code you want to try goes next, on indented
lines. Next, you need the word except followed by an exception type. After a colon, add your error
message.
try:
except:
10
Don't run your code yet. Have a look at what PyCharm has underlined in your code. It has
underlined the word except. Hold your mouse over except and you'll see a message:
You won't get an error if you run your code, however. Enter the text 'one' instead of the number 1
and you'll see 'Was that a number?' printed in the output window.
The reason PyCharm is flagging up a problem is because it's highly recommended that you have
one of the exception types after the keyword except. For our code, the type was ValueError.
Change the exception line to this:
except ValueError:
The underline should go away in PyCharm. You still get the same error message when you run
the code, though.
The point of using the try … except block, however, is so that your programs don't crash. If they
are crashing, make a note of the type error, such as the ValueError above. You can then add that
type error after the except part.