# Sets

Sets in python are same as sets in mathematics and Python allows you to perform operations such as union, intersection, Cartesian etc. A set can be created as follows:

```name_set = {'Eric','Alex','Lisa','Richard'}
print(name_set)
```

You can create a set from a list as follows:

```name_list = ['Eric','Alex','Lisa','Richard']
name_set = set(name_list)
print(name_set)
```

## Union of two sets

Union is used to combine values of two sets into one set:

```set1 = {1,2,3}
set2 = {4,5,6}
set3 = set1.union(set2)
print(set3)
```

## Intersection of two sets

Intersection function delivers a set that has elements that were common in two sets:

```set1 = {1,2,3,4}
set2 = {4,5,6}
set3 = set1.intersection(set2)
print(set3)
```

## subset and superset

issubset() is a method that is used to find out whether a set is a subset of the other set or not. The function returns true if it is a subset or else false is returned.

```set1 = {1,2,3,4,3,4,5,6,9,10}
set2 = {4,5,6}
if set2.issubset(set1):
print("set2 is a subset of set1")
```

issuperset() is a method that is used to find out whether a set is a superset of the other set or not. The function returns true if it is a superset or else false is returned.

```set1 = {1,2,3,4,3,4,5,6,9,10}
set2 = {4,5,6}
if set1.issuperset(set2):
print("set1 is a superset of set2")
```

# Exception Handling

## What is Exception

While executing a program sometimes the normal flow of events may get disrupted if there is a situation that Python is not able to cope with. In such a scenario it will raise and exception. Exception is nothing but a Python object that indicates that the execution of the program was disrupted due to some error. If the exception is not handled properly then the program will be terminated.

Some of the common exceptions encountered in Python are as follows:
1. SystemExit: This exception is raised by a sys.exit() function.
2. ArithematicError: Occurs when there is a problem with arithematic calculation.
3. IOError: When the program faces problem in opening a file.
4. ValueError: when an invalid argument is passed to a function.

Python has defined a number of exceptions and the ones mentioned on top are just a few of them. However you can deal with exceptions with the help of try and except blocks

Whenever you write a complicated code that can create error you must put that code in try block as shown below:

```try:
code
except:
code
```

As you can see in the syntax above, if there is any error encountered in the code written in the try block then the system will straight away go to except block and execute the code written there. Now let’s have a look at an example

```try:
print("let's divide a number by zero")
print(str(1/0))
except:
print("System has encountered an error please check your code")
```

Now let’s try another example:

```try:
print("let's carry out division")
a = input("enter the first number: ")
b = input("enter the first number: ")
print(a/b)

except:
print("System has encountered an error please check your code")
```

The problem with the code above is that input statement provides value in string and we have to first convert the numbers to string in order to print them. Following code will not throw exception.

```try:
print("let's carry out division")
a = input("enter the first number: ")
b = input("enter the first number: ")
print((int(a)/int(b)))

except:
print("System has encountered an error please check your code")

```

# Passing multiple arguments to the functions

We have seen how to write a function and how to pass an argument to it. Advanced level programming often requires functions that can take multiple arguments. The format for multiple arguments is as follows:

```def your_function(arg1,arg2,arg3):
statement 1#
statement 2#
……..
```

Look at the example given below:

```def print_info(arg1, arg2):
print(arg1 + " " + arg2)

arg1 = input("what is the first argument?")
arg2 = input("what is the second argument?")
print_info(arg1, arg2)
```

When you run the code you will be prompted to enter first argument. Type the word “Hello”. For the second word type “World”. The output will be “Hello World”

Now, have a look at the next example:

```def add_info(arg1, arg2, arg3):
sum = int(arg1)+int(arg2)+int(arg3)
print(str(sum))

num1 = input("what is the first number?")
num2 = input("what is the second number?")
num3 = input("what is the third number?")
add_info(num1, num2, num3)
```

As you can see the above example is about addition of three numbers. When you feed in values of numbers, they are taken in as string values. So, in add_info() function the values are first converted to integer. Then to print the values, the sum of the numbers is again converted to a string.

# Comprehension lists

Comprehension lists in Python provide you a very concise and smart way of creating lists. In order to create a comprehension list you will use square brackets that would consist of a ‘for’ statement and it may or may not have more for or if statements.

For better understanding have a look at the following example:

