0% found this document useful (0 votes)
9 views

Python

The document provides an introduction to Python, covering its history, features, installation process, and basic programming concepts. It explains Python's characteristics such as being easy to learn, interpreted, and object-oriented, along with how to set up the environment and run simple scripts. Additionally, it discusses identifiers, keywords, indentation, variables, comments, data types, and basic data structures like lists and tuples.

Uploaded by

nadafaaliya1
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)
9 views

Python

The document provides an introduction to Python, covering its history, features, installation process, and basic programming concepts. It explains Python's characteristics such as being easy to learn, interpreted, and object-oriented, along with how to set up the environment and run simple scripts. Additionally, it discusses identifiers, keywords, indentation, variables, comments, data types, and basic data structures like lists and tuples.

Uploaded by

nadafaaliya1
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/ 82

Programming With Python-22616

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

Python provides lots of features that are listed below.


1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level
programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable
and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by
line at a time. This makes debugging easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux,
Unix and Macintosh etc. So, we can say that Python is a portable language.
5) Free and Open Source
Python language is freely available at offical web address.The source-code is
also available. Therefore it is open source.
1
Programming With Python-22616

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.

 How to Install Python (Environment Set-up)

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, we are ready to install python-3.6.7. Let's install it

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

Add the new path variable in the user variable section.

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

 Running Simple python script to display message Hello World!


 First Python Program

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.

Python provides us the two ways to run a program:

o Using Interactive interpreter prompt


o Using a script file

Let's discuss each one of them in detail.

7
Programming With Python-22616

Interactive interpreter prompt

 Python provides us the feature to execute the python statement one by


one at the interactive prompt. It is preferable in the case where we are
concerned about the output of each line of our python program.
 To open the interactive mode, open the terminal (or command prompt) and
type python (python3 in case if you have python2 and python3 both installed
on your system).
 It will open the following prompt where we can execute the python
statement and check their impact on the console.

 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.

Using a script file

 Interpreter prompt is good to run the individual statements of the code.


However, we cannot write the code every-time on the terminal.

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.

 Python Building Blocks-


 Identifier,Keywords,Indention,Variable,comments
 Python Identifiers

 An identifier is a name given to entities like class, functions, variables,


etc. It helps to differentiate one entity from another.

Rules for writing identifiers

1. Identifiers can be a combination of letters in lowercase (a to z) or


uppercase (A to Z) or digits (0 to 9) or an underscore _. Names
like myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is
perfectly fine.
3. Keywords cannot be used as identifiers.
1.
2. >>> global = 1
3. File "<interactive input>", line 1
4. global = 1
5. ^

9
Programming With Python-22616

6. SyntaxError: invalid syntax


b. We cannot use special symbols like !, @, #, $, % etc. in our
identifier.
1.
2. >>> a@ = 0
3. File "<interactive input>", line 1
4. a@ = 0
5. ^
6. SyntaxError: invalid syntax
c. Identifier can be of any length.
 Python Keywords
 Keywords are the reserved words in Python.
 We cannot use a keyword as a variable name, function name or
any other identifier. They are used to define the syntax and structure
of the Python language.
 In Python, keywords are case sensitive.
 There are 33 keywords in Python 3.7. This number can vary slightly
in the course of time.
 All the keywords except True, False and None are in lowercase and
they must be written as it is. The list of all the keywords is given
below.


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.

 Generally four whitespaces are used for indentation and is preferred


over tabs. Here is an example.

 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

 A variable is a named location used to store data in the memory. It is helpful


to think of variables as a container that holds data which can be changed
later throughout programming. For example,

number = 10
Here, we have created a named number. We have assigned value 10 to the
variable.

 Assigning a value to a Variable in Python


As you can see from the above example, you can use the assignment
operator = to assign a value to a variable.

Example 1: Declaring and assigning a value to a variable

When you run the program, the output will be:

apple.com

Note : Python is a type inferred language; it can automatically know apple.com is a


string and declare website as a string.

12
Programming With Python-22616

When you run the program, the output will be:

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

• Comments can be used to explain Python code.

13
Programming With Python-22616

• Comments can be used to make the code more readable.

• Comments can be used to prevent execution when testing code.

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.

