0% found this document useful (0 votes)
7 views97 pages

Python Programming Basics Guide

The document outlines the curriculum for a Python Programming course, including an introduction to Python, its features, installation instructions, and programming modes. It covers Python syntax, variables, constants, and naming conventions, along with practical examples. Additionally, it discusses the advantages and disadvantages of using interactive and script modes for coding in Python.

Uploaded by

THANGA SELVI R
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)
7 views97 pages

Python Programming Basics Guide

The document outlines the curriculum for a Python Programming course, including an introduction to Python, its features, installation instructions, and programming modes. It covers Python syntax, variables, constants, and naming conventions, along with practical examples. Additionally, it discusses the advantages and disadvantages of using interactive and script modes for coding in Python.

Uploaded by

THANGA SELVI R
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

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


Academic Year 2025- 26 : Summer Semester
10211CS213 / PYTHON PROGRAMMING
Faculty Name: Dr. R. Thanga Selvi
Slot: S2-1L14 & S10-1L7

Unit I Introduction 3
Python Basics: variables-data types-operators and expressions-control statements- comments in the
program-python collections (List, Tuple, Set, Dictionary)-modules- packages and composition-python
functions-build-in functions-Lambda functions-python iterator and generator.
Case Study: Shuffling a Deck o f Card

What is Python?
Python is a general-purpose
programming language. It was interpreted, interactive, object-oriented, and high-level
Python source code is also avail acreated by Guido van Rossum during 1985- 1990. Like Perl,
P
ble under the GNU General Public License (G L)
What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alon gside software to create workflows.

 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematic s.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a f unctional way.

10211 C S 213 – PYTHON P R O G R A M M I N G Page 1


Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.

How to install Python in Windows?

Step 1 − Select Version of Python to Install


Python has various versions available with differences between the syntax and working of different
versions of the language. We need to choose the version which we want to use or need.

Step 2 − Download Python Executable Installer


On the web browser, in the official site of python ([Link]), move to the Download for
Windows section.
All the available versions of Python will be listed. Select the version required by you and click on
Download. Let suppose, we choose the Python 3.9.1 version.

On clicking download, various available executable installers shall be visible with different
operating system specifications. Choose the installer which suits your system operating system
and download the installer. Let suppose, we select the Windows installer (64 bits).

The download size is less than 30MB.

10211 C S 213 – PYTHON P R O G R A M M I N G Page 2


Step 3 − Run Executable Installer
We downloaded the Python 3.9.1 Windows 64 bit installer.
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install
New.

On clicking the Install Now, The installation process starts.

10211 C S 213 – PYTHON P R O G R A M M I N G Page 3


The installation process will take few minutes to complete and once the installation is successful,
the following screen is displayed.

Step 4 − Verify Python is installed on Windows


To ensure if Python is successfully installed on your system. Follow the given steps −

10211 C S 213 – PYTHON P R O G R A M M I N G Page 4


 Open the command prompt.
 Type ‘python’ and press enter.
 The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.

How to install Pycharm IDE in Windows?

PyCharm is a cross-platform IDE that provides consistent experience on the Windows, macOS,
and Linux operating systems.
PyCharm is available in three editions: Professional, Community, and Edu. The
Community and Edu editions are open-source projects and they are free, but they have fewer
features. PyCharm Edu provides courses and helps you learn programming with Python. The
Professional edition is commercial, and provides an outstanding set of tools and features.
Step 1: Download Pycharm Executable Installer
[Link]

1. Run the installer and follow the wizard steps.


Mind the following options in the installation wizard
o 64-bit launcher: Adds a launching icon to the Desktop.

10211 C S 213 – PYTHON P R O G R A M M I N G Page 5


o Open Folder as Project: Adds an option to the folder context menu that will allow opening the
selected directory as a PyCharm project.
o .py: Establishes an association with Python files to open them in PyCharm.
o Add launchers dir to the PATH: Allows running this PyCharm instance from the Console
without specifying the path to it.
To run PyCharm, find it in the Windows Start menu or use the desktop shortcut. You can also
run the launcher batch script or executable in the installation directory under bin.

10211 C S 213 – PYTHON P R O G R A M M I N G Page 6


Python Programming in Interactive vs Script Mode

In Python, there are two options/methods for running code:

 Interactive mode
 Script mode

Interactive Mode

Interactive mode, also known as the REPL provides us with a quick way of running blocks or a
single line of Python code. The code executes via the Python shell, which comes with Python
installation.

To access the Python shell, open the terminal of your operating system and then type "python".
Press the enter key and the Python shell will appear.

The >>> indicates that the Python shell is ready to execute and send your commands to the Python
interpreter. The result is immediately displayed on the Python shell as soon as the Python
interpreter interprets the command.

To run your Python statements, just type them and hit the enter key. You will get the results
immediately, unlike in script mode. For example, to print the text "Hello World", we can type the
following:

10211 C S 213 – PYTHON P R O G R A M M I N G Page 7


Pros and Cons of Interactive Mode

The following are the advantages of running your code in interactive mode:

 Helpful when your script is extremely short and you want immediate results.
 Faster as you only have to type a command and then press the enter key to get the results.
 Good for beginners who need to understand Python basics.

The following are the disadvantages of running your code in the interactive mode:

 Editing the code in interactive mode is hard as you have to move back to the previous
commands or else you have to rewrite the whole command again.
 It's very tedious to run long pieces of code.

Script Mode

If you need to write a long piece of Python code or your Python script spans multiple files,
interactive mode is not recommended. Script mode is the way to go in such cases. In script mode,
You write your code in a text file then save it with a .py extension which stands for "Python". Note
that you can use any text editor for this, including Sublime, Atom, notepad++, etc.

If you are in the standard Python shell, you can click "File" then choose "New" or simply hit "Ctrl
+ N" on your keyboard to open a blank script in which you can write your code. You can then
press "Ctrl + S" to save it.

After writing your code, you can run it by clicking "Run" then "Run Module" or simply press F5.

Pros and Cons of Script Mode

The following are the advantages of running your code in script mode:

 It is easy to run large pieces of code.


 Editing your script is easier in script mode.
 Good for both beginners and experts.

The following are the disadvantages of using the script mode:

10211 C S 213 – PYTHON P R O G R A M M I N G Page 8


 Can be tedious when you need to run only a single or a few lines of cod.
 You must create and save a file before executing your code.

Python Basic Syntax


Python statement ends with the token NEWLINE character (carriage return). It means each
line in a Python script is a statement. The following Python script contains three statements
in three separate lines.

print('id: ', 1)
print('First Name: ', 'Steve')
print('Last Name: ', 'Jobs')
Use backslash character \ to join a statement span over multiple lines, as shown below.

if 100 > 99 and \


200 <= 300 and \
True != False:
print('Hello World!')
Use the semicolon ; to separate multiple statements in a single line.

print('id: ', 1);print('First Name: ', 'Steve');print('Last Name: ',


'Jobs')

Expressions in parentheses (), square brackets [ ], or curly braces { } can be spread over
multiple lines without using backslashes.

list = [1, 2, 3, 4

10211 C S 213 – PYTHON P R O G R A M M I N G Page 9


5, 6, 7, 8,
9, 10, 11, 12]

Indentation in Python

Leading space or tab at the beginning of the line is considered as indentation level of the line,
which is used to determine the group of statements. Statements with the same level of indentation
considered as a group or block.

For example, functions, classes, or loops in Python contains a block of tatements to be


executed. Other programming languages such as C# or Java use curly braces { } to denote a
block of code. Python uses indentation (a space or a tab) to denote a block of statements.

Indentation Rules

 Use the colon : to start a block and press Enter.


 All the lines in a block must use the same indentation, either space or a tab.
 Python recommends four spaces as indentation to make the code more readable. Do not
mix space and tab in the same block.
 A block can have inner blocks with next level indentation.

Example

if 10 > 5: # 1st block starts