```numbers=[1,2,3,4,5,6,7,8,9,10]
even_numbers=[x for x in numbers if x%2==0]
for element in even_numbers:
print(element)
```

In the above example, even_number is a comprehension list. See how it is created from the numbers list.

Now , have a look at the second example. Here, we try to create list that provides squares of numbers that are given in the numbers list:

```numbers=[1,2,3,4,5,6,7,8,9,10]
sq_of_numbers=[x*x for x in numbers]
for element in sq_of_numbers:
print(element)
```

Now, let’s try to produce a comprehension list that is a cross product of two lists

```color=['red','blue','green']
dress=['frock', 'shirt','skirt']
color_of_dress=[(x,y) for x in color for y in dress]
for element in color_of_dress:
print(element)
```

Have a look at the output. It has two for loops. For every x in colors it looks for every dress in y and then creates the sets.

# Regular Expressions – search function

In the last tutorial we learnt about the match function. In this tutorial we will see how the search function works. The syntax for the search function is as follows:

```re.search(expression, str, flag)
```

The function can take three parameters the same way as in the case of match function. The first one expression refers to the regular expression that you want to match.

‘str’ is the string on which the search operation is performed to match the pattern of the string on which the search is performed.

The search function too has a flag parameter which can help in controlling the match operation.

You have already seen that the expression is nothing but a string of characters, Some characters have literal meaning and then there are some meta characters that hold special meanings. The same identifiers and modifiers are used here as well to create an expression. Mastering the art of writing expression can take time but if you look into it deeply it is very logical.

Creation of expression is same as in case of match function and you will use the same modifiers and expressions.

## Difference between match and search function

At this point it is important to understand the difference between the match and search function. A match function matches the expression only with the beginning however the search function will look through the entire text.

```import re

str_obj = re.compile("hello")
match_obj = str_obj.search("A big hello to the world")
if match_obj == None:
print("Match not found")
else:
print("match found")

```

In the above code if you replace search by match then the output will be “Match not found”.

```import re
match_obj = re.search(r'bea','it is a beautiful day')
if(match_obj):
print("Match found")
else:

print("Match Not found")
```

In the above example we have a string “It is a beautiful day”. We have an expression : r’bea’, where we try to find if anywhere string ‘bea’ appears in the text and as expected a match is found when it encounters the word beautiful. However, this would not work with match function as it will match the expression only with the beginning of the text.

# What are regular expressions?

Regular expressions are required when there is a need to perform high level advanced pattern base search or match strings. Regular expressions itself is a programming language in itself. For working with these expressions a module by the name of ‘re’ is defined in python. While dealing with regular expressions we are going to import this module in our program. There are two important functions that you must know to work with regular expressions:
(1)match function
(2) search function

## match function

In this tutorial we will deal with the ‘match’ function. The syntax for the same is given below;

```Re.match(expression, str, flag)
```

As you can see, the function can take three parameters. The first one expression refers to the regular expression that you want to match.

‘str’ is the string on which the search operation is performed to match the pattern of the string on which the search is performed.

The match function has a flag parameter which can help in controlling the match operation.

Regular functions are compiled into pattern objects. These objects have access to some methods that can help with the searching part. Let’s first take a look at a simple example:

```import re

str_obj = re.compile("hello")
match_obj = str_obj.match("hello world")
if match_obj == None:
print("Match not found")
else:
print("match found")

```

We will now work on other example that would use re object the way we have shown in the syntax, but before we go ahead with that you need to know how to create and expression for search. For this you should have Knowledge of Identifiers and modifiers.

## Identifiers

\d stands for any number
\D stands for anything but number
\s space
\S stands for anything but space
\w stands for character
\W stands for anything but a character
. stands for any character except a new line
\b whitespace around words
\. Looking for a ‘.’

## Modifiers

{} curly brackets define what we expect
+ look for one or more matches
? look for 0 or 1 match
* look for 0 or more matches
\$ look for a match at the end of the string
^ look for a match at the beginning
| either or
[] defines range or variance

```import re
match_obj = re.match(r'b[a-z]a','beautiful')
if(match_obj):
print("Match found")
else:

print("Match Not found")```

