Python 4
Python 4
Sets are unordered collection of data items. They store multiple items in a single variable. Set
items are separated by commas and enclosed within curly brackets {}. Sets are unchangeable,
meaning you cannot change items of the set once created. Sets do not contain duplicate items.
Example:
print(info)
Output:
Here we see that the items of set occur in random order and hence they cannot be accessed
using index numbers. Also sets do not allow duplicate values.
Quick Quiz: Try to create an empty set. Check using the type() function whether the type of
your variable is a set
Example:
print(item)
Output:
False
Carla
19
5.9
32 - Joining Sets
Sets in python more or less work in the same way as sets in mathematics. We can perform
operations like union and intersection on the sets just like in mathematics.
Example:
cities3 = cities.union(cities2)
print(cities3)
Output:
Example:
cities.update(cities2)
print(cities)
Output:
cities3 = cities.intersection(cities2)
print(cities3)
Output:
{'Madrid', 'Tokyo'}
Example :
cities.intersection_update(cities2)
print(cities)
Output:
{'Tokyo', 'Madrid'}
Example:
cities3 = cities.symmetric_difference(cities2)
print(cities3)
Output:
Example:
cities.symmetric_difference_update(cities2)
print(cities)
Output:
Example:
cities3 = cities.difference(cities2)
print(cities3)
Output:
Example:
print(cities.difference(cities2))
Output:
Set Methods
There are several in-built methods used for the manipulation of set.They are explained below
isdisjoint():
The isdisjoint() method checks if items of given set are present in another set. This method
returns False if items are present, else it returns True.
Example:
print(cities.isdisjoint(cities2))
Output:
False
issuperset():
The issuperset() method checks if all the items of a particular set are present in the original set.
It returns True if all the items are present, else it returns False.
Example:
print(cities.issuperset(cities2))
print(cities.issuperset(cities3))
Output:
False
False
issubset():
The issubset() method checks if all the items of the original set are present in the particular set.
It returns True if all the items are present, else it returns False.
Example:
print(cities2.issubset(cities))
Output:
True
add()
If you want to add a single item to the set use the add() method.
Example:
cities.add("Helsinki")
print(cities)
Output:
update()
If you want to add more than one item, simply create another set or any other iterable
object(list, tuple, dictionary), and use the update() method to add it into the existing set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.update(cities2)
print(cities)
Output:
remove()/discard()
We can use remove() and discard() methods to remove items form list.
Example :
cities.remove("Tokyo")
print(cities)
Output:
The main difference between remove and discard is that, if we try to delete an item which is not
present in set, then remove() raises an error, whereas discard() does not raise any error.
Example:
cities.remove("Seoul")
print(cities)
Output:
KeyError: 'Seoul'
pop()
This method removes the last item of the set but the catch is that we don’t know which item
gets popped as sets are unordered. However, you can access the popped item if you assign the
pop() method to a variable.
Example:
item = cities.pop()
print(cities)
print(item)
Output:
del
del is not a method, rather it is a keyword which deletes the set entirely.
Example:
del cities
print(cities)
Output:
NameError: name 'cities' is not defined We get an error because our entire set has been deleted
and there is no variable called cities which contains a set.
What if we don’t want to delete the entire set, we just want to delete all items within that set?
clear():
This method clears all items in the set and prints an empty set.
Example:
print(cities)
Output:
set()
Example
if "Carla" in info:
print("Carla is present.")
else:
print("Carla is absent.")
Output:
Carla is present.
33 - Python Dictionaries
Dictionaries are ordered collection of data items. They store multiple items in a single variable.
Dictionary items are key-value pairs that are separated by commas and enclosed within curly
brackets {}.
Example:
print(info)
Output:
Example:
print(info['name'])
print(info.get('eligible'))
Output:
Karan
True
Example:
Output:
Example:
print(info.keys())
Output:
Example:
print(info.items())
Output:
update()
The update() method updates the value of the key provided to it if the item already exists in the
dictionary, else it creates a new key-value pair.
Example:
print(info)
info.update({'age':20})
info.update({'DOB':2001})
print(info)
Output:
clear():
The clear() method removes all the items from the list.
Example:
info.clear()
print(info)
Output:
{}
pop():
The pop() method removes the key-value pair whose key is passed as a parameter.
Example:
info.pop('eligible')
print(info)
Output:
popitem():
The popitem() method removes the last key-value pair from the dictionary.
Example:
info.popitem()
print(info)
Output:
del:
we can also use the del keyword to remove a dictionary item.
Example:
del info['age']
print(info)
Output:
If key is not provided, then the del keyword will delete the dictionary entirely.
Example:
del info
print(info)
Output:
Python allows the else keyword to be used with the for and while loops too. The else block
appears after the body of the loop. The statements in the else block will be executed after all
iterations are completed. The program exits the loop only after the else block is executed.
Syntax
for counter in sequence:
else:
Example:
for x in range(5):
else:
Output:
iteration no 1 in for loop
36 - Exception Handling
Exception handling is the process of responding to unwanted or unexpected events when a
computer program runs. Exception handling deals with these events to avoid the program or
system crashing, and without this process, exceptions would disrupt the normal operation of a
program.
Exceptions in Python
Python has many built-in exceptions that are raised when your program encounters an error
(something in the program goes wrong).
When these exceptions occur, the Python interpreter stops the current process and passes it to
the calling process until it is handled. If not handled, the program will crash.
Python try...except
try….. except blocks are used in python to handle errors and exceptions. The code in try block
runs when there is no error. If the try block catches the error, then the except block is executed.
Syntax:
try:
#exception
except:
Example:
try:
Output:
Enter an integer: 6.022
Syntax:
try:
#exception
except:
finally:
except ValueError:
else:
print("Integer Accepted.")
finally:
Output 1:
Enter an integer: 19
Integer Accepted.
Output 2:
Enter an integer: 3.142
In the previous tutorial, we learned about different built-in exceptions in Python and why it is
important to handle exceptions. However, sometimes we may need to create our own custom
exceptions that serve our purpose.
class CustomError(Exception):
# code ...
pass
try:
# code ...
except CustomError:
# code...
This is useful because sometimes we might want to do something when a particular exception is
raised. For example, sending an error report to the admin, calling an api, etc.
39 Day39 - Exercise 3: Solution
Create a program capable of displaying questions to the user
like KBC. Use List data type to store the questions and their
correct answers. Display the final amount the person is
taking home after playing the game.
questions = [
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
[
"Which language was used to create fb?", "Python", "French", "JavaScript",
"Php", "None", 4
],
]
levels = [1000, 2000, 3000, 5000, 10000, 20000, 40000, 80000, 160000, 320000]
money = 0
for i in range(0, len(questions)):
question = questions[i]
print(f"\n\nQuestion for Rs. {levels[i]}")
print(f"a. {question[1]} b. {question[2]} ")
print(f"c. {question[3]} d. {question[4]} ")
reply = int(input("Enter your answer (1-4) or 0 to quit:\n" ))
if (reply == 0):
money = levels[i-1]
break
if(reply == question[-1]):
print(f"Correct answer, you have won Rs. {levels[i]}")
if(i == 4):
money = 10000
elif(i == 9):
money = 320000
elif(i == 14):
money = 10000000
else:
print("Wrong answer!")
break
Decoding:
if the word contains less than 3 characters, reverse it else: remove 3 random characters from
start and end. Now remove the last letter and append it to the beginning
# Coding:
# if the word contains atleast 3 characters, remove the first letter and append it at the end
# now append three random characters at the starting and the end
# else:
# simply reverse the string
# Decoding:
# if the word contains less than 3 characters, reverse it
# else:
# remove 3 random characters from start and end. Now remove the last letter and append it to the
beginning