print("10 is greater than 5") # 1st block
print("Now checking 20 > 10") # 1st block
if 20 > 10: # 1st block
print("20 is greater than 10") # inner block
elif: # 2nd block starts

print("10 is less than 5") # 2nd block


print("This will never print") # 2nd block

The following example illustrates the use of indents in Python shell:

10211CS213 - PYTHON PROGRAMMING Page 10


As you can see, in the Python shell, the SayHello() function block started after : and pressing
Enter. It then displayed ... to mark the block. Use four space (even a single space is ok) or a
tab for indent and then write a statement. To end the block, press Enter two times.

The same function can be written in IDLE or any other GUI-based IDE as shown below,
using Tab as indentation.

Python Variables

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

as a container that holds data that can be changed later in the program. For example,
number = 10
Here, we have created a variable named number. We have assigned the value 10 to the variable.
You can think of variables as a bag to store books in it and that book can be replaced at any time.
number = 10
number = 1.1
Initially, the value of number was 10. Later, it was changed to 1.1.

Assigning values to Variables in Python


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

website = "[Link]"
print(website)

Output

[Link]

In the above program, we assigned a value [Link] to the variable website. Then, we printed
out the value assigned to websit e i.e. [Link]

10211CS213 - PYTHON PROGRAMMING Page 11


Changing the value of a variable

website = "[Link]"
print(website)
# assigning a new value to website
website = "[Link]"
print(website)

Output

[Link]
[Link]

Assigning multiple values to multiple variables

a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)

If we want to assign the same value to multiple variables at once, we can do this as:

x = y = z = "same"
print (x)
print (y)
print (z)

Constants

A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
as containers that hold information which cannot be changed later.

You can think of constants as a bag to store some books which cannot be replaced once placed
inside the bag.

10211CS213 - PYTHON PROGRAMMING Page 12


Assigning value to constant in Python

In Python, constants are usually declared and assigned in a module. Here, the module is a new
file containing variables, functions, etc which is imported to the main file. Inside the module,
constants are written in all capital letters and underscores separating the words.

Declaring and assigning value to a constant


Create a [Link]:

PI = 3.14
GRAVITY = 9.8

Create a [Link]:

import constant
print([Link])
print([Link])

Output

3.14
9.8

In the above program, we create a [Link] module file. Then, we assign the constant value
to PI and GRAVITY. After that, we create a [Link] file and import the constant module.
Finally, we print the constant value.

Python Naming Conventions

The Python program can contain variables, functions, classes, modules, packages, etc. Identifier
is the name given to these programming elements. An identifier should start with either an
alphabet letter (lower or upper case) or an underscore (_). After that, more than one alphabet letter
(a-z or A-Z), digits (0-9), or underscores may be used to form an identifier. No other characters
are allowed.

 Identifiers in Python are case sensitive, which means variables named age and Age are
different.
 Class names should use the TitleCase convention. It should begin with an uppercase
alphabet letter e.g. MyClass, Employee, Person.
 Function names should be in lowercase. Multiple words should be separated by
underscores, e.g. add(num), calculate_tax(amount).
 Variable names in the function should be in lowercase e.g., x, num, salary.
 Module and package names should be in lowercase e.g., mymodule, tax_calculation. Use
underscores to improve readability.
 Constant variable names should be in uppercase e.g., RATE, TAX_RATE.
 Use of one or two underscore characters when naming the instance attributes of a class.

10211CS213 - PYTHON PROGRAMMING Page 13


 Two leading and trailing underscores are used in Python itself for a special purpose, e.g.
add , init , etc.

Literals
Literal is a raw data given in a variable or constant. In Python, there are various types of literals
they are as follows:
Numeric Literals
Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different
numerical types: Integer, Float, and Complex.
How to use Numeric literals in Python?

a = 0b1010 #Binary Literals


b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal

#Float Literal
float_1 = 10.5
float_2 = 1.5e2

#Complex Literal
x = 3.14j

print(a, b, c, d)
print(float_1, float_2)
print(x, [Link], [Link])

Output

10 100 200 300


10.5 150.0
3.14j 3.14 0.0

In the above program,


We assigned integer literals into different variables. Here, a is binary literal, b is a decimal
literal, c is an octal literal and d is a hexadecimal literal.
 When we print the variables, all the literals are converted into decimal values.
 10.5 and 1.5e2 are floating-point literals. 1.5e2 is expressed with exponential and is equivalent
to 1.5 * 102.
We assigned a complex literal i.e 3.14j in variable x. Then we use imaginary literal ([Link])
and real literal ([Link]) to create imaginary and real parts of complex numbers.

10211CS213 - PYTHON PROGRAMMING Page 14


String literals

A string literal is a sequence of characters surrounded by quotes. We can use both single, double,
or triple quotes for a string. And, a character literal is a single character surrounded by single or
double quotes.

How to use string literals in Python?

strings = "This is Python"


char = "C"
multiline_str = """This is a multiline string with more than one line code."""
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string"

print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)

Output

This is Python
C
This is a multiline string with more than one line code.
Ünicöde
raw \n string