To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")

14
Programming With Python-22616

Hello, World!

 Or, not quite as intended, you can use a multiline string.

 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 Data Types

 Every value in Python has a datatype. Since everything is an object in


Python programming, data types are actually classes and variables are
instance (object) of these classes.
 There are various data types in Python. Some of the important types are
listed below.

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

print(a, "is of type", type(a))


a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output-
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
 Integers can be of any length, it is only limited by the memory available.
 A floating point number is accurate up to 15 decimal places. Integer and
floating points are separated by decimal points. 1 is integer, 1.0 is floating
point number.
 Complex numbers are written in the form, x + yj, where x is the real part
and y is the imaginary part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
 Notice that the float variable b got truncated.\
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
 Python Strings
 The string can be defined as the sequence of characters represented in the
quotation marks. In python, we can use single, double, or triple quotes to
define a string.
 String handling in python is a straightforward task since there are various
inbuilt functions and operators provided.
 In the case of string handling, the operator + is used to concatenate two
strings as the operation "hello"+" python" returns "hello python".

16
Programming With Python-22616

 The operator * is known as repetition operator as the operation "Python " *2


returns "Python Python ".
 The following example illustrates the string handling in python.
str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

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.

 Declaring a list is pretty straight forward. Items separated by commas are


enclosed within brackets [ ].

>>> a = [1, 2.2, 'python']

 We can use the slicing operator [ ] to extract an item or a range of items


from a list. Index starts form 0 in Python.

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

# a[0:3] = [5, 10, 15]


print("a[0:3] = ", a[0:3]) a[0:3] = [5, 10, 15]

# a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:]) a[5:] = [30, 35, 40]

----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
 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)


 We can use the slicing operator [] to extract items but we cannot change its
value.

t = (5,'program', 1+3j)

# t[1] = 'program' t[1] = program


print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j)) t[0:3] = (5, 'program', (1+3j))


print("t[0:3] = ", t[0:3])

# 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.

 It is generally used when we have a huge amount of data. Dictionaries are


optimized for retrieving data. We must know the key to retrieve the value.

 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.

d = {1:'value','key':2} <class 'dict'>


print(type(d)) d[1] = value
d['key'] = 2
print("d[1] = ", d[1]);
Traceback (most recent call last):
print("d['key'] = ", File "<stdin>", line 9, in <module>
d['key']); print("d[2] = ", d[2]);
KeyError: 2
# Generates error
print("d[2] = ", d[2]);

----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------

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.

 Python provides a variety of operators described as follows.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------

 Arithmetic operators

 Arithmetic operators are used to perform mathematical operations like


addition, subtraction, multiplication etc.

Operator Meaning Example


x + y
+ Add two operands or unary plus +2
Subtract right operand from the left or unary x - y
- minus -2
* Multiply two operands x*y

20
Programming With Python-22616

Divide left operand by the right one (always


/ results into float) x/y
Modulus - remainder of the division of left x % y (remainder
% operand by the right of x/y)
Floor division - division that results into
whole number adjusted to the left in the
// number line x // y
Exponent - left operand raised to the power x**y (x to the
** of right power y)

21
Programming With Python-22616

Example #1: Arithmetic operators in Python


x = 15
y=4

# 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)

When you run the program, the output will be:

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

Operator Meaning Example


Greater that - True if left operand is
> greater than the right x>y
Less that - True if left operand is less
< than the right x<y
== Equal to - True if both operands are equal x == y
Not equal to - True if operands are not
!= equal x != y
Greater than or equal to - True if left
operand is greater than or equal to the
>= right x >= y
Example #2: Comparison operators in Python
1. x = 10
2. y = 12
3.
4. # Output: x > y is False
5. print('x > y is',x>y)
6.
7. # Output: x < y is True
8. print('x < y is',x<y)
9.
10.# Output: x == y is False
11.print('x == y is',x==y)
12.
13.# Output: x != y is True
14.print('x != y is',x!=y)
15.
16.# Output: x >= y is False
17.print('x >= y is',x>=y)
18.
19.# Output: x <= y is True
20.print('x <= y is',x<=y)

---------------------------------------------------------------------------------------------------------------------

 Logical operators
 Logical operators are the and, or, not operators.