Look at the expression: r’b[a-z]a’. Since we are dealing with raw strings the expression is written within r”. We are trying to find out if the word ‘beautiful’ starts with ‘b’ , ends with ‘a’ and has any other small letter from[a-z] range. If yes, then it is a match else not a match. ‘bea’ falls in this range hence the match os found. In the next tutorial we will look at the search function.

# Generators in Python

Generators make the life of a developer very easy but it is a bit tricky to understand. The idea behind having a generator is to create an iterator but it is different from what we have seen till now. Generators are very simple functions in nature and they return an iterable set of elements one by one.

So far we have seen or worked with functions that return a single value but if there is a need to create a function that return multiple values what would you do? Well, in such cases, developers go for generator with a ‘yield’ statement. Generators allow coders to easily retrieve series of values.

The main difference between a generator and other iterator is that every generator is an iterator but the vice versa does not hold true. Look at the code below:

```def student_name():
yield("Alex")
yield("Mike")
yield("Mary")
yield("Martin")
yield("Erin")
stu = student_name()
print(stu.__next__())
print(stu.__next__())
print(stu.__next__())
print(stu.__next__())
print(stu.__next__())
```

when a call is made to the generator, it returns an object, no statements are executed. The function is invoked using the dot(‘.’) notation. The function works till it encounters the ‘yied’ statement and then returns the value that it has at that time.

Please note that the older versions of python used next() function to retrieve a value but in Pyhton 3 next() is replaced by __next__().

Now to get a better understanding of generators, try the following code:

```def student_name():
student = ["Alex","Mike","Mary","Martin","Erin"]
for item in student:
yield item

stu = student_name()
print(stu.__next__())
```

When you run the above code the output is “Alex”. The function executes till it encounters ‘yield’ statement. The function resumes operation only when we call the __next__() method. So, if you now type print(stu.__next__()) in the Python shell the next value will be displayed.

# Class Inheritance in Python

While coding an application a developer will create several classes. Sometimes, he may feel the need to create a class similar to an existing one but with some additional features. In such a case instead of creating a class from scratch he can create a class that inherits the existing class and then add the new functionality to it.

Let’s try to explain this with a simple example. Suppose we have a class called human which has some features. Then we try to create two classes – boy and girl. Now, both boy and girl are humans but different from each other. So, they both can inherit the common properties of human class and then define their own features that separate them from each other.

```class human:
def __init__(self):
print ("Human class is the parent class")
def human_method(self):
print ("I am a parent method being called from the child object of class girl")

class girl(human):
def __init__(self):
print ("girl class is inherited from human")
def girl_method(self):
print ("I am a child method being called from the child object of class girl")

g  = girl()
g.girl_method()
g.human_method()
```

In the above code have a look at how the girl class inherits the human class – “class girl(human):
” . You should also notice that an object of the girl class can call the method of the human class.

Similarly, a class can have more than one parent

```class woman:
class_definition

class man:
class_definition

class baby(woman,man):
class_definition
```

## issubclass() function

issubclass() is a function that can be used to find whether a class is a subclass of another given class or not. If yes, it returns true else it will return false.

```class woman:
pass

class man:
pass

class baby(woman,man):
pass

if issubclass(baby,man):
print("baby is a subclass of man")
if issubclass(baby,woman):
print("baby is a subclass of woman")

```

## Overriding methods

Child class can override any method of the parent class. If you have a method defined in a parent class and you want it to work differently in any of its child class then you can define the new functionality for the same method in the child class. Have a look at the code below how the method hi_whomsoever() is defined differently in the parent and the child class.

```class human:
def __init__(self):
print ("Human class is the parent class")
def human_method(self):
print ("I am a parent method being called from the child object of class girl")
def hi_whomsoever(self):
print("Hi human")

class girl(human):
def __init__(self):
print ("girl class is inherited from human")
def girl_method(self):
print ("I am a child method being called from the child object of class girl")
def hi_whomsoever(self):
print("Hi girl")

h  = human()
h.hi_whomsoever()

g  = girl()
g.hi_whomsoever()
```

## Classes Objects in Python

All modern day programming languages are based on the concept of OOP – object oriented programming and support classes and objects. Python too is an object oriented language right from the very beginning. Let’s have a look at the basics of object oriented programming. An object is creating or encapsulating your customized group of variables that has its own set of attributes, functions and properties. A call defines all the characteristics and properties of an object. The object can access methods with the help of dot notation. A variable that holds data values associated with a class and its objects is known as data member. Download the powerpoint