In the above program, This is Python is a string literal and C is a character literal.
The value in triple-quotes """ assigned to the multiline_str is a multi-line string literal.
The string u"\u00dcnic\u00f6de" is a Unicode literal which supports characters other than
English. In this case, \u00dc represents Ü and \u00f6 represents ö.
r"raw \n string" is a raw string literal.

Boolean literals
A Boolean literal can have any of the two values: True or False.
How to use boolean literals in Python?

x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)

10211CS213 - PYTHON PROGRAMMING Page 15


print("b:", b)

Output

x is True
y is False
a: 5
b: 10

In the above program, we use boolean literal True and False. In Python, True represents the
value as 1 and False as 0 . The value of x is True because 1 is equal to True. And, the value
False 1
of y is because is not equal to False.

Similarly, we can use the True and False in numeric expressions as the value. The value
of a is 5 because we add True which has a value of 1 with 4. Similarly, b is 10 because we add
False 0
the having value of with 10.

Special literals
Python contains one special literal i.e. None. We use it to specify that the field has not been
created.
How to use special literals in Python?

drink = "Available"
food = None

def menu(x):
if x == drink:
print(drink)
else:
print(food)

menu(drink)
menu(food)

Output

Available
None

10211CS213 - PYTHON PROGRAMMING Page 16


In the above program, we define a menu function. Inside menu, when we set the argument
as drink then, it displays Available. And, when the argument is food, it displays None.

Literal Collections
There are four different literal collections List literals, Tuple literals, Dict literals, and Set
literals.

10211CS213 - PYTHON PROGRAMMING Page 17


Example 10: How to use literals collections in Python?

fruits = ["apple", "mango", "orange"] #list


numbers = (1, 2, 3) #tuple
alphabets = {'a':'apple', 'b':'ball', 'c':'cat'} #dictionary
vowels = {'a', 'e', 'i' , 'o', 'u'} #set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)

Output

['apple', 'mango', 'orange']


(1, 2, 3)
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'e', 'a', 'o', 'i', 'u'}

In the above program, we created a list of fruits, a tuple of numbers, a dictionary dict having
values with keys designated to each value and a set of vowels.

Data Types in Python


As the name suggests, a data type is the classification of the type of values that can be assigned
to variables.
Python data types are categorized into two as follows:
 Mutable Data Types: Data types in python where the value assigned to a variable can be
changed. Some mutable data types in Python include set, list, user-defined classes and
dictionary.
 Immutable Data Types: Data types in python where the value assigned to a variable
cannot be changed. Some immutable data types in Python are int, decimal, float, tuple,
bool, range and string.

10211CS213 - PYTHON PROGRAMMING Page 18


Let’s discuss the above-mentioned core data types in Python.
 Numbers: The number data type in Python is used to store numerical values. It is used to
carry out normal mathematical operations.
 Strings: Strings in Python are used to store textual information. They are used to carry out
operations that perform positional ordering among items.
 Lists: The list data type is the most generic Python data type. Lists can consist of a
collection of mixed data ty pes, stored by relative positions.
 Tuples: Python Tuples ar e one among the immutable Python data types t hat can store
values of mixed data types. They are basically a list that cannot be changed.
 Sets: Sets in Python are a data type that can be considered as an unordered collection of
data without any duplicate items.
 Dictionaries: Dictionaries in Python can store multiple objects, but unlike lists, in
dictionaries, the objects are stored by keys and not by positions.

Display Output

The print() serves as an output statement in Python. It echoes the value of any Python
expression on the Python shell.

Multiple values can be displayed by the single print() function separated by comma. The
following example displays values of name and age variables using the
single print() function.

>>> name="Ram"
>>> print(name) # display single variable
Ram
>>> age=21
>>> print(name, age)# display multiple variables

10211CS213 - PYTHON PROGRAMMING Page 19


Ram 21
>>> print("Name:", name, ", Age:",age) # display formatted
output
Name: Ram, Age: 21

By default, a single space ' ' acts as a separator between values. However, any other character
can be used by providing a sep parameter.
The actual syntax of the print() function is:
print(*objects, sep=' ', end='\n', file=[Link], flush=False)
Here, objects is the value(s) to be printed.
The sep separator is used betwe en the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is [Link] (screen).
Here is an example to illustrate this.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end=' &')

Output
1234
1*2*3*4
1#2#3#4&

Getting User's Input

The input() function is a part of the core library of standard Python distribution. It reads the
key strokes as a string object which can be referred to by a variable having a suitable name.

10211CS213 - PYTHON PROGRAMMING Page


110
Note that the blinking cursor waits for the user's input. The user enters his input and then hits Enter.
This will be captured as a string.
In the above example, the input() function takes the user's input from the next line, e.g. 'Steve'
in this case. input() will capture it and assign it to a name variable. The name variable will
display whatever the user has provided as the input.
The input() function has an optional string parameter that acts as a prompt for the user.

The input() function always reads the input as a string, even if comprises of digits. The type()
function used earlier confirms this behaviour.

>>> name=input("Enter your name: ")


Enter your name: Steve
>>> type(name)
<class 'str'>
>>> age=input("Enter your age: ")
Enter your age: 21
>>> type(age)
<class 'str'>

Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactiv einterpreter in
Python. We use the import keyword to do this.

10211CS213 - PYTHON PROGRAMMING


Page 20
For example, we can import the math module by typing the following line:

import math

We can use the module in the following ways:

import math
print([Link])

Output

3.141592653589793

Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:

>>> from math import pi


>>> pi
3.141592653589793

Python Type Conversion and Type Casting


Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.
Let's see an example where Python promotes the conversion of the lower data type (integer) to
the higher data type (float) to avoid data loss.
Example 1: Converting integer to float

num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

When we run the above program, the output will be:

10211CS213 - PYTHON PROGRAMMING Page 21


datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>

Value of num_new: 124.23


datatype of num_new: <class 'float'>

In the above program,


 We add two variables num_int and num_flo, storing the value in num_new.
 We will look at the data type of all three objects respectively.
 In the output, we can see the data type of num_int is an integer while the data type of num_flo is
a float.
Also, we can see the num_new has a float data type because Python always converts smaller
data types to larger data types to avoid the loss of data.

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required data type. We
use the predefined functions like int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type
of the objects.
Syntax :

<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to the expression.
Example 1: Addition of string and integer using explicit conversion

num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

When we run the above program, the output will be:

Data type of num_int: <class 'int'>


Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>

In the above program,

10211CS213 - PYTHON PROGRAMMING Page 22


 We add num_str and num_int variable.
 We converted num_str from string(higher) to integer(lower) type using int() function to perform
the addition.
num_str
 After converting
num_sum to an integer value, Python is able to add these two variables.
 We got the value and data type to be an integer.

Operators in Python
In Python, we have a set of special symbols that perform various kinds of operations such as logical
operations, mathematical operations, and more. These symbols are called Python operators. For
every symbol or operator, there is a unique kind of operation. The values on which the operators
perform their respective operations are known as operands.
Types of Operators in Python
Depending on the type of operations that the operators perform, they are categorized into the
following categories:
 Arithmetic Operators in Python
 Relational Operators in Python
 Assignment Operators in Python
 Logical Operators in Python
 Membership Operators in Python
 Identity Operators in Python
 Bitwise Operators in Python
Arithmetic operators
 Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
Operator Meaning Example
+ Add two operands or unary plus x + y+ 2
- Subtract right operand from the left or unary minus x - y- 2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
% Modulus - remainder of the division of left operand by the right x % y (remainder of x/y)
// Floor division - division that results into whole number adjusted to x // y
the left in the number line
** Exponent - left operand raised to the power of right x**y (x to the power y)
Comparison operators
Comparison operators are used to compare values. It returns either True or False according to the
condition.
Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - 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
<= Less than or equal to - True if left operand is less than or equal to the right x <= y

10211CS213 - PYTHON PROGRAMMING Page 23


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

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
Bitwise operators
Bitwise operators act on operands as if they were strings of binary digits. They operate 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)
~ 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 Equivalent 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
|= 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 types 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
is True if the operands are identical (refer to the same object) x is True

10211CS213 - PYTHON PROGRAMMING Page 24


is not True if the operands are not identical (do not refer to the same object) x is not True
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

Decision Making Statements


Decision making statement used to control the flow of execution of program depending upon
condition means if the condition is true then the block will execute and if the co dition is false
then block will not execute.
Type Of Decision Making Statement in Python
In Python there are three types of decision making statement.
1. if statements
2. if-else statements
3. Nested if-else statement

1. if Statements In Python
If statement will execute block of statements only if the condition is true.

if statements
Syntax of If Statement In Python
if(condition):
statements
Example of If Statement In Python
apple = 2
if (apple == 2):
print('You have two apple')

10211CS213 - PYTHON PROGRAMMING Page 25


Output
You have two apple
2. if-else Statements In Python
If else statements will execute one block of statements if condition is true else another block of
statement will be executed.

if-else statements
Syntax of if-else Statement In Python
if(condition):
statements
else:
statements
Example of if-else Statement In Python
age =19
if(age < 18):
print('you are minior')
else:
print('you are adult')
Output :-
you are adult

3. Nested if-else statement


Nested if-else statement target to another if or else statement

10211CS213 - PYTHON PROGRAMMING Page 26


Nested if-else statement
Syntax of Nested if-else In Python
If (condition):
statements
elif (condition):
statements
else:
statements
When one condition is true its respective block of statement will be executed remaining
conditions will be bypassed
Example of Nested if-else statement In Python
age =19
if(age < 18):
print('you are under 18')
elif(age == 18):
print('you are 18')
else:
print('you are above 18')
Output :-
you are above 18

Loops and Control Statements


In a programming language, a loop is a statement that contains instructions that continually
repeats until a certain condition is reached.

10211CS213 - PYTHON PROGRAMMING Page 27


Loops help us remove the redundancy of code when a task has to be repeated several times. With
the use of loops, we can cut short those hundred lines of code to a few. Suppose you want to
print the text “Hello, World!” 10 times. Rather than writing a print statement 10 times, you can
make use of loops by indicating the number of repetitions needed.
Loop Types
The three types of loops in Python programming are:

1. while loop
2. for loop
3. nested loops

1. While Loop In Python


While Loop In Python is used to execute a block of statement as long as a given condition is true.
And when the condition is false, the control will come out of the loop.
The condition is checked every time at the beginning of the loop.
While Loop Syntax
while (condition):
statements
Flowchart of While Loop

Python Flowchart of While Loop

10211CS213 - PYTHON PROGRAMMING Page 28


Example Of While Loop
x=0
while (x < 5):
print(x)
x=x+1
Output :-
0
1
2
3
4
While Loop With Else In Python
The else part is executed if the condition in the while loop becomes False.
Syntax of While Loop With Else
while (condition):
loop statements
else:
else statements
Example of While Loop With Else
x=1
while (x < 5):
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)
Output :-
inside while loop value of x is 1
inside while loop value of x is 2
inside while loop value of x is 3
inside while loop value of x is 4
inside else value of x is 5
Infinite While Loop In Python
A Infinite loop is a loop in which condition always remain True.
Example of Infinite While Loop
x=1
while (x == 1):
print('hello')
Output :-
hello
hello
hello

2. For Loop In Python


For loop in Python is used to iterate over items of any sequence, such as a list or a string.

10211CS213 - PYTHON PROGRAMMING Page 29


For Loop Syntax
for val in sequence:
statements
Flowchart of For Loop

Python Flowchart of For Loop


Example of For Loop
for i in range(1,5):
print(i)
Output :-
1
2
3
4
The range() Function In Python
The range() function is a built-in that is used to iterate over a sequence of numbers.
Syntax Of range() Function
range(start, stop[, step])
The range() Function Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the sequence.
Example 1 of range() function
for i in range(5):
print(i)

10211CS213 - PYTHON PROGRAMMING Page 30


Output :-
0
1
2
3
4
Example 2 of range() function

for i in range(2,9):
print(i)
Output :-
2
3
4
5
6
7
8
Example 3 of range() function using step parameter
for i in range(2,9,2):
print(i)
Output :-
2
4
6
8
For Loop With Else In Python
The else is an optional block that can be used with for [Link] else block with for loop executed
only if for loops terminates [Link] means that the loop did not encounter any break.
Example of For Loop With Else
list=[2,3,4,6,7]
for i in range(0,len(list)):
if(list[i]==5):
print('list has 5')
break
else:
print('list does not have 5')
Output :-
list does not have 5
3. Nested For Loops In Python
When one Loop defined within another Loop is called Nested Loops.
Syntax of Nested For Loops
for val in sequence:
for val in sequence:
statements
statements

10211CS213 - PYTHON PROGRAMMING Page 31


Example 1 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output :-
1
22
333
4444
55555
Type of Jump Statements in Python:-
1. break
2. continue
3. pass

1. break Statement in Python


break Statement in Python is used to terminate the loop.
Syntax of break Statement
break
Flowchart of break Statement

Flowchart of break Statements in Python


Example 1 of break statement
for i in range(10):
print(i)

10211CS213 - PYTHON PROGRAMMING Page 32


if(i == 7):
print('break')
break
Output :-
0
1
2
3
4
5
6
7
break
Example 2 of break statement
After break statement controls goes to next line pointing after the loop body.
for i in range(10):
print(i)
if(i == 7):
print('before break')
break
print('after break') # Inside loop body, any code after the break statement will not execute
print('Out of loop body')
Output :-
0
1
2
3
4
5
6
7
before break
Out of loop body
Example 3 of break statement
If a break statement is inside a nested loop, it will terminate the innermost loop and continue the
outer loop.
# printing table from 2 to 5, each table upto 5 iterations only
for i in range(2,6):
print('Table of ',i)
for j in range(1,11):

10211CS213 - PYTHON PROGRAMMING Page 33


print(i*j)
if (j == 5):
break
Output :-
Table of 2
2
4
6
8
10
Table of 3
3
6
9
12
15
Table of 4
4
8
12
16
20
Table of 5
5
10
15
20
25
2. continue Statement in Python
continue Statement in Python is used to skip all the remaining statements in the loop and move
controls back to the top of the loop.
Syntax of continue Statement
continue

10211CS213 - PYTHON PROGRAMMING Page 34


Flowchart of continue Statement

Flowchart of continue Statement in Python


Example of continue statement
for i in range(6):
if(i==3):
continue
print(i)
Output :-
0
1
2
4
5
when 'i' is equal to 3 continue statement will be executed which skip the print statement.

10211CS213 - PYTHON PROGRAMMING Page 35


3. pass Statement in Python
pass Statement in Python does nothing. You use pass statement when you create a method that
you don't want to implement, yet.
Example using pass statement
It makes a controller to pass by without executing any code.
def myMethod():
pass
print('hello')
Output :-
hello
Example without using pass statement
def myMethod():

print('hello')
Output :-
Traceback (most recent call last):
File "python", line 3
print('hello')
IndentationError: expected an indented block
Difference Between pass And continue Statement in Python
pass statement simply does nothing. You use pass statement when you create a method that you
don't want to implement, yet.

Where continue statement skip all the remaining statements in the loop and move controls back
to the top of the loop.

Python Comments
Comments can be used to explain Python code.
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!")
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
A comment does not have to be text that explains the code, it can also be used to prevent Python
from executing code:

10211CS213 - PYTHON PROGRAMMING Page 36


Example
#print("Hello, World!")
print("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!")
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!")

Python collections
Python List

Python lists are one of the most versatile data types that allow us to work with multiple elements
at once. For example,

# a list of programming languages


['Python', 'C++', 'JavaScript']

Create Python Lists


In Python, a list is created by placing elements inside square brackets [] , separated by commas.

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

A list can have any number of items and they may be of different types (integer, float, string,
etc.).

10211CS213 - PYTHON PROGRAMMING Page 37


# empty list
my_list = []

# list with mixed data types


my_list = [1, "Hello", 3.4]

A list can also have another list as an item. This is called a nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

Access List Elements


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. In Python, indices start at 0. So, a list

having 5 elements will have an index from 0 to 4.


Trying to access indexes other than these will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result in TypeError.

Nested lists are accessed using nested indexing.

my_list = ['p', 'r', 'o', 'b', 'e']

# first item
print(my_list[0]) # p

# third item
print(my_list[2]) # o

# fifth item
print(my_list[4]) # e

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

10211CS213 - PYTHON PROGRAMMING Page 38


# Nested indexing
print(n_list[0][1])

print(n_list[1][3])

# Error! Only integer can be used for indexing


print(my_list[4.0])

Output

p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float

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.

# Negative indexing in lists


my_list = ['p','r','o','b','e']

# last item
print(my_list[-1])

# fifth last item


print(my_list[-5])

Output

e
p

10211CS213 - PYTHON PROGRAMMING Page 39


List indexing in Python

List Slicing in Python


We can access a range of items in a list by using the slicing operator :.

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements from index 2 to index 4


print(my_list[2:5])

# elements from index 5 to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

Output

['o', 'g', 'r']


['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

10211CS213 - PYTHON PROGRAMMING Page 40


Add/Change List Elements
Lists are mutable, meaning their elements can be changed unlike string or tuple.
We can use the assignment operator = to change an item or a range of items.

# Correcting mistake values in a list


odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

print(odd)

# change 2nd to 4th items


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

print(odd)

Output

[1, 4, 6, 8]
[1, 3, 5, 7]

We can add one item to a list using the append() method or add several items using
the extend() method.

# Appending and Extending lists in Python


odd = [1, 3, 5]

[Link](7)

print(odd)

[Link]([9, 11, 13])

print(odd)

Output

10211CS213 - PYTHON PROGRAMMING Page 41


[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]

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.

# Concatenating and repeating lists


odd = [1, 3, 5]

print(odd + [9, 7, 5])

print(["re"] * 3)

Output

[1, 3, 5, 9, 7, 5]
['re', 're', 're']

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.

# Demonstration of list insert() method


odd = [1, 9]
[Link](1,3)

print(odd)

odd[2:2] = [5, 7]

print(odd)

Output

[1, 3, 9]
[1, 3, 5, 7, 9]

Delete List Elements


We can delete one or more items from a list using the Python del statement. It can even delete
the list entirely.

# Deleting list items

10211CS213 - PYTHON PROGRAMMING Page 42


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

# delete one item


del my_list[2]

print(my_list)

# delete multiple items


del my_list[1:5]

print(my_list)

# delete the entire list


del my_list

# Error: List not defined


print(my_list)

Output

['p', 'r', 'b', 'l', 'e', 'm']


['p', 'm']
Traceback (most recent call last):
File "<string>", line 18, in <module>
NameError: name 'my_list' is not defined

We can use remove() to remove the given item or pop() to remove an item at the given index.
The pop() method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
And, if we have to empty the whole list, we can use the clear() method.

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'

10211CS213 - PYTHON PROGRAMMING Page 43


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)

my_list.clear()

# Output: []
print(my_list)

Output

['r', 'o', 'b', 'l', 'e', 'm']


o
['r', 'b', 'l', 'e', 'm']
m
['r', 'b', 'l', 'e']
[]

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

10211CS213 - PYTHON PROGRAMMING Page 44


Python List Methods
Python has many useful list methods that makes it really easy to work with lists. Here are some
of the commonly used list methods.
Methods Descriptions
append() adds an element to the end of the list
extend() adds all elements of a list to another list
insert() inserts an item at the defined index
remove() removes an item from the list
pop() returns and removes an element at the given index
clear() removes all items from the list
index() returns the index of the first matched item
count() returns the count of the number of items passed as an argument
sort() sort items in a list in ascending order
reverse() reverse the order of items in the list
copy() returns a shallow copy of the list

# Example on Python list methods

my_list = [3, 8, 1, 6, 8, 8, 4]

# Add 'a' to the end


my_list.append('a')

# Output: [3, 8, 1, 6, 8, 8, 4, 'a']


print(my_list)

# Index of first occurrence of 8


print(my_list.index(8)) # Output: 1

# Count of 8 in the list


print(my_list.count(8)) # Output: 3

List Comprehension: Elegant way to create Lists


List comprehension is an elegant and concise way to create a new list from an existing list in
Python.
A list comprehension consists of an expression followed by for statement inside square brackets.
Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)]


print(pow2)

10211CS213 - PYTHON PROGRAMMING Page 45


Output

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

This code is equivalent to:

pow2 = []
for x in range(10):
[Link](2 ** x)

A list comprehension can optionally contain more for or if statements. An


optional if statement can filter out items for the new list. Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]


>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

Other List Operations in Python


List Membership Test
We can test if an item exists in a list or not, using the keyword in .

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

# Output: True
print('p' in my_list)

# Output: False
print('a' in my_list)

# Output: True
print('c' not in my_list)

Output

True

10211CS213 - PYTHON PROGRAMMING Page 46


False
True

Iterating Through a List

Using a for loop we can iterate through each item in a list.

for fruit in ['apple','banana','mango']:


print("I like",fruit)

Output

I like apple
I like banana
I like mango

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 we can change the elements of a list.
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.).

# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)

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

10211CS213 - PYTHON PROGRAMMING Page 47


print(my_tuple)

Output

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

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

my_tuple = 3, 4.6, "dog"


print(my_tuple)

# tuple unpacking is also possible


a, b, c = my_tuple

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

Output

(3, 4.6, 'dog')


3
4.6
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'>

Output

10211CS213 - PYTHON PROGRAMMING Page 48


<class 'str'>
<class '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 index outside of
the tuple index range(6,7,... in this example) 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.

# Accessing tuple elements using indexing


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

# 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

Output

p
t
s
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.

10211CS213 - PYTHON PROGRAMMING Page 49


# Negative indexing for accessing tuple elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])

Output

t
p

3. Slicing
We can access a range of items in a tuple by using the slicing operator colon : .

# Accessing tuple elements using slicing


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


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

Output

('r', 'o', 'g')


('p', 'r')
('i', 'z')
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

10211CS213 - PYTHON PROGRAMMING Page 50


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.

Element Slicing in Python


Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once they have been assigned. But, if the
element is itself a mutable data type like a list, its nested items can be changed.
We can also assign a tuple to different values (reassignment).

# Changing tuple values


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)

Output

(4, 2, 3, [9, 5])


('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

We can use + operator to combine two tuples. This is 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)

10211CS213 - PYTHON PROGRAMMING Page 51


print((1, 2, 3) + (4, 5, 6))

# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)

Output

(1, 2, 3, 4, 5, 6)
('Repeat', 'Repeat', 'Repeat')

Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or
remove items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.

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

Output

Traceback (most recent call last):


File "<string>", line 12, in <module>
NameError: name 'my_tuple' is not defined

Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two
methods are available.
Some examples of Python tuple methods:

my_tuple = ('a', 'p', 'p', 'l', 'e',)

print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

10211CS213 - PYTHON PROGRAMMING Page 52


Output

2
3

Other Tuple Operations


1. Tuple Membership Test
We can test if an item exists in a tuple or not, using the keyword in .

# Membership test in tuple


my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation
print('a' in my_tuple)
print('b' in my_tuple)

# Not in operation
print('g' not in my_tuple)

Output

True
False
True

2. Iterating Through a Tuple


We can use a for loop to iterate through each item in a tuple.

# Using a for loop to iterate through a tuple


for name in ('John', 'Kate'):
print("Hello", name)

Output

Hello John
Hello Kate

Advantages of Tuple over List


Since tuples are quite similar to lists, both of them are used in similar situations. However, there
are certain advantages of implementing a tuple over a list. Below listed are some of the main
advantages:
 We generally use tuples for heterogeneous (different) data types and lists for homogeneous
(similar) data types.
 Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight
performance boost.

10211CS213 - PYTHON PROGRAMMING Page 53


 Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is
not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it remains
write-protected.

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

Creating Python Sets


A set is created by placing all the items (elements) inside curly braces {}, separated by comma,
or by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float, tuple, string
etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

# Different types of sets in Python


# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


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

Output

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

Try the following examples as well.

# set cannot have duplicates


# Output: {1, 2, 3, 4}

10211CS213 - PYTHON PROGRAMMING Page 54


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

# we can make set from a list


# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

# set cannot have mutable items


# here [3, 4] is a mutable list
# this will cause an error.

my_set = {1, 2, [3, 4]}

Output

{1, 2, 3, 4}
{1, 2, 3}
Traceback (most recent call last):
File "<string>", line 15, in <module>
my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'

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.

# Distinguish set and dictionary while creating empty set

# initialize a with {}
a = {}

# check data type of a


print(type(a))

# initialize a with set()


a = set()

10211CS213 - PYTHON PROGRAMMING Page 55


# check data type of a
print(type(a))

Output

<class 'dict'>
<class 'set'>

Modifying a set in Python


Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does not
support it.
We can add a 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.

# initialize my_set
my_set = {1, 3}
print(my_set)

# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing

# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# add multiple elements


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

10211CS213 - PYTHON PROGRAMMING Page 56


# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)

Output

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

Removing elements from a set


A particular item can be removed from a set using the methods discard() and remove().
The only difference between the two is that the discard() function leaves a set unchanged if the
element is not present in the set. On the other hand, the remove() function will raise an error in
such a condition (if element is not present in the set).
The following example will illustrate this.

# Difference between discard() and remove()

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)

# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)

# discard an element

10211CS213 - PYTHON PROGRAMMING Page 57


# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)

# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError

my_set.remove(2)

Output

{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
{1, 3, 5}
Traceback (most recent call last):
File "<string>", line 28, in <module>
KeyError: 2

Similarly, we can remove and return an item using the pop() method.

Since set is an unordered data type, there is no way of determining which item will be popped. It
is completely arbitrary.
We can also remove all the items from a set using the clear() method.

# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)

# pop an element
# Output: random element
print(my_set.pop())

# pop another element

10211CS213 - PYTHON PROGRAMMING Page 58


my_set.pop()
print(my_set)

# clear my_set
# Output: set()
my_set.clear()
print(my_set)

print(my_set)

Output

{'H', 'l', 'r', 'W', 'o', 'd', 'e'}


H
{'r', 'W', 'o', 'd', 'e'}
set()

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.

>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}

Set Union

Set Union in Python

10211CS213 - PYTHON PROGRAMMING Page 59


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 union() method.

# Set union method


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

Output

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

Try the following examples on Python shell.

# use union function


>>> [Link](B)
{1, 2, 3, 4, 5, 6, 7, 8}

# use union function on B


>>> [Link](A)
{1, 2, 3, 4, 5, 6, 7, 8}

Set Intersection

Set Intersection in Python

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

10211CS213 - PYTHON PROGRAMMING Page 60


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

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

# use & operator


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

Output

{4, 5}

Try the following examples on Python shell.

# use intersection function on A


>>> [Link](B)
{4, 5}

# use intersection function on B


>>> [Link](A)
{4, 5}

Set Difference

Set Difference in Python

10211CS213 - PYTHON PROGRAMMING Page 61


Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A.
Difference is performed using - operator. Same can be accomplished using
the difference() method.

# Difference of two sets


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

Output

{1, 2, 3}

Try the following examples on Python shell.

# use difference function on A


>>> [Link](B)
{1, 2, 3}

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

# use difference function on B


>>> [Link](A)
{8, 6, 7}

10211CS213 - PYTHON PROGRAMMING Page 62


Set Symmetric Difference

Set Symmetric Difference in Python

Symmetric Difference of A and B is a set of elements in A and B but not in both (excluding the

intersection).
Symmetric difference is performed using ^ operator. Same can be accomplished using the
method symmetric_difference() .

# Symmetric difference of two sets


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

Output

{1, 2, 3, 6, 7, 8}

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)

10211CS213 - PYTHON PROGRAMMING Page 63


{1, 2, 3, 6, 7, 8}

Other Python Set Methods


There are many set methods, some of which we have already used above. Here is a list of all the
methods that are available with the set objects:
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member. (Do nothing if the
element is not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element. Raises KeyError if the
set is empty
remove() Removes an element from the set. If the element is not a member,
raises a KeyError
symmetric_difference() Returns the symmetric difference of two sets as a new set
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
union() Returns the union of sets in a new set
update() Updates the set with the union of itself and others

Other Set Operations


Set Membership Test
We can test if an item exists in a set or not, using the in keyword.

# in keyword in a set
# initialize my_set
my_set = set("apple")

# check if 'a' is present


# Output: True
print('a' in my_set)

10211CS213 - PYTHON PROGRAMMING Page 64


# check if 'p' is present
# Output: False
print('p' not in my_set)

Output

True
False

Iterating Through a Set


We can iterate through each item in a set using a for loop.

>>> for letter in set("apple"):


... print(letter)
...
a
p
e
l

Built-in Functions with Set


Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are

commonly used with sets to perform different tasks.


Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False .
enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as a
pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
sum() Returns the sum of all elements in the set.

10211CS213 - PYTHON PROGRAMMING Page 65


Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods
like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_differen
ce() and union() . Being immutable, it does not have methods that add or remove elements.

# Frozensets
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

Try these examples on Python shell.

>>> [Link](B)
False
>>> [Link](B)
frozenset({1, 2})
>>> A | B
frozenset({1, 2, 3, 4, 5, 6})
>>> [Link](3)
...
AttributeError: 'frozenset' object has no attribute 'add'

Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has
a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
An item has a key and a corresponding value that is expressed as a pair (key: value).
While the 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.

10211CS213 - PYTHON PROGRAMMING Page 66


# 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()
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 from above, we can also create a dictionary using the built-in dict() function.
Accessing Elements from Dictionary
While indexing is used with other data types to access values, a dictionary uses keys. Keys can
be used either inside square brackets [] or with the get() method.
If we use the square brackets [], KeyError is raised in case a key is not found in the dictionary.
On the other hand, the get() method returns None if the key is not found.

# get vs [] for retrieving elements


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


# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Output

Jack
26
None
Traceback (most recent call last):

10211CS213 - PYTHON PROGRAMMING Page 67


File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'

Changing and Adding Dictionary elements


Dictionaries are mutable. We can add new items or change the value of existing items using an
assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not present, a
new (key: value) pair is added to the dictionary.

# Changing and adding Dictionary Elements


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)

Output

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


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

Removing elements from Dictionary


We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from
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.

# Removing elements from a dictionary

# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# remove a particular item, returns its value


# Output: 16

10211CS213 - PYTHON PROGRAMMING Page 68


print([Link](4))

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


print(squares)

# remove an arbitrary item, return (key,value)


# Output: (5, 25)
print([Link]())

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

# remove all items


[Link]()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
print(squares)

Output

16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined

Python Dictionary Methods


Methods that are available with a dictionary are tabulated below. Some of them have already
been used in the above examples.
Method Description
clear() Removes all items from the dictionary.
copy() Returns a shallow copy of the dictionary.
fromkeys(seq[, Returns a new dictionary with keys from seq and value equal to v (defaults to
v]) None).
get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).

10211CS213 - PYTHON PROGRAMMING Page 69


items() Return a new object of the dictionary's items in (key, value) format.
keys() Returns a new object of the dictionary's keys.
pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is
not provided and the key is not found, it raises KeyError.
popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the
dictionary is empty.
setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the key
with a value of d and returns d (defaults to None).
update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing
keys.
values() Returns a new object of the dictionary's values

Here are a few example use cases of these methods.

# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)

# Output: {'English': 0, 'Math': 0, 'Science': 0}


print(marks)

for item in [Link]():


print(item)

# Output: ['English', 'Math', 'Science']


print(list(sorted([Link]())))

Output

{'Math': 0, 'English': 0, 'Science': 0}


('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']

Python Dictionary Comprehension


Dictionary comprehension is an elegant and concise way to create a new dictionary from an
iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by
a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.

# Dictionary Comprehension
squares = {x: x*x for x in range(6)}

print(squares)

10211CS213 - PYTHON PROGRAMMING Page 70


Output

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

This code is equivalent to

squares = {}
for x in range(6):
squares[x] = x*x
print(squares)

Output

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

A dictionary comprehension can optionally contain more for or if statements.


An optional if statement can filter out items to form the new dictionary.
Here are some examples to make a dictionary with only odd items.

# Dictionary Comprehension with if conditional


odd_squares = {x: x*x for x in range(11) if x % 2 == 1}

print(odd_squares)

Output

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

Other Dictionary Operations


Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in. Notice that the membership
test is only for the keys and not for the values .

# Membership Test for Dictionary Keys


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

# Output: True
print(1 in squares)

# Output: True
print(2 not in squares)

# membership tests for key only not value


# Output: False
print(49 in squares)

10211CS213 - PYTHON PROGRAMMING Page 71


Output

True
True
False

Iterating Through a Dictionary


We can iterate through each key in a dictionary using a for loop.

# Iterating through a Dictionary


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

Output

1
9
25
49
81

Dictionary Built-in Functions


Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with
dictionaries to perform different tasks.
Function Description
all() Return True if all keys of the dictionary are True (or if the dictionary is empty).
any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.
len() Return the length (the number of items) in the dictionary.
cmp() Compares items of two dictionaries. (Not available in Python 3)
sorted() Return a new sorted list of keys in the dictionary.
Here are some examples that use built-in functions to work with a dictionary.

# Dictionary Built-in Functions


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

# Output: False
print(all(squares))

# Output: True
print(any(squares))

# Output: 6
print(len(squares))

10211CS213 - PYTHON PROGRAMMING Page 72


# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))

Output

False
True
6
[0, 1, 3, 5, 7, 9]

Python Modules
What are modules in Python?
Modules refer to a file containing Python statements and definitions.
A file containing Python code, for example: [Link], is called a module, and its module
name would be example.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
Let us create a module. Type the following and save it as [Link].

# Python Module example

def add(a, b):


"""This program adds two
numbers and return the result"""

result = a + b
return result

Here, we have defined a function add() inside a module named example. The function takes in
two numbers and returns their sum.
How to import modules in Python?
We can import the definitions inside a module to another module or the interactive interpreter in
Python.
We use the import keyword to do this. To import our previously defined module example, we
type the following in the Python prompt.

>>> import example

This does not import the names of the functions defined in example directly in the current
symbol table. It only imports the module name example there.
Using the module name we can access the function using the dot . operator. For example:

10211CS213 - PYTHON PROGRAMMING Page 73


>>> [Link](4,5.5)
9.5

Standard modules can be imported the same way as we import our user-defined modules.
There are various ways to import modules. They are listed below..
Python import statement
We can import a module using the import statement and access the definitions inside it using the
dot operator as described above. Here is an example.

# import statement example


# to import standard module math

import math
print("The value of pi is", [Link])

When you run the program, the output will be:

The value of pi is 3.141592653589793

Import with renaming


We can import a module by renaming it as follows:

# import module by renaming it

import math as m
print("The value of pi is", [Link])

We have renamed the math module as m . This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, [Link] is invalid, and [Link] is
the correct implementation.
Python from...import statement
We can import specific names from a module without importing the module as a whole. Here is
an example.

# import only pi from math module

from math import pi


print("The value of pi is", pi)

Here, we imported only the pi attribute from the math module.


In such cases, we don't use the dot operator. We can also import multiple attributes as follows:

>>> from math import pi, e


>>> pi

10211CS213 - PYTHON PROGRAMMING Page 74


3.141592653589793
>>> e
2.718281828459045

Import all names


We can import all names(definitions) from a module using the following construct:

# import all names from the standard module math

from math import *


print("The value of pi is", pi)

Here, we have imported all the definitions from the math module. This includes all names visible
in our scope except those beginning with an underscore(private definitions).
Importing everything with the asterisk (*) symbol is not a good programming practice. This can
lead to duplicate definitions for an identifier. It also hampers the readability of our code.
Python Module Search Path
While importing a module, Python looks at several places. Interpreter first looks for a built-in
module. Then(if built-in module not found), Python looks into a list of directories defined
in [Link]. The search is in this order.
The current directory.
PYTHONPATH (an environment variable with a list of directories).
The installation-dependent default directory.

>>> import sys


>>> [Link]
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\[Link]',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

We can add and modify this list to add our own path.
Reloading a module
The Python interpreter imports a module only once during a session. This makes things more
efficient. Here is an example to show how this works.
Suppose we have the following code in a module named my_module .

# This module shows the effect of


# multiple imports and reload

print("This code got executed")

10211CS213 - PYTHON PROGRAMMING Page 75


Now we see the effect of multiple imports.

>>> import my_module


This code got executed
>>> import my_module
>>> import my_module

We can see that our code got executed only once. This goes to say that our module was imported
only once.
Now if our module changed during the course of the program, we would have to reload [Link]
way to do this is to restart the interpreter. But this does not help much.
Python provides a more efficient way of doing this. We can use the reload() function inside
the imp module to reload a module. We can do it in the following ways:

>>> import imp


>>> import my_module
This code got executed
>>> import my_module
>>> [Link](my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>

The dir() built-in function


We can use the dir() function to find out names that are defined inside a module.
For example, we have defined a function add() in the module example that we had in the
beginning.

We can use dir in example module in the following way:

>>> dir(example)
[' builtins ',
' cached ',
' doc ',
' file ',
' initializing ',
' loader ',
' name ',
' package ',
'add']

Here, we can see a sorted list of names (along with add). All other names that begin with an
underscore are default Python attributes associated with the module (not user-defined).
For example, the name attribute contains the name of the module.

>>> import example


>>> example. name

10211CS213 - PYTHON PROGRAMMING Page 76


'example'

All the names defined in our current namespace can be found out using the dir() function
without any arguments.

>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
[' builtins ', ' doc ', ' name ', 'a', 'b', 'math', 'pyscripter']

Python Package
What are packages?
We don't usually store all of our files on our computer in the same location. We use a well-
organized hierarchy of directories for easier access.
Similar files are kept in the same directory, for example, we may keep all the songs in the
"music" directory. Analogous to this, Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar modules
in one package and different modules in different packages. This makes a project (program) easy
to manage and conceptually clear.
Similarly, as a directory can contain subdirectories and files, a Python package can have sub-
packages and modules.
A directory must contain a file named init .py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
package in this file.
Here is an example. Suppose we are developing a game. One possible organization of packages
and modules could be as shown in the figure below.

Package Module Structure in Python Programming

10211CS213 - PYTHON PROGRAMMING Page 77


Importing module from a package
We can import modules from packages using the dot (.) operator.
For example, if we want to import the start module in the above example, it can be done as
follows:

import [Link]

Now, if this module contains a function named select_difficulty() , we must use the full name to
reference it.

[Link].select_difficulty(2)

If this construct seems lengthy, we can import the module without the package prefix as follows:

from [Link] import start

We can now call the function simply as follows:

start.select_difficulty(2)

Another way of importing just the required function (or class or variable) from a module within a
package would be as follows:

from [Link] import select_difficulty

Now we can directly call this function.

select_difficulty(2)

Although easier, this method is not recommended. Using the full namespace avoids confusion
and prevents two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in [Link], similar as
for module search path.

Python Functions
What is a function in Python?
In Python, a function is a group of related statements that performs 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 the code reusable.
Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)

10211CS213 - PYTHON PROGRAMMING Page 78


Above shown is a function definition that consists of the following components.
1. Keyword def that marks the start of the function header.
2. A function name to uniquely identify the function. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Example of a function

def greet(name):
"""
This function greets to
the person passed in as
a 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!