23
Programming With Python-22616

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

Example #3: Logical Operators in Python


1. x = True
2. y = False
3.
4. # Output: x and y is False
5. print('x and y is',x and y)
6.
7. # Output: x or y is True
8. print('x or y is',x or y)
9.
10.# Output: not x is False
11.print('not x is',not x)

 Bitwise operators

 Bitwise operators act on operands as if they were string of binary digits. It


operates bit by bit, hence the name.

 For example, 2 is 10 in binary and 7 is 111.


In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in
binary)

Operator Meaning Example

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

24
Programming With Python-22616

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)


--------------------------------------------------------------------------------------------

 Assignment operators

 Assignment operators are used in Python to assign values to


variables.

 a = 5 is a simple assignment operator that assigns the value 5 on the


right to the variable a on the left.
 There are various compound operators in Python like a += 5 that adds to
the variable and later assigns the same. It is equivalent to a = a + 5.

Operator Example Equivatent to

= 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

&= x &= 5 x=x&5

25
Programming With Python-22616

|= x |= 5 x=x|5

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5


--------------------------------------------------------------------------------------------
 Special operators

 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.

Operator Meaning Example

True if the operands are identical (refer to the same


is object) x is True

True if the operands are not identical (do not refer to


is not the same object) x is not True

Example #4: Identity operators in Python


1. x1 = 5
2. y1 = 5
3. x2 = 'Hello'
4. y2 = 'Hello'
5. x3 = [1,2,3]
6. y3 = [1,2,3]
7.
8. # Output: False
9. print(x1 is not y1)

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.

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x

Example #5: Membership operators in Python


1. x = 'Hello world'
2. y = {1:'a',2:'b'}
3.
4. # Output: True
5. print('H' in x)
6.
7. # Output: True
8. print('hello' not in x)
9.

27
Programming With Python-22616

10.# Output: True


11.print(1 in y)
12.
13.# Output: False
14.print('a' in y)

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.

--------------------------------------------------------------------------------------------

 Precedence of Python Operators


• The combination of values, variables, operators and function calls is
termed as an expression. Python interpreter can evaluate a valid
expression.

• For example:

1.
2. >>> 5 - 7
3. -2
• Here 5 - 7 is an expression. There can be more than one operator in an
expression.

• To evaluate these type of expressions there is a rule of precedence in Python.


It guides the order in which operation are carried out.

• For example, multiplication has higher precedence than subtraction.

# Multiplication has higher


precedence Out[1]: 2
# than subtraction
# Output: 2
10 - 4 * 2

28
Programming With Python-22616

• But we can change this order using parentheses () as it has higher


precedence.

# Parentheses () has higher precendence


Out[1]: 12
# Output: 12

(10 - 4) * 2

• The operator precedence in Python are listed in the following table. It is in


descending order; upper group has higher precedence than the lower ones.

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

Multiplication, Division, Floor division,


*, /, //, % Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is


not, in, not in Comparisons, Identity, Membership operators

not Logical NOT

29
Programming With Python-22616

and Logical AND

or Logical OR

---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------

Control Flow-

1) Python IF Statement

 It is similar to that of other languages. The if statement contains a logical


expression using which data is compared and a decision is made based on
the result of the comparison.

 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")

Example 3 : Program to print the


largest of the three numbers. Output:
1. a = int(input("Enter a? "));
2. b = int(input("Enter b? ")); Enter a? 100
3. c = int(input("Enter c? ")); Enter b? 120
4. if a>b and a>c: Enter c? 130
5. print("a is largest"); c is largest
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");

The if-else statement


 The if-else statement provides an else block combined with the if statement
which is executed in the false case of the condition.
 If the condition is true, then the if-block is executed. Otherwise, the else-
block is executed.

The syntax of the if-else statement is given below.

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...")

The elif statement


 The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them.
We can have any number of elif statements in our program depending upon
our need. However, using elif is optional.
 The elif statement works like an if-else-if ladder statement in C. It must be
succeeded by an if statement.

The syntax of the elif statement is given below.

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 ?")

Python Nested if statements


 We can have a if...elif...else statement inside another if...elif...else statement.
This is called nesting in computer programming.

 Any number of these statements can be nested inside one another.


Indentation is the only way to figure out the level of nesting. This can get
confusing, so must be avoided if we can.

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:-

Python While Loops


 The while loop is also known as a pre-tested loop. In general, a while loop
allows a part of the code to be executed as long as the given condition is
true.
 It can be viewed as a repeating if statement. The while loop is mostly used in
the case where the number of iterations is not known in advance.
 The syntax is given below.
while expression:
statements
 Here, the statements can be a single statement or the group of statements.
The expression should be any valid python expression resulting into true or
false. The true is any non-zero value.

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

Infinite while loop


 If the condition given in the while loop never becomes false then the while
loop will never terminate and result into the infinite while loop.
 Any non-zero value in the while loop indicates an always-true condition
whereas 0 indicates the always-false condition. This type of approach is
useful if we want our program to run continuously in the loop without any
disturbance.
Example 1
while (1):
print("Hi! we are inside the infinite while loop");
Output:
Hi! we are inside the infinite while loop
(infinite times)

Python for loop


The for loop in Python is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like list, tuple,
or dictionary.

The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)
Example 1 Output:

i=1

n=int(input("Enter the number up to which you 0 1 2 3 4 5 6 7 8 9


want to print the natural numbers?"))

for i in range(0,10):

print(i,end = ' ')

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

Nested for loop in python


 Python allows us to nest any number of for loops inside a for loop. The inner
loop is executed n number of times for every iteration of the outer loop. The
syntax of the nested for loop in python is given below.

for iterating_var1 in sequence:


for iterating_var2 in sequence:
#block of statements
#Other statements
Output:
Example 1
1. n = int(input("Enter the number of rows yo Enter the number of rows you want to
u want to print?")) print?5
2. i,j=0,0 *
3. for i in range(0,n): **
4. print() ***
5. for j in range(0,i+1): ****
print("*",end="") *****

----------------------------------------------------------------------------------------------------

37
Programming With Python-22616

Loop manipulation using continue ,pass, break,else:-

Python continue Statement

 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

Python break statement


 The break is a keyword in python which is used to bring the program control
out of the loop. The break statement breaks the loops one by one, i.e., in the
case of nested loops, it breaks the inner loop first and then proceeds to outer
loops. In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after the loop.
 The break is commonly used in the cases where we need to break the loop
for a given condition.
 The syntax of the break is given below.

#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);

Python pass Statement:-


 It is used when a statement is required syntactically but you do not want
any command or code to execute.

39
Programming With Python-22616

 The pass statement is a null operation; nothing happens when it executes.


The pass is also useful in places where your code will eventually go, but
has not been written yet (e.g., in stubs for example) −
 Syntax
Pass
Example1 When the above code is executed,
#!/usr/bin/python it produces following result −
Current Letter : P
for letter in 'Python': Current Letter : y
if letter == 'h': Current Letter : t
pass This is pass block
print 'This is pass block' Current Letter : h
print 'Current Letter :', letter Current Letter : o
Current Letter : n
print "Good bye!" Good bye!

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.

How to create a list?


 In Python programming, a list is created by placing all the items (elements)
inside a square bracket [ ], separated by commas.
 It can have any number of items and they may be of different types (integer,
float, string etc.).
# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

 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']]

How to access elements from a list?

 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.

Nested list are accessed using nested indexing.

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

# Error! Only integer can be used for indexing


# my_list[4.0]

# 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])

How to slice lists in Python?

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

# elements beginning to 4th


print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

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

How to change or add elements to a list?


 List are mutable, meaning, their elements can be changed
unlike string or tuple.

 We can use assignment operator (=) to change an item or a range of items.

# mistake values
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

# Output: [1, 4, 6, 8]
print(odd)

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

# 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

odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]


print(odd)

 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: ["re", "re", "re"]


print(["re"] * 3)

 Furthermore, we can insert one item at a desired location by using the


method insert() or insert multiple items by squeezing it into an empty slice
of a list.
odd = [1, 9]
odd.insert(1,3)

# 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']

# delete one item


del my_list[2]

# Output: ['p', 'r', 'b', 'l', 'e', 'm']

45
Programming With Python-22616

print(my_list)

# delete multiple items


del my_list[1:5]

# Output: ['p', 'm']


print(my_list)

# delete entire list


del my_list

# Error: List not defined


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: ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']


print(my_list)

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.

>>> my_list = ['p','r','o','b','l','e','m']


>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python List Built-in functions


 Python provides the following built-in functions which can be used with the
lists.
SN Function Description
1 cmp(list1, list2) It compares the elements of both the lists.
2 len(list) It is used to calculate the length of the list.
3 max(list) It returns the maximum element of the list.
4 min(list) It returns the minimum element of the list.
5 list(seq) It converts any sequence to the list.

Python List cmp() Method


 Python list method cmp() compares elements of two lists.
 Syntax
Following is the syntax for cmp() method −
cmp(list1, list2)

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.

 If numbers, perform numeric coercion if necessary and compare.


 If either element is a number, then the other element is "larger" (numbers are
"smallest").
 Otherwise, types are sorted alphabetically by name.
 If we reached the end of one of the lists, the longer list is "larger." If we
exhaust both lists and share the same data, the result is a tie, meaning that 0
is returned.
Example
The following example shows the usage of cmp() method.
list1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
When we run above program, it produces following result −
-1
1
-1
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
Python List len() Method
Description
Python list method len() returns the number of elements in the list.
Syntax
Following is the syntax for len() method −

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

Python List max() Method


Description
Python list method max returns the elements from the list with maximum value.
Syntax
Following is the syntax for max() method −
max(list)
Parameters
 list − This is a list from which max valued element to be returned.
Return Value
This method returns the elements from the list with maximum value.
Example
The following example shows the usage of max() method.
list1, list2 = [123, 'xyz', 'pqrs', 'abc'], [456, 700, 200]
print "Max value element : ", max(list1)
print "Max value element : ", max(list2)
49
Programming With Python-22616

When we run above program, it produces following result −


Max value element : pqrs
Max value element : 700

Python List min() Method


Description
Python list method min() returns the elements from the list with minimum value.
Syntax
Following is the syntax for min() method −
min(list)
Parameters
 list − This is a list from which min valued element to be returned.
Return Value
This method returns the elements from the list with minimum value.
Example
The following example shows the usage of min() method.
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "min value element : ", min(list1)
print "min value element : ", min(list2)
When we run above program, it produces following result −
min value element : 123
min value element : 200
----------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------

50
Programming With Python-22616

Python List list() Method:-


Description
Python list method list() takes sequence types and converts them to lists. This is
used to convert a given tuple into list.
Note − Tuple are very similar to lists with only difference that element values of a
tuple can not be changed and tuple elements are put between parentheses instead
of square bracket.
Syntax
Following is the syntax for list() method −
list( seq )
Parameters
 seq − This is a tuple to be converted into list.
Return Value
This method returns the list.
Example
The following example shows the usage of list() method.
aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print "List elements : ", aList
When we run above program, it produces following result −
List elements : [123, 'xyz', 'zara', 'abc']
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------

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: ()

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple) # Output: (1, "Hello", 3.4)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# Output: ("mouse", [8, 4, 6], (1, 2, 3))


print(my_tuple)

 A tuple can also be created without using parentheses. This is known as


tuple packing.
my_tuple = 3, 4.6, "dog"
print(my_tuple) # Output: 3, 4.6, "dog"

# tuple unpacking is also possible

52
Programming With Python-22616

a, b, c = my_tuple

print(a) #3
print(b) # 4.6
print(c) # dog

 Creating a tuple with one element is a bit tricky.


 Having one element within parentheses is not enough. We will need a
trailing comma to indicate that it is, in fact, a tuple.
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>

# Creating a tuple having one element


my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>

# 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'

# IndexError: list index out of range


# print(my_tuple[6])
53
Programming With Python-22616

# Index must be an integer


# TypeError: list indices must be integers, not float
# my_tuple[2.0]

# 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')

# elements 2nd to 4th


# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# elements beginning to 2nd


# Output: ('p', 'r')
print(my_tuple[:-7])

# elements 8th to end


# Output: ('i', 'z')
print(my_tuple[7:])

# elements beginning to end


54
Programming With Python-22616

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

 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 the
index that will slice the portion from the tuple.

----------------------------------------------------------------------------------------------------
Changing a Tuple

 Unlike lists, tuples are immutable.


 This means that elements of a tuple cannot be changed once it has been
assigned. But, if the element is itself a mutable datatype like list, its nested
items can be changed.
 We can also assign a tuple to different values (reassignment).
my_tuple = (4, 2, 3, [6, 5])
# TypeError: 'tuple' object does not support item assignment
# my_tuple[1] = 9
# However, item of mutable element can be changed
my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])
print(my_tuple)
# Tuples can be reassigned
my_tuple = ('p','r','o','g','r','a','m','i','z')
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
----------------------------------------------------------------------------------------------------
 We can use + operator to combine two tuples. This is also
