Python Conditional Assignment Overview
Python Conditional Assignment Overview
Table of Contents
Module Title
1 INTRODUCTION TO PYTHON
History of Python
Key Features of Python
Real World Applications of Python
System Requirements for Installing of Python
Procedure to Install Python 3 on Windows OS
Script Mode Vs Interactive Mode
Interactive Mode Programming
Comments
Indentation
2 BASICS OF PYTHON
Python Character Set
Input( ) and Output( ) Functions
Tokens
Keywords
Identifiers
Literals
String Literals
Numeric Literals
Punctuators
Escape Sequence
Boolean Literals
3 OPERATORS
Operators
Types of Operators
Arithmetic Operators
Relational Operators or Comparitive Operators
Logical Operators
Assignment Operators
Conditional Operators
Identity Operators
Membership Operators
1
4 CONDITIONAL STATEMENTS
Conditional Statements
Simple if Statement
if..else Statements
if…elif…else
Short Hand if
5 LOOPING CONSTRUCTS
Looping Constructs
for Loop
range( ) Function
Using else statement with for loop
While loop
Using else statement with While Loop
6 NESTED LOOPS
Nested For Loops
break
continue
pass
7 PYTHON ARRAYS
Arrays
How to use array in a program
NumPy
Basic operations
Matrix Multiplication
8 PYTHON STRINGS
Strings
len( ), replace( ), del( ), upper( )
String Operators
Concatenation
String Repetition Operator
String Slicing
Sample Programs
Built-in String functions
2
9 PYTHON FUNCTIONS
Functions
Advantages of Functions
Types of Functions
User Defined Functions
Return Statement
Lambda Functions
Recursive Functions
Built-in Functions
10 PYTHON LISTS
Introduction to Lists
List methods in Python
Nested List
11 PYTHON TUPLES
Tuples
Pack Unpack
Tuples method
12 PYTHON SETS AND DICTIONARY
Sets
Set Operations
Dictionary – Key Value Pairs
13 PYTHON CLASSES AND OBJECTS
Classes and Objects
Creating Classes- Variables , Methods
14 PYTHON MODULES AND PACKAGES
Modules
Library
Important Packages
15 PYTHON DATE TIME MODULE
Date time module
Various date time format
3
MODULE 1
INTRODUCTION TO PYTHON
HISTORY OF PYTHON
5
SYSTEM REQUIREMENTS FOR INSTALLING PYTHON
Operating Systems and CPU architecture:
* Windows 7 or 10
* Mac OS X 10.11 or higher, 64-bit
* Linux: RHEL 6/7, 64-bit (almost all libraries also work in Ubuntu)
RAM and free disk space:
4 GB RAM
5 GB free disk space
Google colab
Colaboratory, or “Colab” for short, is a product from Google Research. Colab allows
anybody to write and execute arbitrary python code through the browser, and is especially
well suited to machine learning, data analysis and education.
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 feature
2. Visit [Link]
3. At the bottom locate Windows x86-64 executable installer for 64 bits OS and Windows
x86 executable installer for 32 bits OS
6
4. Click on the located installer file to download.
Note: After double clicking the installer, check mark the option “Add Python 3.6 to PATH”
5. After download completes, double click on the installer file to start the installation
procedure.
6. Follow the instructions as per the installer
7
SCRIPT MODE VS INTERACTIVE MODE
In Python, programs can be written in two ways namely Interactive mode and Script mode.
The Interactive mode allows us to write codes in Python command prompt (>>>) whereas in
script mode programs can be written and stored as separate file with the extension .py and
executed. Script mode is used to create and edit python source file. Programs written in
script mode can be used later.
[Link]
print("Hello, World!")
COMMENTS
The comments make the source code easy to understand. It can also be used to prevent
Python from executing code:
In Python, single line comments begin with hash symbol (#). The lines that begins with # are
considered as comments and ignored by the Python interpreter.
#This is a comment
print("Welcome to python")
The multiline comments should be enclosed within a set of ''' '''(triple quotes) which contains
more than one line
''' This is a comment
print("Welcome to python") '''
8
This will not be executed by Python Interpreter
INDENTATION
Python uses whitespace such as spaces and tabs to define program blocks whereas other
languages like C, C++, java use curly braces { } to indicate blocks of codes for class,
functions or body of the loops and block of selection command. The number of whitespaces
(spaces and tabs) in the indentation is not fixed, but all statements within the block must be
indented with same amount spaces.
9
MODULE 2
BASICS OF PYTHON
PYTHON CHARACTER SET
Character set is the set of valid characters that a language can recognize. A character
represents any letter, digit or any other symbol.
input( ) functions:
The syntax for input( ) function is,
Variable = input (“prompt string”)
Where prompt string is the message to the user
Sample code
10
Simple input( ) function without prompt is also available.
The input ( ) accepts all data as string or characters but not as numbers. If a numerical value
is entered, the input values should be explicitly converted into numeric data type. The int( )
function is used to convert string data as integer data explicitly.
s =int(input("Enter any number"))
Enter any number12
print( ) functions
To print or display output, Python provides print( ) function.
Sample code
Sample code
The sep parameter is primarily used to format the strings that need to be printed on the
console and add a separator between strings to be printed. This feature was newly introduced
in Python 3.x version.
11
print(10,20,30,sep='%')
output
10%20%30
The end parameter is primarily used to append any string at the end of the output of
the print statement in python.
print(100,200,300,end="$")
output
100 200 300$
TOKENS
A token is the smallest individual unit in a python program. All statements and instructions
in a program are built with tokens.
Python has the following tokens:
(i) Keyword
(ii) Identifiers
(iii) Literals
(iv) Operators and
(v) Punctuators
Keywords
Keywords are the reserved words in Python. We cannot use a keyword as a variable name,
function name or any other identifier. They are used to define the syntax and structure of the
Python language. In Python, keywords are case sensitive.
12
Few keywords are given below.
Identifiers :
An Identifier is a name used to identify a variable, function, class, module or object.
• An identifier must start with an alphabet (A..Z or a..z) or
underscore ( _ ).
• Identifiers may contain digits (0 .. 9)
• Python identifiers are case sensitive i.e. uppercase and lowercase letters are
distinct.
• Identifiers must not be a python keyword.
• Python does not allow punctuation character such as %,$, @ etc., within
identifiers.
LITERALS:
Literal is a raw data given to a variable or constant. In Python, there are various types of
literals
13
String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well
as double quotes to create a string.
Example:
“python programming…”
Numeric Literals:
Numeric literals can belong to 3 different numerical types
** Integer,
** Float and
** Complex Numbers
Sample code
# Program to demonstrate Numeric Literals
Execute it and give output
Punctuators
Punctuators are the symbols with specific [Link] are used in python to
organize the structures, statements and expressions.
Some of the Punctuators are: [ ] { } ( ) -= += *= //= **= /=
14
Escape Sequence
Python allows to have certain non-graphic characters in string values. Such characters cannot
be typed directly from keyboard. e.g. backspace, tabs, carriage return. These can be
represented by escape sequence. An escape sequence is represented by backslash followed
by one or more characters. Following are the list of escape sequence:
\” - Double quotes
\’ - Single quotes
\\ - Backslash
\b - Backspace
\n - New line
\r - Carriage return
\t - Horizontal tab
\v - Vertical tab
Boolean literals
Used to represent one of the two boolean values, that is True and False.
For example:
>>>bool=(6>10)
>>>print (bool)
False
15
MODULE 3
OPERATORS
OPERATORS
Operators are used to perform operations on variables and values.
TYPES OF OPERATORS
Various types of operators available in Python are
Arithmetic Operators
Relational or Comparative Operators
Logical Operators
Assignment Operators
Conditional Operators
Identity Operators
Membership Operators
Bitwise Operators
Precedence of Operators :
The precedence of operators determines which operator is executed first if there is
more than one operator in an expression.
Precedence:
P – Parentheses
E– Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
Arithmetic Operators :
Arithmetic Operators are used to perform mathematical calculations like addition,
subtraction, multiplications , divisions. Operator is the symbol for calculations and operand
is the value on which the operator acts.
16
Operator Description
- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative.
a = 30, b = 20
a - b = 10
/ (divide) It returns the quotient after dividing the first operand by the second
operand.
a = 40, b = 20
a/b = 2.0
% (remainder) It returns the remainder after dividing the first operand by the
Modulo second operand.
a = 200, b = 100
a%b = 0
//(Floor division) It gives the quotient produced by dividing the two operands.
Integer division
17
TRY IT YOURSELF
x = 15
y=3
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(x%y)
print(x//y)
print(x**y)
18
>Greater than:
returns True if the left operand is greater than the right
x> y
<Less than:
returns True if the left operand is less than the right
x< y
==Equal to:
returns True if both operands are equal
x == y
!=Not equal to
returns True if operands are not equal
x != y
19
print("x <= y:", x <= y)
print("x >= y:", x >= y
output
x == y: False
x != y: True
x < y: True
x > y: False
x <= y: True
x >= y: False
TRY IT YOURSELF
print(20.2 )
print(20.2 < 21.3)
print(20.2 >21.3< 22.4)
print(20.2 < 21.3 < 22.4 < 23.5)
Logical Operators
There are three logical operators that are used to compare values. They evaluate expressions
down to Boolean values, returning either True or False. These operators are and, or, and not
Operator What it means Example
and True if both are true x and y
or True if at least one is true x or y
not True only if false not x
20
Program code
x = 15
print(x > 3 and x < 20)
print(x > 3 or x < 4)
print(not(x > 3 and x < 20))
output
True
True
False
Assignment operator
In Python, = is a simple assignment operator to assign values to variable. There are various
compound operators in Python like +=, -=, *=, /=, %=, **= and //=
Operators Descriptions
21
Find output
#Demo Program to test Assignment Operators
CONDITIONAL OPERATORS
Ternary operator is also known as conditional operator that evaluate something based
on a condition being true or false. It simply allows testing a condition in a single line
replacing the multiline if-else making the code compact.
Syntax
Variable Name = [on_true] if [Test expression] else [on_false]
Code for finding maximum among 2 numbers using conditional operators
a=100
b=50
large=a if a>b else b
print(large)
output
100
22
IDENTITY OPERATORS
Identity operators compare the memory locations of two objects
is not Returns True if both variables are not the same object x is not y
PROGRAM CODE :
TRY IT YOURSELF
>>> a=b=3.1
>>> a is b
>>> id(a)
>>> id(b)
>>>c,d=3.1,3.1
>>> c is d
>>> id(c)
>>> id(d)
23
MEMBERSHIP OPERATORS
Membership operator is an operator which test for membership in a sequence, such as string,
list, tuple etc
Operator Description
not in Evaluate to true, if it does not find a variable in the specified sequence;
otherwise false
>>> 5 in [0,5,10,15]
True
>>> 6 in [0,5,10,15]
False
>>> 5 not in [0,5,10,15]
False
>>> 6 not in [0,5,10,15]
True
Find output
Sample code
vowels = ['A', 'E', 'I', 'O', 'U']
ch = input('Please Enter a Capital Letter:\n')
if ch in vowels:
print('You entered a vowel character')
else:
print('You entered a consonants character')
24
MODULE 4
CONDITIONAL STATEMENTS
CONDITIONAL STATEMENTS
Conditional Statement in Python perform different computations or actions depending on
whether a specific Boolean constraint evaluates to true or false. Conditional statements are
handled by IF statements in Python.
Decision making is the most important aspect of almost all the programming languages. As
the name implies, decision making allows us to run a particular block of code for a particular
decision
Conditional statements are handled by if statements in Python
Python provides the following types of alternative or branching statements:
• Simple if statement
• if..else statement
• if..elif statement
SIMPLE IF STATEMENT
It has a code body that only executes if the condition in the if statement is true. The
statement can be a single line or a block of code.
Syntax:
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the test
expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation
25
Sample Code :
num = 5
if num > 0:
print(num, "is a positive number.")
print("This statement is true.")
#When we run the program, the output will be:
5 is a positive number.
This statement is true.
if…else statement :
The if…else statement is used to test a specific condition. If the condition is true, a block of
code (if-block) will be executed and if it fails , another block of code will be executed.
Syntax :
if test expression:
statement1
else:
statement2
Sample code
num = 5
if num>= 0:
print("Positive ")
else:
print("Negative number")
output : Positive
26
if….elif….else
The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them.
We can have any number of elif statements in our program depending upon our need.
However, using elif is optional.
Syntax of if...elif...else
if test expression:
Body of if
Body of else
Sample Code :
print(maximum)
27
OUTPUT:
1st Number: 1
2nd Number: 2
3rd Number: 3
3.0
Short Hand if
If you have only one statement to execute, you can put it on the same line as the if
statement.
Example
if a > b: print("a is greater than b")
TRY IT YOURSELF
1. Write a program to check whether a person is eligible for voting or not. (accept age from
user)
2. Write a python program that inputs an integer in the range ( 0 – 999 ) and prints whether it
is a 1 or 2 or 3 digit number.
3. Write a program to display "Hello" if a number entered by user is a multiple of five ,
otherwise print "Bye".
28
MODULE 5
LOOPING CONSTRUCTS
LOOPING CONSTRUCTS
Loop executes set of statements repeatedly certain number of times.
Iteration or loop are used in situation when the user need to execute a block of
code several of times or till the condition is satisfied.
For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string). It is also an entry check loop.
Syntax 1
for iterating_var in sequence:
statement(s)
Syntax 2
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
sample code 1
str = "Python"
for i in str:
print(i)
29
Output:
P
y
t
h
o
n
range( ) function
The range() is an in-built function in Python.
The range() function is used to generate the sequence of the numbers. for loop uses the
range() function in the sequence to specify the initial, final and increment values.
range() generates a list of values starting from start till stop-1.
The syntax of range() is as follows:
range (start,stop,[step])
start: It’s an optional parameter used to define the starting point of the sequence.
By default, it’s zero.
stop: It’s a mandatory parameter, used to define the stopping point of the sequence
step: It’s also an optional parameter used to specify the incrementation on each
iteration; by default, the value is one.
By default, the range() function only allow integers as parameters. If you pass float value,
then it throws the following error:
sum(range(10))
output
45
sum(range(4))
output
6
for i in range(10,20,2):
print(i)
#OutPut
10
12
14
16
18
31
Sample code
for i in range(10):
print(i,end = ' ')
Output:
0123456789
Python allows us to use the else statement with the for loop which can be executed only
when all the iterations are exhausted. Here, we must notice that if the loop contains any of
the break statement then the else statement will not be executed. This feature is available
only in Python.
for i in range(0,3):
print(i)
else:
print("for loop completely exhausted")
Output:
While loop
We generally use this loop when we don't know the number of times to iterate beforehand.
while test_expression:
Body of while
32
In the while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked
again. This process continues until the test_expression evaluates to False.
Sample Code
i=1
while i< 6:
print(i)
i += 1
sample code
count =0
while count <5:
print count," is less than 5"
count = count +1
output
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
count =0
while count <5:
print count," is less than 5"
count = count +1
else:
print count," is not less than 5"
TRY IT YOURSELF
1. Write a program to count the occurence of even number and odd number between the
range 10 – 55.
34
MODULE 6
NESTED LOOPS
NESTED FOR LOOPS
Nested for loop is having one or more for loops inside another for loop
Sample code
# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Output:
TRY IT YOURSELF
35
break
The break is a keyword in python that is used to terminates the loop containing it. If break
statement is inside a nested loop (loop inside another loop), break will terminate the
innermost [Link] has to note an important point here is that ‘if a loop is left by break, the
else part is not executed’
Syntax
break
program code
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
output
Current Letter : P
Current Letter : y
Current Letter : t
continue
The continue statement, skips the current iteration and continues with the next iteration of
the loop:
syntax
continue
coding
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
36
output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
pass
pass statement in Python programming is a null statement. pass statement when executed by
the interpreter it is completely ignored. Nothing happens when pass is executed, it results in
no operation. pass statement can be used in ‘if ’ clause as well as within loop construct, when
you do not want any statements or commands within that block to be executed
The pass statement in Python is used when a statement is required syntactically but you do not
want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also
useful in places where your code will eventually go, but has not been written yet
pass statement is generally used as a placeholder. When we have a loop or function that is to
be implemented in the future and not now, we cannot develop such functions or loops with
empty body segment because the interpreter would raise an error. So, to avoid this we can
use pass statement to construct a body that does nothing.
Syntax:
Pass
Example
for letter in 'Python': # First Example
if letter == 'h':
pass
print ('Current Letter :', letter)
37
output
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Sample code
a=int (input(“Enter any number :”))
if (a==0):
pass
else:
print (“non zero value is accepted”)
Output:
Enter any number :3
non zero value is accepted
When the above code is executed if the input value is 0 (zero) then no action will be
performed, for all the other input values the output will be as per input
TRY IT YOURSELF
Write a python code to get the following output ( adds only positive number )
38
MODULE 7
PYTHON ARRAYS
ARRAYS
An array is defined as a collection of items of similar data type that are stored at contiguous
memory locations. Arrays in Python are Data Structures that can hold multiple values of the
same type.
Arrays are also mutable ( change ) and not fixed in size, which means they can grow and
shrink throughout the life of the program. Items can be added and removed, making them
very flexible to work with.
Accessing array elements in Python :
Each and every element in an array is given an index or subscript. To access array elements,
you need to specify the index values. Array Indexing starts at 0 .
a
12 13 14 15 15
0 1 2 3 4 n-1
Index
a[0]=12
a[1]=13
39
How to use array in a program
By using import array at the top of the file to include the module array. You would then go
on to create an array using [Link]( )
import array
[Link]( )
you can also use from array import * ( * means importing all the functionalities) and then
create an array by writing the array( ) constructor alone.
from array import *
array( )
NumPy
NumPy is a special Python library with a large collection of high-level mathematical
functions to operate on arrays. It also has functions for working with statistical calculations,
linear algebra, fourier transform, and matrices.
Basic operations
Example
Get the first element from the following array:
import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr[0])
output as single element
1
40
output in array form
[ 9 11]
Sample code
import numpy as np
a = [Link]([1, 2, 3, 6])
print(a**2)
output
[1, 4, 9, 36]
import numpy as np
[Link](1)
0.8414709848078965
The value of sin 1 is 0.8414709848, in radian
import numpy as np
a = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print([Link]())
output
[[1 4 7]
[2 5 8]
[3 6 9]]
41
Corresponding Output
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
Matrix Multiplication
Given 2 numpy arrays as matrices, output the result of multiplying the 2 matrices (as a
numpy array)
import numpy as np
a = [Link]([[1,2,3],
[4,5,6],
[7,8,9]])
42
b = [Link]([[2,3,4],
[5,6,7],
[8,9,10]])
o = [Link](a, b)
print(o)
output
[[ 36 42 48]
[ 81 96 111]
[126 150 174]]
43
MODULE 8
PYTHON STRINGS
STRINGS
Strings are sequence of characters enclosed in single quotes or in double quotes.
String is a datatype in python. String is an array of characters.
Examples
'Welcome to Python' # string in single quotes
" Welcome to Python" # string in double quotes
''' Welcome to Python''' # string in triple quotes
""" Welcome to Python""" # string in triple double-quotes
Positive 0 1 2 3 4 5 index
P Y T H O N
Negative -6 -5 -4 -3 -2 -1 index
if you want a string to have a single quote as a part of a string ,then it should be given in
double quotes.
44
output
Welcome to "Python " strings
len( )
len( ) function is used to find the length of a string.
str='Python'
print(len(str))
6
replace( )
replace( ) function is used to change all occurrences of a particular character in a string
Sample code
str='Python'
print([Link]('t','a'))
Pyahon
del( )
del( ) function deletes the string
Sample code
del str
print(str)
NameError : name ‘str’ is not defined
upper( )
upper( ) function returns the strings in upper case letters
45
Sample code
str='Python'
print([Link]())
PYTHON
String Operators
Concatenation ( + )
Two or more Strings can be joined using ‘+’ operators in python
Sample code
str1='Python'
str2=' Programming'
print(str1+str2)
output
Python Programming
Sample code
str= "Python "
print(str*1)
print(str*2)
print(str*3)
print(str*4)
46
output
Python
Python Python
Python Python Python
Python Python Python Python
String Slicing
To make substring from the original string.
Sample code
str= "Python "
print(str)
Python
Sample code
str= "Python "
print(str[:])
Python
47
#printing characters 0 to 3
Sample code
str= "Python "
print(str[:4])
Pyth
# characters 2,3
Sample code
str= "Python "
print(str[2:4])
th
# characters 2 to end
Sample code
str= "Python "
print(str[2:])
thon
Pto
48
#skip 2 characters and printing 3rd character
Sample code
str= "Python "
print(str[::3])
output
Ph
49
rstrip( ) - removes spaces from right of the string
TRY IT YOURSELF
50
MODULE 9
PYTHON FUNCTIONS
FUNCTIONS
Functions are the blocks of code that accomplish a single task. Each and every function will
have a name and will be called whenever needed. Functions enable the programmers to
break down a problem into smaller components.
ADVANTAGES OF FUNCTIONS
Reusability of Code
Code Sharing
TYPES OF FUNCTIONS
Functions are classified as
User defined functions
Lambda functions
Recursive functions
Built-in Functions
SYNTAX
def functionname :
block of code
return
51
Sample code
def sum(a, b):
return (a + b)
a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
# f is format for output
print(f'Sum of {a} and {b} is {sum(a, b)}')
output
Enter 1st number:
12
Enter 2nd number:
22
Sum of 12 and 22 is 34
Here in this example , a and b are called parameters through which the values are passed to
the functions. Name of the function is sum. The function sum is called from the print
function in the main program
RETURN STATEMENT
The Python return keyword exits a function and instructs Python to continue executing the
main program. The return keyword can send a value back to the main program.
LAMBDA FUNCTIONS
Lambda functions are also called as anonymous functions. These function are defined
without a name. Lambda functions are defined with the keyword lambda. Lambda functions
are used for creating small and one time anonymous functions. Lambda functions can take
any number of arguments and must return one value.
52
Sample code
cube = lambda a: a*a*a
print(cube(10))
output
1000
RECURSIVE FUNCTIONS
A recursive function is a function that calls itself during its execution. The process may
repeat several times. It calls itself over and over again until a base condition is met that
breaks the loop.
Why recursion?
Recursion is made for solving problems that can be broken down into smaller, repetitive
problems. It is especially good for working on things that have many possible branches and
are too complex for an iterative approach .
Sample code
Finding factorial
def rec_fact(n):
if n == 1:
return n
else:
return n*rec_fact(n-1) #function calling itself
#taking input from the user
n = int(input("Enter any number : "))
print("The factorial of", n, "is", rec_fact(n))
53
output
Enter any number :
5
The factorial of 5 is 120
Built-in Functions
A built-in function is a function that is already available in a programming language,
application, or another tool that can be accessed by end users.
54
abs()
ascii()
bin()
bool()
55
MODULE 10
PYTHON LISTS
INTRODUCTION TO LISTS
List is a data type used in python for storing multiple items of different or same data type in
a single variable. Some popular languages that include list comprehension are JavaScript,
Perl 6, C# and Python.
Example :
Num=[12,13,15]
Sample code
List elements are mutable which means list contents can be changed.
List also has index value like arrays. In python , index value is an integer number which can
be positive or negative.
56
List=[ ]
# list of lists
List=[[11,22],[33,44,55]]
Sample code
# same value repeatedly
list = [3]* 5
print(list)
output
[3, 3, 3, 3, 3]
List Traversal
Each element in a list can be accessed using its index in square brackets. The list elements
can be accessed using loops using positive or negative index.
Sample code
weight=[22.5,66,45.5,34.5]
for x in weight:
print(x)
57
output
22.5
66
45.5
34.5
Method Description
range( ) Returns an iterator of integers from start to stop, with an increment of step.
Sample code
square=[a**2 for a in range(1,10)]
print(square)
output
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Why 100 not printed ?
58
sum( ) Adds all items of an iterable.
Sample code
print(sum([19,3,2,5,1,-9]))
21
Sample code
print(min([19,3,2,5,1,-9]))
-9
Sample code
print(max([19,3,2,5,1,-9]))
19
Sample code
name=['Hari','Booshan','Charu','Shami','Varshini','Ashwin']
[Link](reverse=True)
print(name)
output
['Varshini', 'Shami', 'Hari', 'Charu', 'Booshan', 'Ashwin']
Sample code
# prg to Add 2 to each item of the list
>>> l1 = [6,4,8,9,2,3,6]
>>> list(map(lambda x: x+2, l1))
[8, 6, 10, 11, 4, 5, 8]
In the example above, we used lambda expressions to add 2 to each item and we
used the Python list() function to create a list from the iterator returned by the
map() function.
Nested list:
A list having one or more sub-lists is called a nested list.
One of the big advantages of list comprehension is that they allow developers to write less
code that is often easier to understand.
List comprehension is usually faster.
Program
1. Write a program in Python to remove duplicate items from a list.
60
MODULE 11
PYTHON TUPLES
TUPLES
Tuples are collection of objects which are ordered and immutable
(unchangeable which means we cannot change the elements of a tuple once
assigned.). Tuples are used to store multiple items in a single variable.
A tuple is one of the four inbuilt data types used to store collections in Python. .
Tuples are sequences, just like lists.
Tuples Vs Lists
1. The elements of a list are mutable whereas the elements of a tuple are
immutable.
2. Iterating over the elements of a tuple is faster compared to iterating over a list.
To create a tuple in Python, place all the elements in a ( ) parenthesis, separated by commas.
A tuple can have heterogeneous data items, a tuple can have string and list as data items as
well.
# empty tuple
tup = ( )
61
Sample code
#creating tuples of similar data type
Tup=( 1,2,3,4,5 )
print(Tup)
output
(1, 2, 3, 4, 5)
Sample code
#creating tuples of different data types
Tup=(6,’hari’,19)
print(Tup)
Sample code
#tuples of tuples
Tup=( (1,2),(3,4),(5,6))
print(Tup)
output
((1, 2), (3, 4), (5, 6))
Sample code
# tuple of lists
Tup=( [1,2],[3,4],[5,6,7])
print(Tup)
output
([1, 2], [3, 4], [5, 6, 7])
62
Sample code
# tuple of tuples,lists,strings
Tup=( (1,2),[3,4],'hari')
print(Tup)
output
((1, 2), [3, 4], 'hari')
index 0 1 2 3 4 5
Mango Orange Grapes Apple Guava Banana
-6 -5 -4 -3 -2 -1
tup=( ‘Mango’,’Orange’,’Grapes’,’Apple’,’Guava’,’Banana’)
Pack Unpack
In packing, we place value into a new tuple while in unpacking we extract those values back
into variables.
If we talk of packing in literal terms, Just like we pack certain items into a box in the real
world. In python we pack certain variables in a single iterable.
Unpacking a tuple means splitting the tuple's elements into individual variables. For
example: x, y = (1, 2)
63
Sample code
x = ("HARI", 100, "CS") # tuple packing
(NAME, MARKS, SUBJECT) = x # tuple unpacking
print(NAME)
print(MARKS)
print(SUBJECT)
Output
HARI
100
CS
Delete
To delete an entire tuple, the del command is used.
Syntax :
del tuple_name
Example
del tup
After deleting tuple, if you try to print the tuple, python will show name error
Slicing
A slice is a substring of the main string. A substring can be taken from the
original string by using [ ] operator and index or subscript values. Thus, [ ] is
also known as the slicing operator. Using the slice operator, we can slice one or
more substrings from the main string.
64
Sample code
tup = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(tup)
Program
[Link] a program to swap two values using tuple assignment.
65
MODULE 12
PYTHON SETS AND DICTIONARY
SETS
Set is an unordered ( it will be displayed in random order ) and unindexed ( no
indexing for set elements ) collection of items in Python. The elements of a set
are defined inside curly brackets and are separated by commas. Each element in
the set must be unique ( duplicates not allowed ), immutable ( unchangeable
which means we cannot change the elements )
set( ) function is used to create sets in python.
For example –
Set1 = {1, 2, 3, "welcome"}
Set operations
The major set operations are
union
intersection
difference
symmetric difference
Union( )
In python , use union( ) or | operator function to combine all elements from two
or more sets
Method 1: [Link](mySet2)
Method 2: mySet1 | mySet2
intersection( )
In python, use intersection( ) function or & operator to have common elements
in both the sets.
Method 1: [Link](mySet2)
Method 2: mySet1 & mySet2
66
difference( )
The difference( ) functions or minus- operator is used to list the elements in the
first and not in second.
Method 1: [Link](mySet2)
Method 2: mySet1 - mySet2
symmetric difference( )
The symmetric difference( ) function or caret operator is used to list all the
elements in 2 sets and ( removing common elements ) not the elements in both.
Method 1: mySet1.symmetric_difference(mySet2)
Method 2: mySet1 ^ mySet2
Sample code
dict={' maths': 100, 'science': 100, 'computer': 100}
print(dict)
output
{' maths': 100, 'science': 100, 'computer': 100}
Sample code
# to display keys
dict={'maths': 100, 'science': 100, 'computer': 100}
print([Link]())
output
dict_keys(['maths', 'science', 'computer'])
68
Sample code
#dictionary sample code
sub=('maths','science','computer')
centum=100
dict1 = [Link](sub,centum)
print(dict1)
#output
{'maths': 100, 'science': 100, 'computer': 100}
69
MODULE 13
PYTHON CLASSES AND OBJECTS
Creating classes
Python class simply behaves as a template to create objects. Python class is simply an entity.
The class keyword is used for creating a class. Constructor is a special function used to
initialize the class variables. Constructor function will be automatically executed when an
object is created.
In Python, Constructor is created by a special function called “init”. It starts and ends with
double underscore symbol.
The self is used to represent the instance of the class. With this keyword, you
can access the attributes and methods of the class in python. It binds the
attributes with the given arguments.
Variables of class
The class variables are called as class objects. The class variables are accessed
using dot operator. A Python class variable is shared by all object instances of a
class. Class variables are declared when a class is being constructed.
70
Public scope :
The class variables are public by default. These variables can be accessed
anywhere in the program.
Private scope :
A variable prefixed with double underscore is a private variable. These
variables can be accessed only within the class.
Methods of a class
Functions of the class are called as Methods.
Sample code
class student:
id = 10
name = "Hari"
def display (self):
print([Link],[Link])
Here, the self is used as a reference variable, which refers to the current class
object. It is always the first argument in the function definition. However, using
self is optional in the function call.
Sample code
#class name student
class student:
RollNo = 1 # class variables
name = "Hari"
def display (self): #method display
print("RollNo: %d \nName: %s"%([Link],[Link]))
# Creating a instance of class
stu=student()
[Link]() #accessing class function using dot operator
71
output
RollNo: 1
Name: Hari
Try it yourself
[Link] a Python program using class to find area of a rectangle.
72
MODULE 14
14 PYTHON MODULES AND PACKAGES
MODULES IN PYTHON
Already we have learnt about functions in Python. Consider, if we are using the same
function in different programs, we have to define it again and again so many times which is
not that much easy . That is time consuming also. We can just create a code or a script
containing that function and save it as a file with a name and import that script in every
program that makes use of that function. These scripts are called modules in Python.
The module is a simple Python file that can contain (Python functions, python variables,
python classes). In Python, modules are used to divide the code into smaller parts. In this, we
can group similar data which makes the program easier to understand.
PACKAGES
There are more than 200,000 Python packages in the world. Python Modules are
grouped as Packages. Already in previous MODULEs, we discussed about the
most important packages numpy.
73
LIBRARY
It is a collection of modules. (Library either contains built in modules (written
in C) + modules written in python)
Example min( ) , max( ), sum( )
Scikit-learn (Sklearn) is the most useful and robust library for machine learning in
Python. It provides a selection of efficient tools for machine learning and statistical
modeling including classification, regression, clustering and dimensionality reduction
via a consistence interface in Python.
Matplotlib is the most common data exploration and visualization library. You can
use it to create basic graphs like line plots, histograms, scatter plots, bar charts, and pie
charts. You can also create animated and interactive visualizations with this library.
Matplotlib is the foundation of every other visualization library.
The library offers a great deal of flexibility with regards to formatting and styling
plots. You can freely choose how to display labels, grids, legends, etc.
Pillow
74
If you work with image data, make sure to check out the Pillow package. It is a fork of
PIL (Python Image Library) that developed into an easy-to-use and efficient tool for
image manipulation in Python.
This is a great image manipulation tool for beginners, and it has fairly powerful image
processing capabilities.
pytest
This package provides a variety of modules for testing new code,
including small unit tests and complex functional tests for applications
and libraries.
75
MODULE 15
PYTHON DATE TIME MODULE
Date time module
The datetime module supplies classes for manipulating dates and times.
The datetime module exports the following constants:
[Link]
The smallest year number allowed in a date or datetime object.
MINYEAR is 1.
[Link]
The largest year number allowed in a date or datetime object.
MAXYEAR is 9999.
date Objects
A date object represents a date (year, month and day) in an idealized calendar,
the current Gregorian calendar indefinitely extended in both directions.
January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and
so on. 2
classmethod [Link]()
Return the current local date.
Sample code
import datetime
x = [Link]()
print(x)
output
2022-06-29 05:48:16.129384
The date contains year, month, day, hour, minute, second, and microsecond.
The method is called strftime(), and takes one parameter, format, to specify the
format of the returned string:
Sample code
#program to return the year and name of weekday:
import datetime
x = [Link]()
print([Link])
print([Link]("%A"))
output
77
2022
Wednesday
Sample code
import datetime
x = [Link]()
print([Link]("%p"))
output
AM
Sample code
import datetime
x = [Link]()
print([Link]("%B"))
OUTPUT
June
Sample code
import datetime
x = [Link]()
print([Link]("%j"))
output
180
Sample code
import datetime
x = [Link]()
print([Link]("%G"))
79
output
2022
80