Try running the above code in the Python program with the function definition to see the output.

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

greet('Paul')

Note: In python, the function definition should always be present before the function call.
Otherwise, we will get an error. For example,

# function call
greet('Paul')

10211CS213 - PYTHON PROGRAMMING Page 79


# function definition
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

# Erro: name 'greet' is not defined

Docstrings
The first string after the function header is called the docstring and is short for documentation
string. It is briefly used to explain what a function does.
Although optional, documentation is a good programming practice. Unless you can remember
what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally
use triple quotes so that docstring can extend up to multiple lines. This string is available to us as
the doc attribute of the function.
For example:
Try running the following into the Python shell to see the output.

>>> print(greet. doc )

This function greets to


the person passed in as
a parameter

To learn more about docstrings in Python, visit Python Docstrings.


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 an expression that 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:

>>> print(greet("May"))
Hello, May. Good morning!

10211CS213 - PYTHON PROGRAMMING Page 80


None

Here, None is the returned value since greet() directly prints the name and no return statement is
used.
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

print(absolute_value(2))

print(absolute_value(-4))

Output

2
4

How Function works in Python?

Working of functions in Python

Scope and Lifetime of variables

10211CS213 - PYTHON PROGRAMMING Page 81


Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function are not visible from outside the function. Hence, they have a
local scope.
The lifetime of a variable is the period throughout which the variable exists 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.

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 affect 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 the same names, they are two different variables with different
scopes.
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.
Types of Functions
Basically, we can divide functions into the following two types:
Built-in functions - Functions that are built into Python.
User-defined functions - Functions defined by the users themselves.

Python User-defined Functions


What are user-defined functions in Python?
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.
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

10211CS213 - PYTHON PROGRAMMING Page 82


1. User-defined functions help to decompose a large program into small segments which makes
program easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those codes and execute
when needed by calling that function.
3. 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))

Output

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.
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 Built in Functions

Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii
characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object

10211CS213 - PYTHON PROGRAMMING Page 83


callable() Returns True if the specified object is callable, otherwise
False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be
executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from
the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and
methods
divmod() Returns the quotient and the remainder when argument1 is
divided by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an
enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or
method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified
attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a
specified object
issubclass() Returns True if a specified class is a subclass of a specified
object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol

10211CS213 - PYTHON PROGRAMMING Page 84


table
map() Returns the specified iterator with the specified function
applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified
character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and
increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the dict property of an object
zip() Returns an iterator, from two or more iterators

Python Function Arguments


Arguments
In the user-defined function topic, we learned about defining a function and calling it. Otherwise,
the function call will result in an error. Here is an example.

def greet(name, msg):


"""This function greets to

10211CS213 - PYTHON PROGRAMMING Page 85


the person with the provided message"""
print("Hello", name + ', ' + msg)

greet("Monica", "Good morning!")

Output

Hello Monica, Good morning!

Here, the function greet() has two parameters.