called concatenation.
 We can also repeat the elements in a tuple for a given number of times
using the * operator.
 Both + and * operations result in a new tuple.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))

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')

# can't delete items


# TypeError: 'tuple' object doesn't support item deletion
# del my_tuple[3]

# Can delete an entire tuple


del my_tuple

# NameError: name 'my_tuple' is not defined


print(my_tuple)
----------------------------------------------------------------------------------------------------

Python Tuple inbuilt functions-

SN Function Description

1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater tha
tuple2) false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple.

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.

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

What is a set in Python?


 A set is an unordered collection of items. Every element is unique (no
duplicates) and must be immutable (which cannot be changed).
 However, the set itself is mutable. We can add or remove items from it.
 Sets can be used to perform mathematical set operations like union,
intersection, symmetric difference etc.

How to create a set?


 A set is created by placing all the items (elements) inside curly braces {},
separated by comma or by using the built-in function set().
 It can have any number of items and they may be of different types (integer,
float, tuple, string etc.). But a set cannot have a mutable element, like list, set
or dictionary, as its element.
# set of integers {1, 2, 3}
my_set = {1, 2, 3}

57
Programming With Python-22616

print(my_set) {1.0, 'Hello', (1, 2, 3)}

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

 Try the following examples as well.

# set do not have duplicates


# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)

 Creating an empty set is a bit tricky.


 Empty curly braces {} will make an empty dictionary in Python. To
make a set without any elements we use the set() function without any
argument.
# initialize a with {}
a = {}

# check data type of a


# Output: <class 'dict'>
print(type(a))

# initialize a with set()


a = set()

# check data type of a


# Output: <class 'set'>
print(type(a))

How to change a set in Python?


 Sets are mutable. But since they are unordered, indexing have no meaning.
 We cannot access or change an element of set using indexing or slicing. Set
does not support it.

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]

10.# add an element


11.# Output: {1, 2, 3}
12.my_set.add(2)
13.print(my_set)

14.# add multiple elements


15.# Output: {1, 2, 3, 4}
16.my_set.update([2,3,4])
17.print(my_set)

18.# add list and set


19.# Output: {1, 2, 3, 4, 5, 6, 8}
20.my_set.update([4,5], {1,6,8})
21.print(my_set)

When you run the program, the output will be:

{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}

59
Programming With Python-22616

How to remove elements from a set?


 A particular item can be removed from set using
methods, discard() and remove().
 The only difference between the two is that, while using discard() if the item
does not exist in the set, it remains unchanged. But remove() will raise an
error in such condition.

 The following example will illustrate this.

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

Python Set Operations


 Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with
operators or methods.
 Let us consider the following two sets for the following operations.
Python Set Operations
 Sets can be used to carry out mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with
operators or methods.
 Let us consider the following two sets for the following operations.
1. >>> A = {1, 2, 3, 4, 5}
2. >>> B = {4, 5, 6, 7, 8}

Set Union

 Union of A and B is a set of all elements from both sets.


 Union is performed using | operator. Same can be accomplished using the method union()
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)

 Try the following examples on Python shell.

61
Programming With Python-22616

# use union function


>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection-

 Intersection of A and B is a set of elements that are common in both sets.


 Intersection is performed using & operator. Same can be accomplished
using the method intersection().

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use & operator


# Output: {4, 5}
print(A & B)

 Try the following examples on Python shell.

# use intersection function on A


>>> A.intersection(B)
{4, 5}

