Python
Python
Unit – I
Introduction to Python
Python History
• Python laid its foundation in the late 1980s.
• The implementation of Python was started in the December 1989 by Guido
Van Rossum at CWI in Netherland.
• In February 1991, van Rossum published the code (labeled version 0.9.0) to
alt.sources.
• In 1994, Python 1.0 was released with new features like: lambda, map, filter,
and reduce.
• Python 2.0 added new features like: list comprehensions, garbage collection
system.
• On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify fundamental flaw of the language.
• ABC programming language is said to be the predecessor of Python language
which was capable of Exception Handling and interfacing with Amoeba
Operating System.
• Python is influenced by following programming languages:
– ABC language.
– Modula-3
Python Features
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and
objects come into existence.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the
code and thus it can be used further in our python code.
8) Large Standard Library
Python has a large and broad library and provides rich set of module and
functions for rapid application development.
9) GUI Programming Support
Graphical user interfaces can be developed using Python.
10) Integrated
It can be easily integrated with languages like C, C++, JAVA etc.
In this section of the tutorial, we will discuss the installation of python on various
operating systems.
Installation on Windows
Visit the link https://www.python.org/downloads/ to download the latest release of
Python. In this process, we will install Python 3.6.7 on our Windows operating
system.
Double-click the executable file which is downloaded; the following window will
open. Select Customize installation and proceed.
2
Programming With Python-22616
The following window shows all the optional features. All the features need to be
installed and are checked by default; we need to click next to continue.
The following window shows a list of advanced options. Check all the options
which you want to install and click next. Here, we must notice that the first check-
box (install for all users) must be checked.
3
Programming With Python-22616
Now, try to run python on the command prompt. Type the command python in
case of python2 or python3 in case of python3. It will show an error as given in
the below image. It is because we haven't set the path.
4
Programming With Python-22616
To set the path of python, we need to the right click on "my computer" and go to
Properties → Advanced → Environment Variables.
5
Programming With Python-22616
Type PATH as the variable name and set the path to the installation directory of
the python shown in the below image.
Now, the path is set, we are ready to run python on our local system. Restart CMD,
and type python again. It will open the python interpreter shell where we can
execute the python statements.
6
Programming With Python-22616
In this Section, we will discuss the basic syntax of python by using which, we will
run a simple program to print hello world on the console.
7
Programming With Python-22616
Let's run a python statement to print the traditional hello world on the
console. Python3 provides print() function to print some message on the
console. We can pass the message as a string into this function. Consider the
following image.
Here, we get the message "Hello World !" printed on the console.
8
Programming With Python-22616
We need to write our code into a file which can be executed later. For this
purpose, open an editor like notepad, create a file named first.py (python
used .py extension) and write the following code in it.
1. Print ("hello world") #here, we have used print() function to print the message o
n the console.
To run this file named as first.py, we need to run the following command on the
terminal.
$ python3 first.py
Hence, we get our output as the message Hello World ! is printed on the console.
9
Programming With Python-22616
10
Programming With Python-22616
Python Indentation
Indentation in Python refers to the (spaces and tabs) that are used at
the beginning of a statement.
Most of the programming languages like C, C++, Java use braces { }
to define a block of code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation
and ends with the first unindented line. The amount of indentation is
up to you, but it must be consistent throughout that block.
The enforcement of indentation in Python makes the code look neat and
clean. This results into Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to
always indent. It makes the code more readable. For example:
11
Programming With Python-22616
Python Variables
number = 10
Here, we have created a named number. We have assigned value 10 to the
variable.
apple.com
12
Programming With Python-22616
apple.com
programiz.com
If we want to assign the same value to multiple variables at once, we can do this as
The second program assigns the same string to all the three variables x, y and z.
Python Comments
13
Programming With Python-22616
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of the
line:
Example
print("Hello, World!") #This is a comment
Hello, World!
Comments does not have to be text to explain the code, it can also be used to
prevent Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")
Cheers, Mate!
Multi Line Comments
Python does not really have a syntax for multi line comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
14
Programming With Python-22616
Hello, World!
Since Python will ignore string literals that are not assigned to a variable,
you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Hello, World!
Python Numbers
Integers, floating point numbers and complex numbers falls under Python
numbers category. They are defined as int, float and complex class in
Python.
We can use the type() function to know which class a variable or a value
belongs to and the isinstance() function to check if an object belongs to a
particular class.
Example -
a=5
15
Programming With Python-22616
16
Programming With Python-22616
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
Python List
List is an ordered sequence of items. It is one of the most used datatype in
Python and is very flexible. All the items in a list do not need to be of the
same type.
a = [5,10,15,20,25,30,35,40] Output-
# a[2] = 15
print("a[2] = ", a[2]) a[2] = 15
17
Programming With Python-22616
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
Python Tuples
Tuple is an ordered sequence of items same as list. The only difference is
that tuples are immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it
cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
t = (5,'program', 1+3j)
# Generates error
# Tuples are immutable Traceback (most recent call last):
t[0] = 10 File "<stdin>", line 11, in <module>
t[0] = 10
TypeError: 'tuple' object does not
support item assignment
18
Programming With Python-22616
Python Dictionary
Dictionary is an unordered collection of key-value pairs.
In Python, dictionaries are defined within braces {} with each item being a
pair in the form key:value. Key and value can be of any type.
1. >>> d = {1:'value','key':2}
2. >>> type(d)
3. <class 'dict'>
We use key to retrieve the respective value. But not the other way
around.
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
19
Programming With Python-22616
Unit-II
Python Operators and Control Flow statements
Python Operators
Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is called
the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands
and 5 is the output of the operation.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
Arithmetic operators
20
Programming With Python-22616
21
Programming With Python-22616
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
----------------------------------------------------------------------------------------------------
Comparison operators
Comparison operators are used to compare values. It either
returns True or False according to the condition.
22
Programming With Python-22616
---------------------------------------------------------------------------------------------------------------------
Logical operators
Logical operators are the and, or, not operators.
23
Programming With Python-22616
Bitwise operators
24
Programming With Python-22616
Assignment operators
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
25
Programming With Python-22616
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Python language offers some special type of operators like the identity
operator or the membership operator. They are described below with
examples.
Identity operators
• is and is not are the identity operators in Python. They are used to check
if two values (or variables) are located on the same part of the memory.
Two variables that are equal does not imply that they are identical.
26
Programming With Python-22616
10.
11.# Output: True
12.print(x2 is y2)
13.
14.# Output: False
15.print(x3 is y3)
Here, we see that x1 and y1 are integers of same values, so they are equal as well
as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. It is because interpreter
locates them separately in memory although they are equal.
----------------------------------------------------------------------------------------------------
Membership operators
in and not in are the membership operators in Python. They are used to test
whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
27
Programming With Python-22616
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similary, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
--------------------------------------------------------------------------------------------
• For example:
1.
2. >>> 5 - 7
3. -2
• Here 5 - 7 is an expression. There can be more than one operator in an
expression.
28
Programming With Python-22616
(10 - 4) * 2
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
29
Programming With Python-22616
or Logical OR
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
Control Flow-
1) Python IF Statement
Syntax
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s)
inside the if statement is executed. If boolean expression evaluates to
FALSE, then the first set of code after the end of the if statement(s) is
executed.
Example:- $python main.py
var1 = 100 1 - Got a true expression value
if var1:
100
print "1 - Got a true expression value"
print var1 Good bye!
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
30
Programming With Python-22616
Output:
Example 2
1. num = int(input("enter the number?")) enter the number?10
2. if num%2 == 0: Number is even
3. print("Number is even")
if condition:
#block of statements
else:
#another block of statements (else-block)
31
Programming With Python-22616
Output:
Example 1 : Program to check whether
a person is eligible to vote or not. Enter your age? 90
1. age = int (input("Enter your age? ")) You are eligible to vote !!
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. print("Sorry! you have to wait !!");
Output:
Example 2: Program to check whether
a number is even or not. enter the number?10
1. num = int(input("enter the number?")) Number is even
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
32
Programming With Python-22616
else:
# block of statements
Output:
Example 1
1. number = int(input("Enter the number?")) Enter the number?15
2. if number==10: number is not equal to 10,
3. print("number is equals to 10") 50 or 100
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Example 2
1. marks = int(input("Enter the marks? "))
2. if marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. elif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. elif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. elif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
else:
print("Sorry you are fail ?")
33
Programming With Python-22616
Output 1
Python Nested if Example
# In this program, we input a number Enter a number: 5
# check if the number is positive or Positive number
# negative or zero and display
# an appropriate message Output 2
# This time we use nested if Enter a number: -1
Negative number
num = float(input("Enter a number: "))
if num >= 0: Output 3
if num == 0:
print("Zero") Enter a number: 0
else: Zero
print("Positive number")
else:
print("Negative number")
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
Looping in python:-
34
Programming With Python-22616
Example 1 Output:
1. i=1; 1
2. while i<=10: 2
3. print(i); 3
4. i=i+1; 4
5
6
7
8
9
10
Example 2 Output:
1. i=1 Enter the number?10
2. number=0
3. b=9 10 X 1 = 10
4. number = int(input("Enter the number?"))
5. while i<=10: 10 X 2 = 20
6. print("%d X %d = %d \n"%(number,i,number*i));
10 X 3 = 30
7. i = i+1;
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
35
Programming With Python-22616
i=1
for i in range(0,10):
36
Programming With Python-22616
Output:
Python for loop example : printing the table of
the given number Enter a number:10
1. i=1; 10 X 1 = 10
2. num = int(input("Enter a number:")); 10 X 2 = 20
3. for i in range(1,11): 10 X 3 = 30
4. print("%d X %d = %d"%(num,i,num*i)); 10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
----------------------------------------------------------------------------------------------------
37
Programming With Python-22616
The continue statement in python is used to bring the program control to the
beginning of the loop. The continue statement skips the remaining lines of
code inside the loop and start with the next iteration. It is mainly used for a
particular condition inside the loop so that we can skip some specific code
for a particular condition.
The syntax of Python continue statement is given below.
#loop statements
continue;
#the code to be skipped
Output:
Example 1
1. i = 0; infinite loop
2. while i!=10:
3. print("%d"%i);
4. continue;
5. i=i+1;
Output:
Example 2
1. i=1; #initializing a local variable 1
2. #starting a loop from 1 to 10 2
3. for i in range(1,11): 3
4. if i==5: 4
5. continue; 6
6. print("%d"%i); 7
8
9
10
38
Programming With Python-22616
#loop statements
break;
Output:
Example 1
1. list =[1,2,3,4] item matched
2. count = 1; found at 2 location
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");
Output:
Example 2
1. str = "python" p
2. for i in str: y
3. if i == 'o': t
4. break h
5. print(i);
39
Programming With Python-22616
Output:
Example2
1. for i in [1,2,3,4,5]: 2. >>>
2. if i==3: 3. 1 2 Pass when value is 3
3. pass 4. 345
4. print "Pass when value is",i 5. >>>
5. print i,
1.
----------------------------------------------------------------------------------------------------
40
Programming With Python-22616
Unit –III
Data Structure in Python
Python List:-
Python offers a range of compound data types often referred to as sequences.
List is one of the most frequently used and very versatile data types used in
Python.
# list of integers
my_list = [1, 2, 3]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
There are various ways in which we can access the elements of a list.
List Index
We can use the index operator [] to access an item in a list. Index starts from
0. So, a list having 5 elements will have index from 0 to 4.
41
Programming With Python-22616
Trying to access an element other that this will raise an IndexError. The
index must be an integer. We can't use float or other types, this will result
into TypeError.
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested List
n_list = ["Happy", [2,0,1,5]]
# Nested indexing
# Output: a
print(n_list[0][1])
# Output: 5
print(n_list[1][3])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.
my_list = ['p','r','o','b','e']
# Output: e
42
Programming With Python-22616
print(my_list[-1])
# Output: p
print(my_list[-5])
We can access a range of items in a list by using the slicing operator (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need two indices that will
slice that portion from the list.
43
Programming With Python-22616
# mistake values
odd = [2, 4, 6, 8]
# Output: [1, 4, 6, 8]
print(odd)
# Output: [1, 3, 5, 7]
print(odd)
We can add one item to a list using append() method or add several items
using extend() method.
odd = [1, 3, 5]
odd.append(7)
# Output: [1, 3, 5, 7]
print(odd)
44
Programming With Python-22616
We can also use + operator to combine two lists. This is also called
concatenation.
The * operator repeats a list for the given number of times.
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])
# Output: [1, 3, 9]
print(odd)
odd[2:2] = [5, 7]
# Output: [1, 3, 5, 7, 9]
print(odd)
How to delete or remove elements from a list?
We can delete one or more items from a list using the keyword del. It can
even delete the list entirely.
my_list = ['p','r','o','b','l','e','m']
45
Programming With Python-22616
print(my_list)
We can use remove() method to remove the given item or pop() method to
remove an item at the given index.
The pop() method removes and returns the last item if index is not provided.
This helps us implement lists as stacks (first in, last out data structure).
We can also use the clear() method to empty a list.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: 'o'
print(my_list.pop(1))
# Output: 'm'
print(my_list.pop())
46
Programming With Python-22616
my_list.clear()
# Output: []
print(my_list)
Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.
47
Programming With Python-22616
Parameters
list1 − This is the first list to be compared.
list2 − This is the second list to be compared.
Return Value
If elements are of the same type, perform the compare and return the result. If
elements are different types, check to see if they are numbers.
48
Programming With Python-22616
len(list)
Parameters
list − This is a list for which number of elements to be counted.
Return Value
This method returns the number of elements in the list.
Example
The following example shows the usage of len() method.
list1, list2 = [123, 'xyz', 'pqrs'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
When we run above program, it produces following result −
First list length : 3
Second list length : 2
50
Programming With Python-22616
51
Programming With Python-22616
Python Tuple
A tuple in Python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas, in a list,
elements can be changed.
Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.
A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple) # Output: ()
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
52
Programming With Python-22616
a, b, c = my_tuple
print(a) #3
print(b) # 4.6
print(c) # dog
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
----------------------------------------------------------------------------------------------------
Access Tuple Elements
There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple where the index
starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access
an element outside of tuple (for example, 6, 7,...) will raise an IndexError.
The index must be an integer; so we cannot use float or other types. This
will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the
example below.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
3. Slicing
We can access a range of items in a tuple by using the slicing operator -
colon ":".
my_tuple = ('p','r','o','g','r','a','m','i','z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
----------------------------------------------------------------------------------------------------
Changing a Tuple
55
Programming With Python-22616
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
----------------------------------------------------------------------------------------------------
Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also
means we cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')
SN Function Description
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater tha
tuple2) false.
56
Programming With Python-22616
List VS Tuple
SN List Tuple
1 The literal syntax of list is The literal syntax of the tuple is
shown by the []. shown by the ().
2 The List is mutable. The tuple is immutable.
3 The List has the variable The tuple has the fixed length.
length.
4 The list provides more The tuple provides less functionality
functionality than tuple. than the list.
5 The list Is used in the The tuple is used in the cases where
scenario in which we need to we need to store the read-only
store the simple collections collections i.e., the value of the items
with no constraints where the can not be changed. It can be used as
value of the items can be the key inside the dictionary.
changed.
----------------------------------------------------------------------------------------------------
Python Sets
57
Programming With Python-22616
58
Programming With Python-22616
We can add single element using the add() method and multiple elements
using the update() method. The update() method can take tuples,
lists, strings or other sets as its argument. In all cases, duplicates are avoided.
1. # initialize my_set
2. my_set = {1,3}
3. print(my_set)
4.
5. # if you uncomment line 9,
6. # you will get an error
7. # TypeError: 'set' object does not support indexing
8.
9. #my_set[0]
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
59
Programming With Python-22616
1. # initialize my_set
2. my_set = {1, 3, 4, 5, 6}
3. print(my_set)
4.
5. # discard an element
6. # Output: {1, 3, 5, 6}
7. my_set.discard(4)
8. print(my_set)
9.
10.# remove an element
11.# Output: {1, 3, 5}
12.my_set.remove(6)
13.print(my_set)
14.
15.# discard an element
16.# not present in my_set
17.# Output: {1, 3, 5}
18.my_set.discard(2)
19.print(my_set)
20.
21.# remove an element
22.# not present in my_set
23.# If you uncomment line 27,
24.# you will get an error.
25.# Output: KeyError: 2
26.
27.#my_set.remove(2)
----------------------------------------------------------------------------------------------------
60
Programming With Python-22616
Set Union
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
61
Programming With Python-22616
Set Intersection-
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
62
Programming With Python-22616
Set Difference-
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
# use - operator on B
>>> B - A
{8, 6, 7}
63
Programming With Python-22616
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
Try the following examples on Python shell.
64
Programming With Python-22616
Function Description
Return True if all elements of the set are true (or if the set
all() is empty).
Return True if any element of the set is true. If the set is
any() empty, return False.
Return an enumerate object. It contains the index and
enumerate() value of all the items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
Return a new sorted list from elements in the set(does not
sorted() sort the set itself).
sum() Retrun the sum of all elements in the set.
-------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------
Python Dictionary
65
Programming With Python-22616
The difference while using get() is that it returns None instead of KeyError,
if the key is not found.
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
Jack
26
Dictionary are mutable(Can Change). We can add new items or change the
value of existing items using assignment operator.
66
Programming With Python-22616
If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.
my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
# add item
my_dict['address'] = 'Downtown'
The method, popitem() can be used to remove and return an arbitrary item
(key, value) form the dictionary. All the items can be removed at once using
the clear() method.
We can also use the del keyword to remove individual items or the entire
dictionary itself.
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
67
Programming With Python-22616
# Output: {2: 4, 3: 9}
print(squares)
# Output: {}
print(squares)
# Throws Error
# print(squares)
16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
68
Programming With Python-22616
Methods that are available with dictionary are tabulated below. Some of
them have already been used in the above examples.
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and
value equal to v (defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d
(defaults to None).
items() Return a new view of the dictionary's items (key,
value).
keys() Return a new view of the dictionary's keys.
pop(key[,d]) Remove the item with key and return its value or d if
key is not found. If d is not provided and key is not
found, raises KeyError.
popitem() Remove and return an arbitary item (key, value).
Raises KeyError if the dictionary is empty.
setdefault(key[,d]) If key is in the dictionary, return its value. If not,
insert key with a value of d and return d (defaults to
None).
update([other]) Update the dictionary with the key/value pairs from
other, overwriting existing keys.
values() Return a new view of the dictionary's values
Built-in functions like all(), any(), len(), cmp(), sorted() etc. are commonly
used with dictionary to perform different tasks.
Function Description
Return True if all keys of the dictionary are true (or if
the dictionary is empty).
all()
69
Programming With Python-22616
Here are some examples that uses built-in functions to work with dictionary.
# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
print(sorted(squares))
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
70
Programming With Python-22616
CHAPTER-IV
Python Functions, Modules, and Packages
Python Functions-
def function_name(parameters):
"""docstring"""
statement(s)
71
Programming With Python-22616
def greet(name):
"""This function greets to the person passed in as parameter"""
print("Hello, " + name + ". Good morning!")
How to call a function in python?
Once we have defined a function, we can call it from another function,
program or even the Python prompt. To call a function we simply type the
function name with appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
Scope and Lifetime of variables
Scope of a variable is the portion of a program where the variable is
recognized. Parameters and variables defined inside a function is not visible
from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable exits in the
memory. The lifetime of variables inside a function is as long as the function
executes.
They are destroyed once we return from the function. Hence, a function does
not remember the value of a variable from its previous calls.
Here is an example to illustrate the scope of a variable inside a function.
72
Programming With Python-22616
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output
Here, we can see that the value of x is 20 initially. Even though the
function my_func() changed the value of x to 10, it did not effect the value
outside the function.
This is because the variable x inside the function is different (local to the
function) from the one outside. Although they have same names, they are
two different variables with different scope.
On the other hand, variables outside of the function are visible from inside.
They have a global scope.
We can read these values from inside the function but cannot change (write)
them. In order to modify the value of variables outside the function, they
must be declared as global variables using the keyword global.
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
The return statement
The return statement is used to exit a function and go back to the place from
where it was called.
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return the None
object.
For example:
73
Programming With Python-22616
1. >>> print(greet("May"))
2. Hello, May. Good morning!
3. None
Here, None is the returned value.
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
Types of Functions
The Python interpreter has a number of functions that are always available
for use. These functions are called built-in functions. For example, print() function
prints the given object to the standard output device (screen) or to the text stream
file.
In Python 3.6 (latest version), there are 68 built-in functions. They are
listed below alphabetically along with brief description.
74
Programming With Python-22616
Method Description
75
Programming With Python-22616
Method Description
76
Programming With Python-22616
Method Description
77
Programming With Python-22616
Method Description
78
Programming With Python-22616
Functions that readily come with Python are called built-in functions. If we
use functions written by others in the form of library, it can be termed as
library functions.
All the other functions that we write on our own fall under user-defined
functions. So, our user-defined function could be a library function to
someone else.
# Program to illustrate
# the use of user-defined functions
def add_numbers(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
Here, we have defined the function my_addition() which adds two numbers
and returns the result.
79
Programming With Python-22616
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
Python Functions
Creating a Function
Example
def my_function():
print("Hello from a function")
my_function()
Output-
Hello from a function
Parameters
Information can be passed to functions as parameter.
80
Programming With Python-22616
Parameters are specified after the function name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Output-
Emil Refsnes
Tobias Refsnes
Linus Refsnes
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
81
Programming With Python-22616
Output-
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Passing a List as a Parameter
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Output-
apple
banana
cherry
82