Since we have called this function with two arguments, it runs smoothly and we do not get any
error.
If we call it with a different number of arguments, the interpreter will show an error message.
Below is a call to this function with one and no arguments along with their respective error
messages.

>>> greet("Monica") # only one argument


TypeError: greet() missing 1 required positional argument: 'msg'
>>> greet() # no arguments
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'

Variable Function Arguments


Up until now, functions had a fixed number of arguments. In Python, there are other ways to
define a function that can take variable number of arguments.
Three different forms of this type are described below.
Python Default Arguments
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=). Here is an
example.

def greet(name, msg="Good morning!"):


"""
This function greets to
the person with the
provided message.

If the message is not provided,


it defaults to "Good
morning!"
"""

print("Hello", name + ', ' + msg)

10211CS213 - PYTHON PROGRAMMING Page 86


greet("Kate")
greet("Bruce", "How do you do?")

Output

Hello Kate, Good morning!


Hello Bruce, How do you do?

In this function, the parameter name does not have a default value and is required (mandatory)
during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional
during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if we
had defined the function header above as:

def greet(msg = "Good morning!", name):

We would get an error as:

SyntaxError: non-default argument follows default argument

Python Keyword Arguments


When we call a function with some values, these values get assigned to the arguments according
to their position.
For example, in the above function greet(), when we called it as greet("Bruce", "How do you
do?"), the value "Bruce" gets assigned to the argument name and similarly "How do you
do?" to msg.
Python allows functions to be called using keyword arguments. When we call functions in this
way, the order (position) of the arguments can be changed. Following calls to the above function
are all valid and produce the same result.

# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")

# 2 keyword arguments (out of order)


greet(msg = "How do you do?",name = "Bruce")

1 positional, 1 keyword argument


greet("Bruce", msg = "How do you do?")

As we can see, we can mix positional arguments with keyword arguments during a function call.
But we must keep in mind that keyword arguments must follow positional arguments.

10211CS213 - PYTHON PROGRAMMING Page 87


Having a positional argument after keyword arguments will result in errors. For example, the
function call as follows:

greet(name="Bruce","How do you do?")

Will result in an error:

SyntaxError: non-keyword arg after keyword arg

Python Arbitrary Arguments


Sometimes, we do not know in advance the number of arguments that will be passed into a
function. Python allows us to handle this kind of situation through function calls with an
arbitrary number of arguments.
In the function definition, we use an asterisk (*) before the parameter name to denote this kind of
argument. Here is an example.

def greet(*names):
"""This function greets all
the person in the names tuple."""

# names is a tuple with arguments


for name in names:
print("Hello", name)

greet("Monica", "Luke", "Steve", "John")

Output

Hello Monica
Hello Luke
Hello Steve
Hello John

Here, we have called the function with multiple arguments. These arguments get wrapped up into
a tuple before being passed into the function. Inside the function, we use a for loop to retrieve all
the arguments back.

Python Recursion
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors facing each other. Any object
in between them would be reflected recursively.
Python Recursive Function
In Python, we know that a function can call other functions. It is even possible for the function to
call itself. These types of construct are termed as recursive functions.

10211CS213 - PYTHON PROGRAMMING Page 88


The following image shows the working of a recursive function called recurse .

Recursive Function in Python


Following is an example of a recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Example of a recursive function

def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is ", factorial(num))

Output

The factorial of 3 is 6

In the above example, factorial() is a recursive function as it calls itself.


When we call this function with a positive integer, it will recursively call itself by decreasing the
number.
Each function multiplies the nu mber with the factorial of the number below it until it is equal to
one. This recursive call can be explained in the following steps.

factorial(3) # 1st call with 3


3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd d call
6 # return from 1st call

10211CS213 - PYTHON PROGRAMMING Page 89


Let's look at an image that shows a step-by-step process of what is going on:

Working of a recursive factorial function


Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting in
stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is crossed, it results
in RecursionError . Let's look at one such condition.

def recursor():
recursor()
recursor()

Output

Traceback (most recent call last):


File "<string>", line 3, in <module>
File "<string>", line 2, in a
File "<string>", line 2, in a

10211CS213 - PYTHON PROGRAMMING Page 90


File "<string>", line 2, in a
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.

Python Anonymous/Lambda Function


What are lambda functions in Python?
In Python, an anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword in Python, anonymous functions are
defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
How to use lambda Functions in Python?
A lambda function in python has the following syntax.
Syntax of Lambda Function in python

lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned. Lambda functions can be used wherever function objects are required.
Example of Lambda Function in python
Here is an example of lambda function that doubles the input value.

# Program to show the use of lambda functions


double = lambda x: x * 2

print(double(5))

Output

10

In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x *
2 is the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier double.
We can now call it as a normal function. The statement

10211CS213 - PYTHON PROGRAMMING Page 91


double = lambda x: x * 2

is nearly the same as:

def double(x):
return x * 2

Use of Lambda Function in python


We use lambda functions when we require a nameless function for a short period of time.
In Python, we generally use it as an argument to a higher-order function (a function that takes in
other functions as arguments). Lambda functions are used along with built-in functions
like filter(), map() etc.
Example use with filter()
The filter() function in Python takes in a function and a list as arguments.
The function is called with all the items in the list and a new list is returned which contains items
for which the function evaluates to True.
Here is an example use of filter() function to filter out only even numbers from a list.

# Program to filter out only the even items from a list


my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)