# use intersection function on B


>>> B.intersection(A)
{4, 5}

62
Programming With Python-22616

Set Difference-

 Difference of A and B (A - B) is a set of elements that are only in A but not


in B. Similarly, B - A is a set of element in B but not in A.
 Difference is performed using - operator. Same can be accomplished using
the method difference().
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use - operator on A
# Output: {1, 2, 3}
print(A - B)

 Try the following examples on Python shell.

# use difference function on A


>>> A.difference(B)
{1, 2, 3}

# use - operator on B
>>> B - A
{8, 6, 7}

# use difference function on B


>>> B.difference(A)
{8, 6, 7}

63
Programming With Python-22616

Set Symmetric Difference-

 Symmetric Difference of A and B is a set of elements in


both A and B except those that are common in both.
 Symmetric difference is performed using ^ operator. Same can be
accomplished using the method symmetric_difference().
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
 Try the following examples on Python shell.

# use symmetric_difference function on A


>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}

# use symmetric_difference function on B


>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Built-in Functions with Set
 Built-in functions
like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are
commonly used with set to perform different tasks.

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

 What is dictionary in Python?


 Python dictionary is an unordered collection of items. While other
compound data types have only value as an element, a dictionary has a
key: value pair.
 Dictionaries are optimized to retrieve values when the key is known.
How to create a dictionary?

 Creating a dictionary is as simple as placing items inside curly braces {}


separated by comma.
 An item has a key and the corresponding value expressed as a pair, key:
value.
 While values can be of any data type and can repeat, keys must be of
immutable type (string, number or tuple with immutable elements) and must
be unique.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()

65
Programming With Python-22616

my_dict = dict({1:'apple', 2:'ball'})


# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
 As you can see above, we can also create a dictionary using the built-in
function dict().

How to access elements from a dictionary?

 While indexing is used with other container types to access values,


dictionary uses keys. Key can be used either inside square brackets or with
the get() method.

 The difference while using get() is that it returns None instead of KeyError,
if the key is not found.

my_dict = {'name':'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
# my_dict['address']

 When you run the program, the output will be:

Jack
26

How to change or add elements in a dictionary?

 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

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name':


'Jack'}
print(my_dict)

 When you run the program, the output will be:

{'name': 'Jack', 'age': 27}


{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

How to delete or remove elements from a dictionary?

 We can remove a particular item in a dictionary by using the method pop().


This method removes as item with the provided key and returns the value.

 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}

# remove a particular item


# Output: 16
print(squares.pop(4))

67
Programming With Python-22616

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item


# Output: (1, 1)
print(squares.popitem())

# Output: {2: 4, 3: 9, 5: 25}


print(squares)

# delete a particular item


del squares[5]

# Output: {2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
# print(squares)

 When you run the program, the output will be:

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

Python Dictionary Methods

 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 with Dictionary-

 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

Return True if any key of the dictionary is true. If the


any() dictionary is empty, return False.
Return the length (the number of items) in the
len() dictionary.
cmp() Compares items of two dictionaries.

Here are some examples that uses built-in functions to work with dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# 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-

What is a function in Python?

 In Python, function is a group of related statements that perform a specific


task.
 Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
 Furthermore, it avoids repetition and makes code reusable.
Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition which consists of following components.

 Keyword def marks the start of function header.


 A function name to uniquely identify it. Function naming follows the same
rules of writing identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They
are optional.
 A colon (:) to mark the end of function header.
 Optional documentation string (docstring) to describe what the function
does.
 One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).
 An optional return statement to return a value from the function.

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!

How Function works in Python?

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

Value inside function: 10


Value outside function: 20

 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

 Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves .

Python Built-in Function-

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

Python abs() returns absolute value of a number

Python all() returns true when all elements in iterable is true

Python any() Checks if any Element of an Iterable is True

Returns String Containing Printable


Python ascii() Representation

Python bin() converts integer to binary string

Python bool() Converts a Value to Boolean

Python bytearray() returns array of given byte size

Python bytes() returns immutable bytes object

Python callable() Checks if the Object is Callable

Python chr() Returns a Character (a string) from an Integer

Python classmethod() returns class method for given function

Python compile() Returns a Python code object