Following are some more terms that you would need to know  about Python classes/objects:
1. A variable that is defined inside a method of a class and can be accessed only by the instance of that class are called instance variable.
2. If you derive a class from another class such that it has all the characteristics of the parent class is called Inheritance.
3. An object of a class is also known as an instance.
4. When you create an instance of a class it is called instantiation.
5. A function that is part of class definition is known as a method

The syntax for defining a class is as follows:

```class Class_Name:
code_functions_variables
```

The syntax for creating an object is:

```object_name = Class_Name()
```

Now let’s try to understand how a class works with the help of a simple example:

```class Hello_World:
def hello_world(self,x):
self.x = x
print(x)

obj_hellow = Hello_World()
obj_hellow.hello_world("Hello World")
```

## Python self keyword

In Python, in every function, the first argument refers to its current instance and this argument is the self. Notice this in the code above. When we make a call to a function we don’t pass any value for self.

If there is a need to customize an object to an initial state when it is created then you will have to define an __init__() function in the class. Look at the following piece of code:

```class Hello_World:
def __init__ (self, x):
self.x = x

obj_hellow = Hello_World("Hello World")
print(obj_hellow.x)
```

So, here you can see when you create the object, a string value “Hello World” is passed as an argument. The __init__() function assigns this value to the attribute x. So, to access this value you can access the variable with a dot notation obj_hellow.x.

## Functions in Python

Whenever there is a need to perform certain actions under certain conditions it is better to define that piece of code in such a way that it can be reused as and when there is a need rather than repeating the same code again and again. This can be achieved with the help of a function. In real world you will not find any application being created without functions.

Python has a set of in built functions which are very helpful. We have come across many such in-built functions while working with strings.

## How to define a function

To define a function Python has defined a keyword ‘def’ which is followed by the name of the function and parantheses -> () followed by a colon -> ‘:’, as you will soon see in the function syntax. If the function requires any arguments then it is passed through these parentheses or else they are left blank. If the job of a function is to return a value at the end then the last statement will be a ‘return’ statement. Keeping this information in mind have a look at the following syntax:

```def my_function(args):
perform_these_steps
return value
```

To get a better understanding have a look at the following piece of code

```def hello(name):
print("Hello " + name + "!!")

val1 = input("What's your name? : ")
hello(val1)
```

1. def hello(name): – defines the function. ‘def ’ is the keyword to define the function. ‘hello’ is the name of the function. ‘name’ is the argument that is passed to the function.
2. When you execute the code you will be prompted to enter a name. The function input(“What’s your name? : “) will prompt the user. Input() method is used when you want the input from the user. Whatever value you enter will be assigned to the variable val1.
3. When you say hello(val1), the function hello will be invoked. The value of val1 will be assigned to the argument ‘name’ in the function definition.
4. print(“Hello ” + name + “!!”) in this statement the function will generate a Hello string. Run the code and see for yourself.

## Passing default values as arguments

Can you guess the outcome of the following code? And why?

```def hello(name = "World"):
print("Hello " +  name + "!!")

val1 = input("What's your name? : ")
hello()
```

1. Look at the function definition – def hello(name = “World”):. Here, the argument name= “World” signifies that if no value is passed to the function then by default it will take the value “World” as argument.
2. So, at the end of the code when a call is made to the function as hello() then, irrespective of what value you have entered when prompted, the function will print “Hello World !!” as the value that you provided was not passed on to the function as argument. Therefore, the default value was used.

So, can you now tell why the following code gives an error when executed?

```def hello(name):
print("Hello " + name + "!!")

val1 = input("What's your name? : ")
hello()
```

1. Look at the function definition – def hello(name). Here, the argument ‘name’ has no default value.
2. So, it is mandatory to pass an argument to the function.
3. If you make a call to the function with “hello()”, then an error will be generated.

## Function returning a value

Have a look at the following code. It shows how a value is returned from a function. We have defined a function that takes to numbers, adds them and returns the value.

```def addition(var1=0, var2=0):
s = int(var1) + int(var2)
return s

val1 = input("Enter first number : ")
val2 = input("Enter first number : ")
print("sum of " + str(val1) + " and " + str(val2) + " = " + str(addition(val1,val2)) )
```
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .