0% found this document useful (0 votes)
6 views10 pages

CHAPTER 7 - Platform Technologies

The document provides lecture notes on Python sequences, specifically focusing on tuples and dictionaries. It explains the characteristics of tuples as immutable data structures and demonstrates how to create and manipulate dictionaries for storing key/value pairs. Additionally, it covers error checking in Python using try and except blocks to handle exceptions gracefully.

Uploaded by

rheabythea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

CHAPTER 7 - Platform Technologies

The document provides lecture notes on Python sequences, specifically focusing on tuples and dictionaries. It explains the characteristics of tuples as immutable data structures and demonstrates how to create and manipulate dictionaries for storing key/value pairs. Additionally, it covers error checking in Python using try and except blocks to handle exceptions gracefully.

Uploaded by

rheabythea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

1

BUCAS GRANDE FOUNDATION COLLEGE


Socorro, Surigao del Norte

PLATFORM TECHNOLOGIES

Lecture Notes

Prepared by:

Romnick G. Canta
2

Course Topics

Chapter 7: Python Sequences


 Python Tupples
 Python Dectionaries
 Python Error Checking
3

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.

Try this code. First, set up a list:

candidates = ['Anne', 'Ben', 'Claire', 'Davi', 'Elise', 'Frank', 'Gomez', 'Hali']

To set up a tuple, add this line:

final_four = ('Anne', 'Davi', 'Elise', 'Hali')

Note that the items in your tuple go between round brackets. A list goes between square ones.
Print the both of them out:

for person in candidates:

print(person)

print("==========")

for finalist in final_four:

print(finalist)

With a list, you can add a candidate on the end:

candidates.append('Idris')

Or you can insert a candidate anywhere you like:

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 out your new items to see them displayed:

print("==========")

for person in candidates:

print(person)

However, you can't use append or insert with a tuple. You can use the usual slice operations on
a tuple, though:

print("final four 2", final_four[1])


print("Last two: ", final_four[2:])

And you can create a new tuple from the one you already have:

final_two = final_four[1] + final_four[2]


4

print("FINAL TWO: ", final_two)

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.

Add the following to a new Python file:

player = {'Name': 'Kranach'}

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:

player = {'Name': 'Kranach', 'Role': 'Warrior'}

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:

player = {'Name': 'Kranach', 'Role': 'Warrior', 'Strength': 7}

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:

player = {'Name': 'Kranach', 'Role': 'Warrior', 'Strength': 7, 'Luck': 6, 'Stamina': 8}

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:

for key, value in player.items():

print(key, ":", value)

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

You can just print the keys:

for key in player:

print(key)

Try the code for yourself. Add a print line as a separator:

print("=========")

Your code will look like this:

And the output window will look like this:

You can also just print just the values:

for value in player:

print(player[value])

Notice how the value is printed above - with a pair of square brackets after the dictionary name:

player[value]

Another way to get at the value is with the get method:

player.get('Role')

Between round brackets, you type the name of the key whose value you want to access.

Add items to a Python dictionary


6

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 the keys and values out like before:

print("=========")

for key, value in enemy.items():

print(key, ":", value)

Your code will look like this:

Run your program to see the output:


7

Delete items from a Python dictionary

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"]

This would remove the key and its value.

Using Python Dictionaries

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.

Let's have a title. Add this to your code:

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:

if enemy.get('Stamina') > player.get('Stamina'):

If it is, display a message:


8

print("Warlock Wins Stamina Battle")

We can test if they are both equal and display a suitable message:

elif enemy.get('Stamina') == player.get('Stamina'):

print("Draw")

If neither of these are true then the player must have won:

else:

print("Warrior Wins Stamina Battle")

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

Python Error Checking

In a previous section, you set up a function that printed a simple error message:

def error_message()

print("Something went wrong")

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:

number = input("Enter a number: ")

Now print it out with this:

print("Your number times 10 is:", int(number) )

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:

ValueError: invalid literal for int() with base 10: 'one'

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:

# YOUR CODE HERE

except exception_type:

# YOUR ERROR MESSAGE HERE

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.

Change your code to this:

number = input("Enter a number: ")

try:

print("Your number times 10 is: ", int(number))

except:
10

print("Was that a number?")

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:

Too broad exception clause. Do not use bare except

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:

print("Was that a number?")

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.

You might also like