Python complex() Creates a Complex Number

Python delattr() Deletes Attribute From the Object

Python dict() Creates a Dictionary

Python dir() Tries to Return Attributes of Object

Python divmod() Returns a Tuple of Quotient and Remainder

Python enumerate() Returns an Enumerate Object

75
Programming With Python-22616

Method Description

Python eval() Runs Python Code Within Program

Python exec() Executes Dynamically Created Program

Python filter() constructs iterator from elements which are true

returns floating point number from number,


Python float() string

Python format() returns formatted representation of a value

Python frozenset() returns immutable frozenset object

Python getattr() returns value of named attribute of an object

returns dictionary of current global symbol


Python globals() table

Python hasattr() returns whether object has named attribute

Python hash() returns hash value of an object

Python help() Invokes the built-in Help System

Python hex() Converts to Integer to Hexadecimal

Python id() Returns Identify of an Object

Python input() reads and returns a line of string

Python int() returns integer from a number or string

Python isinstance() Checks if a Object is an Instance of Class

Python issubclass() Checks if a Object is Subclass of a Class

Python iter() returns iterator for an object

76
Programming With Python-22616

Method Description

Python len() Returns Length of an Object

Python list() Function creates list in Python

Returns dictionary of a current local symbol


Python locals() table

Python map() Applies Function and Returns a List

Python max() returns largest element

Python memoryview() returns memory view of an argument

Python min() returns smallest element

Python next() Retrieves Next Element from Iterator

Python object() Creates a Featureless Object

Python oct() converts integer to octal

Python open() Returns a File object

returns Unicode code point for Unicode


Python ord() character

Python pow() returns x to the power of y

Python print() Prints the Given Object

Python property() returns a property attribute

return sequence of integers between start and


Python range() stop

Python repr() returns printable representation of an object

77
Programming With Python-22616

Method Description

Python reversed() returns reversed iterator of a sequence

rounds a floating point number to ndigits


Python round() places.

Python set() returns a Python set

Python setattr() sets value of an attribute of object

Python slice() creates a slice object specified by range()

Python sorted() returns sorted list from a given iterable

Python staticmethod() creates static method from a function

Python str() returns informal representation of an object

Python sum() Add items of an Iterable

Python super() Allow you to Refer Parent Class by super

Python tuple() Function Creates a Tuple

Python type() Returns Type of an Object

Python vars() Returns __dict__ attribute of a class

Python zip() Returns an Iterator of Tuples

Python __import__() Advanced Function Called by import

Python User-defined Functions


 Functions that we define ourselves to do certain specific task are referred as
user-defined functions. The way in which we define and call functions in
Python are already discussed.

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.

Advantages of user-defined functions

 User-defined functions help to decompose a large program into small


segments which makes program easy to understand, maintain and debug.
 If repeated code occurs in a program. Function can be used to include those
codes and execute when needed by calling that function.
 Programmars working on large project can divide the workload by making
different functions.

Example of a user-defined function

# Program to illustrate
# the use of user-defined functions

def add_numbers(x,y):
sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))

Enter a number: 2.4


Enter another number: 6.5
The sum is 8.9

 Here, we have defined the function my_addition() which adds two numbers
and returns the result.

79
Programming With Python-22616

 This is our user-defined function. We could have multiplied the two


numbers inside our function (it's all up to us). But this operation would not
be consistent with the name of the function. It would create ambiguity.

 It is always a good idea to name functions according to the task they


perform.

 In the above example, print() is a built-in function in Python.

----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
Python Functions

 A function is a block of code which only runs when it is called.

 You can pass data, known as parameters, into a function.

 A function can return data as a result.

Creating a Function

 In Python a function is defined using the def keyword


Example
def my_function():
print("Hello from a function")
Calling a Function
 To call a function, use the function name followed by parenthesis:

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

Default Parameter Value


 The following example shows how to use a default parameter
value.

 If we call the function without parameter, it uses the default value:

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

 You can send any data types of parameter to a function (string,


number, list, dictionary etc.), and it will be treated as the same data
type inside the function.

 E.g. if you send a List as a parameter, it will still be a List when it


reaches the function:

Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Output-
apple
banana
cherry

82

You might also like