Output

[4, 6, 8, 12]

Example use with map()


The map() function in Python takes in a function and a list.
The function is called with all the items in the list and a new list is returned which contains items
returned by that function for each item.
Here is an example use of map() function to double all the items in a list.

# Program to double each item in a list using map()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

print(new_list)

Output

10211CS213 - PYTHON PROGRAMMING Page 92


[2, 10, 8, 12, 16, 22, 6, 24]

Python Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the
values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which
consist of the methods iter () and next ().
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you
can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
Example
Return an iterator from a tuple, and print each value:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))
Output:
apple
banana
cherry
Even strings are iterable objects, and can return an iterator:
Example
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
Output:
b
a
n
a

10211CS213 - PYTHON PROGRAMMING Page 93


n
a
Looping Through an Iterator
We can also use a for loop to iterate through an iterable object:
Example
Iterate the values of a tuple:
mytuple = ("apple", "banana", "cherry")

for x in mytuple:
print(x)
Output:
apple
banana
cherry
Example
Iterate the characters of a string:
mystr = "banana"

for x in mystr:
print(x)
Output:
b
a
n
a
n
a
The for loop actually creates an iterator object and executes the next() method for each loop.

Create an Iterator
To create an object/class as an iterator you have to implement the
methods iter () and next () to your object.
As you have learned in the Python Classes/Objects chapter, all classes have a function
called init (), which allows you to do some initializing when the object is being created.
The iter () method acts similar, you can do operations (initializing etc.), but must always
return the iterator object itself.
The next () method also allows you to do operations, and must return the next item in the
sequence.
Example
Create an iterator that returns numbers, starting with 1, and each sequence will increase by one
(returning 1,2,3,4,5 etc.):
class MyNumbers:
def iter (self):

10211CS213 - PYTHON PROGRAMMING Page 94


self.a = 1
return self

def next (self):


x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
output:
1
2
3
4
5
StopIteration
The example above would continue forever if you had enough next() statements, or if it was used
in a for loop.
To prevent the iteration to go on forever, we can use the StopIteration statement.
In the next () method, we can add a terminating condition to raise an error if the iteration is
done a specified number of times:
Example
Stop after 20 iterations:
class MyNumbers:
def iter (self):
self.a = 1
return self

def next (self):


if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

10211CS213 - PYTHON PROGRAMMING Page 95


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

10211CS213 - PYTHON PROGRAMMING Page 96

You might also like