SP Unit-1 Complete Python Notes
SP Unit-1 Complete Python Notes
VAMSHI KRISHNA
UNIT-1
INTRODUCTION TO PYTHON PROGRAMMING
Python is a general purpose high level programming language.
Python was developed by Guido Van Rossam in 1991.
Currently we are using Python 3 version.
The name for the language was inspired by the BBC TV show Monty Python’s Flying Circus.
Basic Syntax
Syntax refers to set of rules to write a statements in a programming language.
In python we don’t need to specify the datatype name before a variable_name.
Python uses indentation (tabs or spaces) for code blocks (if block, else block, function block
etc).
Python is a case sensitive language. That means if we define a=10 which is different from
A=10. Python consider them as different variables.
All the conditional statements and class definition statements in python ends with colon ( :
) symbol. The colon symbol represents the start of new block.
Python provides several inbuilt keywords, we cannot use keywords for naming any of
variables, functions or classes etc.
Variables
A variable is a name that refers to a value. An assignment statement creates new variables and
gives them values.
Syntax: variable_name = value
Example:
n=10
section='CSE-C'
percentage=90.55
To display the value of a variable, you can use a print statement:
print(n)
10
print(section)
CSE-C
print(percentage)
90.55
1
KMEC/II/SP/Unit-1 [Link] KRISHNA
Keywords in Python
The Python interpreter uses keywords to recognize the structure of the program, and they
cannot be used as variable names.
2
KMEC/II/SP/Unit-1 [Link] KRISHNA
Types of operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
Arithmetic operators
Arithmetic operators are used for performing mathematical calculations.
Relational operators
Relational operators also called as comparison operators.
They are used to compare values and return a either True or False value based on the
comparison.
3
KMEC/II/SP/Unit-1 [Link] KRISHNA
Logical Operators
Logical operators are used to combine logical expressions and evaluate complex conditions.
There are three main logical operators: and, or and not.
and : It returns True only if all expressions are true. Otherwise, it returns False.
Example: a=10 b=20 c=15
a>b and a<c False and True returns False
a<b and a<c True and True returns True
or : It returns True if atleast one of the expressions is true. Returns False only if all expressions
are false.
a>b and a<c False or True returns True
a>b and a>c False or False returns False
not : used to negate a logical expression. It reverses the value of the expression. If the
expression is True, the not operator returns False. If the expression is False, the not operator
returns True
Example: not True False
not False True
Bitwise operators
Bitwise operations performed on integer values. First the integer value will be converted
integers into binary value and then apply bitwise operators on each bit of a binary value. Finally
we get the output result in the form of integer only.
There are 6 bitwise operators in python:
4
KMEC/II/SP/Unit-1 [Link] KRISHNA
Assignment Operators
The assignment operator (=) is used to assign value to the variable.
Example: a=10
The following is the list of all possible compound assignment operators in Python
+= -= *= /= %= //= **= &= |= ^=
Python allows multiple values are assigned to multiple variables in a single statement.
Example : a,b=10,20
Where a=10 and b=20.
Ternary operator
The ternary operator in Python allows us to perform conditional checks and assign values or
perform operations on a single line.
Syntax: Variable = Value1 if condition else Value2
If condition is True then Value1 will be assigned to variable else Value2 will be assigned to
the variable.
Example: max= a if a>b else b.
Special operators
The following are special operators: is, is not, in , not in.
Example:2
a=10
b=20
print(a is not b) # The variables a and b are not poiting to same value object
output: True
Example_1 : s='Python'
print('y' in s)
output: True
5
KMEC/II/SP/Unit-1 [Link] KRISHNA
Example_2: s='Python'
print('a' not in s)
output: True
print(s)
output: Python Programming
Python allows us to pass a string to input to be displayed to the user before pause for the input
from keyboard. We can also add new line (\n) character in the input().
Example:
name=input('Enter your name')
vamshi
print(name)
vamshi
String is the default datatype of input() function, so if we want to take an integer value as input,
then we have to use int() to convert to integer from string.
Example:
number = int(input('Enter an integer:'))
Enter an integer:5
print(number)
5
Output statement: print()
print() is a function that is used to display the output on the console.
Case_1: print() without any arguments.
print() without any argument, just prints the new line character.
Example: print('Python Programming')
output: Python Programming
print('Python \nProgramming')
output: Python
Programming
6
KMEC/II/SP/Unit-1 [Link] KRISHNA
Datatypes
In python we don’t need to specify the type explicitly.
Python will automatically assign the type after we assign a value to the variable.
The following datatypes are supported by python:
int, float, bool, complex, str, range, list, tuple, set, dict, bytes, bytearray, frozenset, None.
Note: type( variable_name ) is an inbuilt function that can display the what type of datatype
the variable belongs to.
7
KMEC/II/SP/Unit-1 [Link] KRISHNA
type(x)
<class 'bool'>
c=10<20
print(c)
False
Ex: s='Python'
s="Python"
type(s)
<class 'str'>
'' and " " are used to represent only single line strings.
For multi line string we need to use Triple quotes ( ''' ... ''')
Ex: s='''Python is a high level
programming language'''
A single character can also treated as str type.
Ex: ch='a'
type(ch)
<class 'str'>
8
KMEC/II/SP/Unit-1 [Link] KRISHNA
[Link]
10
[Link]
5
9
KMEC/II/SP/Unit-1 [Link] KRISHNA
print(s1)
Output: {10,20,'a',False}
type(s1)
<class ‘set’>
An empty set can be created by using the s=set().
Features of set:
1. Set is mutable. We can add and delete elements in the set.
2. Set consists heterogeneous objects are allowed.
3. Set does not contain duplicate elements.
4. Set doesn't use indexing.
Features of dictionary:
1. Dictionary is mutable. We can add and delete elements in the dictionary.
2. Dictionary consists heterogeneous objects are allowed.
3. Duplicate keys are not allowed but values can be duplicated.
4. If we are trying to insert an entry with duplicate key then old value will be replaced with
new value.
10
KMEC/II/SP/Unit-1 [Link] KRISHNA
Conditional statements
The conditional statement in python ends with colon (:) symbol.
if statement
if is a conditional statement that ends with colon (:) symbol.
Syntax:
if condition:
#statements
/#statements
If the condition is true then statements inside if are executed.
Example: if a>0:
print(“Positive integer”)
if else statement:
If there are only two choices then we go for if else construct.
If condition is true then the corresponding statements of if will be executed, otherwise else part
statements are executed.
Both if and else statements end with colon(:).
Syntax:
if condition :
#statement_if
else :
#statement_else
Example:
a=10
b=20
if a>b:
print("max=",a)
else:
print("max=",b)
if-elif-else statement:
If there are more than two choices then we go for if elif else construct.
All the statements of if , elif and else statements are ends with colon (:) symbol.
Syntax:
if conditon:
#if_statements
elif condition:
11
KMEC/II/SP/Unit-1 [Link] KRISHNA
#elif statements
else:
#else statements
Example:
a,b,c=10,20,30
if a>b and a>c:
print("max=",a)
elif b>c :
print("max=",b)
else:
print("max=",c)
Loops
Loops are iterative statements or repetitive statements. If we want to repeat statements
multiple time then we use loops.
Python supports for loop and while loop.
for loop
The statement of for loop in python ends with colon( : ).
Syntax:
for i in iterable:
#statements
The iterable may be a sequence data or any collection such list, tuple, string etc.
The statements inside the for loop is executed for every element present in the sequence.
12
KMEC/II/SP/Unit-1 [Link] KRISHNA
while loop
If we want to execute a group of statements iteratively until some condition false,then we
should go for while loop.
Syntax:
while condition :
#statements
If the condition is true the statements inside of while are executed.
If the condition is false, then the loop will be terminated.
Example_1: Program for printing for 5 natural numbers
i=1
while i<=5:
print(i, end= ' ')
i=i+1
output: 1 2 3 4 5
Nested loops
A loop within a loop is called nested loop.
Example_1: Program to print the following pattern.
1
12
123
1234
12345
for line in range(1,6,1):
for num in range(1,line+1,1):
13
KMEC/II/SP/Unit-1 [Link] KRISHNA
print(num,end='')
print()
Infinite loops
An infinite loop in Python is a loop that continues to execute indefinitely.
Syntax:
while True:
#statements
The condition True always evaluates to true, causing the loop to run forever.
Example_1:
while True:
print('Python')
The above code print Python for infinite number of times. The loop will never terminate.
Purpose of using infinite loops:
We can terminate the infinite loops by using "break" statement.
break statement
The break statement enables to exit from a loop.
We can use break statement inside loops to break loop execution based on some condition.
Example_1: Write a python program to take an integer from user input() untill it receives a
negative integer.
while True:
n=int(input("Enter an integer:"))
if n<0:
print("Loop exited")
break
else:
print(n)
output:
Enter an integer:1
1
Enter an integer:5
5
Enter an integer:-3
Loop exited
The above program executed continuously for all positive numbersm, but when we give input
as negative number then the loop terminated.
So when we dont know how many number of time the loop will be executed and the loop
termination depends on some value, then we go for infinite loops.
14
KMEC/II/SP/Unit-1 [Link] KRISHNA
continue statement
The continue statement essentially returns to the top of the loop and continues with the next
value of the loop variable.
We can use continue statement to skip current iteration and continue next iteration.
Example_1: Write a program to print odd numbers.
for i in range(10):
if i%2==0:
continue
print(i, end=' ')
output: 1 3 5 7 9
The code will be skipped for all the even values of i.
Functions
A function is a block of code in a program.
A function is a named sequence of statements that performs a computation.
When you define a function, you specify the name and the sequence of statements.
The main advantage of functions is code Reusability.
A function “takes” an argument or parameters and “returns” a result. The result is called
the return value.
The parameters and return values are optional in function.
Python supports 2 types of functions:
1. Built in Functions
2. User Defined Functions
Built in Functions
Python provides a number of important built-in functions that we can use without needing
to provide the function definition.
These functions are used to solve common problems and included them in Python for
programmers to use.
Ex: len(), id(), input(), print(), eval() etc.
len():
len() takes one object (iterator) as parameter, and returns the total number of elements in
that object or iterator.
That means, len() returns a numeric value that denotes the number of items in the given list,
tuple, array, dictionary, etc.
In case of string, it returns the total numbers of characters.
Example_1: s='Python'
len(s)
6
Example_2: l=[10,20,30,40]
len(l)
4
15
KMEC/II/SP/Unit-1 [Link] KRISHNA
type()
It is used to return the type of a variable.
Syntax: type(variable_name)
Example: a=10
type(a)
<class 'int'>
id()
It is used to get the address of the object.
Syntax: id(variable_name)
Example: a=10
id(a)
140710595070680
USER-DEFINED FUNCTIONS
Apart from built_in functions python allows us to add user defined functions also.
The functions which are written by programmers are called User defined functions.
16
KMEC/II/SP/Unit-1 [Link] KRISHNA
Example_1: write a program that prints first 5 natural numbers without passing parameters
and return statement.
def natural():
for i in range(1,6,1):
print(i,end=' ')
natural()
output: 1 2 3 4 5
Example_2: write a program that prints prints the reverse of a given number by passing
parameters and using a return statement.
n=int(input("Enter integer:"))
def reverse(n):
rev=0
while n!=0:
rem=n%10
rev=rev*10+rem
n=n//10
return rev
r=reverse(n)
print("Reverse=",r)
Note_1: we can directly use reverse(n) in print statement directly, so the return value is
replaced with reverse(n) function.
Ex: print("Reverse=",reverse(n))
Example_2:
def fun2(book="Python"):
print(book,"Programming")
fun2()
output: Python Programming
Note:
1. If we don't pass any value as parameter to fun2() then only default value will be considered.
2. If we pass any value as parameter then the default value will be replaced.
17
KMEC/II/SP/Unit-1 [Link] KRISHNA
Example: fun2("Java")
output: Java Programming
3. The default will be passed as the last arguments. You cannot pass the normal parameters
after default parameters.
output: Sum: 0
Sum: 30
Sum: 60
pass statement
pass is a keyword in python.
pass essentially does nothing.
18
KMEC/II/SP/Unit-1 [Link] KRISHNA
In python we want to write a function with no statement in it, then we write pass statement
inside the function.
Types of variables
Python supports 2 types of variables: Local variables, Global variables
Local variable:
A variable is local to a function if it is:
a parameter of the function
declared inside a function
bound to a control structure (such as for, with, and except)
Local variables are available only for the function in which we declared it. That means a local
variable of one function cannot be accessed by other function.
def f1():
a=10
print(a) # valid
def f2():
print(a) #invalid
f1()
f2()
Global variable:
A variable that are declared outside a function are called global variables.
Example: a=10
def f1():
a=20
print("inside f1():",a)
def f2():
print("inside f2():",a)
f1()
19
KMEC/II/SP/Unit-1 [Link] KRISHNA
f2()
Output:
inside f1(): 20
inside f2(): 10
global keyword:
We can use global keyword for the following 2 purposes:
1. To declare global variable inside function
2. To make global variable available to the function so that we can perform required
modifications
Example:
def f1():
global a
a=10
print("inside f1():",a)
def f2():
print("inside f2():",a)
f1()
f2()
Output:
inside f1(): 10
inside f2(): 10
Recursive Functions
A function that calls itself is known as Recursive Function.
The main advantages of recursive functions are:
1. We can reduce length of the code and improves readability
2. We can solve complex problems very easily.
20
KMEC/II/SP/Unit-1 [Link] KRISHNA
output: 10
Example_2: Using lambda function to multiply two integers.
f= lambda x,y:x*y
result(f(2,3))
print(result)
output: 6
Example_3: Using lambda function to find the maximum of two numbers.
f=lambda a,b:a if a>b else b
print(“Maximum=”, f(5,6))
output: Maximum= 6
Note:
1. In lambda functions we don’t need to write explicit return statement, internally lambda
function returns a value.
2. Python 3 supports iterators, such as filter(), map(), and reduce(), which are useful when you
need to iterate over the items in a list, create a dictionary, or extract a subset of a list.
3. lambda functions that are often used in combination with the functions filter(), map(), and
reduce().
map() function
The map() function is a built-in function that applies a function to each item in an iterable.
Syntax: map(function,sequence)
For every element present in the given sequence (list or range),it apply some modification and
generate new element with the required modification.
21
KMEC/II/SP/Unit-1 [Link] KRISHNA
Example: The function can be applied on each element of list and generates new list.
Example_1: Write a program that take a list of values and multiply each element of the list
with 2 using a fuction name multiply().
l=[1,2,3,4,5]
def multiply(x):
return 2*x
m=list(map(multiply,l))
print(m)
output: [2,4,6,8,10]
Example_2: Write a program that take a list of values and multiply each element of the list
with 2, using a lambda fuction.
l=[1,2,3,4,5]
m=list(map(lambda x:x*2,l))
print(m)
output: [2,4,6,8,10]
map() function can be applied on multiple lists. We need to make sure that the lists should have
same length.
Example: list1=[1,2,3,4]
list2=[5,6,7,8]
list3=list(map(lambda x,y:x*y,list1,list2))
print(list3)
output: [5,12,21,32]
Note: In the above program x takes the values from list1 and y takes the values from list2.
filter() function
The filter() function allows you to extract a subset of values based on conditional logic.
Syntax: filter( function, sequence)
22
KMEC/II/SP/Unit-1 [Link] KRISHNA
else:
return False
l=[1,2,3,4,5,6]
even_list=list(filter(even_fun,l))
print(even_list)
output: [2, 4, 6]
Example_2: Write a program that take a list of values and create list of even numbers using
lambda function.
l=[1,2,3,4,5,6]
even_list=list(filter(lambda x:x%2==0,l))
print(even_list)
output: [2, 4, 6]
reduce() function
The reduce() function reduces sequence of elements into a single element by applying the
specified function.
Syntax: reduce(function,sequence)
23
KMEC/II/SP/Unit-1 [Link] KRISHNA
Modules
A module in Python is a file containing Python code (functions, classes, or variables) that can
be reused in other programs.
• It helps organize large programs into smaller, manageable pieces.
• It avoids code duplication and improves reusability
Types of Modules:
1. Built_in 2. User Defined 3. Third party Modules
Built_in modules
Python provides several inbuilt modules such as random, math,datetime, os,sys,time etc.
Example:
import math
print([Link](25))
5.0
print([Link](8))
2.0
#use_module.py
import arithmetic
[Link](10,20)
[Link](10,20)
[Link](10,20)
24
KMEC/II/SP/Unit-1 [Link] KRISHNA
Renaming a module
A module can be renamed using the keyword "as"
Example: rename arithmetic module with new name "a".
import arithmetic as a
[Link](10,20)
[Link](10,20)
[Link](10,20)
from keyword
We can also import a module using "from" keyword.
Advantage: We can access members directly without using module name.
Example: from arithmetic import *
sum(10,20)
sub(10,20)
mul(10,20)
output: >>>python use_module.py
Sum: 30
Sum: -10
Sum: 200
The statement from arithmetic import *, imports all members (variables and functions) of a
module. We can import a specific function in a module as follows:
from arithmetic import sum
sum(10,20)
output:
sum: 30
25
KMEC/II/SP/Unit-1 [Link] KRISHNA
import random
[Link]()
0.12570589738398708
[Link](1,10)
2.7490802349697097
Integer functions:
1. randint(start, stop)--> returns random integer value between start value and stop value where
stop value is also included.
2. randrange(start, stop, step): return random integer value between start value and stop value
(with help of step value) where stop value is not included.
import random
[Link](1,10)
5
[Link](1,10)
5
Iterable functions:
1. choice(sequence): returns a random element from the given sequence data. Sequence may
be a range(), string, list, tuple or belongs any of sequence type variable.
2. shuffle(list): returns the list with values to be swapped in random order.
Note: The argument must be list or list values only. Because list is mutable where as string,
tuple are immutable and set and dictionary doesnot support indexing so swapping is not
possible.
Example: import random
l=['A','B','C','D','E']
[Link](l)
'B'
[Link](l)
print(l)
['A', 'E', 'D', 'C', 'B']
math module:
This module provides several inbuilt functions for mathematical operations such as square root
and cube roots, logarithmic, and trigonometric functions.
Example: sqrt(), cbrt(), ceil(), floor(),log(),sin(),cos() etc
import math
[Link](25)
5.0
[Link](8)
2.0
[Link](2.56)
3
[Link](2.56)
2
26
KMEC/II/SP/Unit-1 [Link] KRISHNA
Operator precedence
Operator precedence decide which operator is evaluated first when multiple operators are
present in a single line of expression.
Operators with higher precedence are evaluated before those with lower precedence.
When operators have the same precedence, their associativity dictates the order of
evaluation, most operators have left-to-right associativity, except for a few like
exponentiation (**), which have right-to-left associativity.
Precedence
Operator(s) Description Associativity
Level
1 () Parentheses (grouping) Left-to-right
x[index],
Subscription, slicing, function call,
2 x[index:index], x(...), Left-to-right
attribute reference
[Link]
3 await x Await expression N/A
4 ** Exponentiation Right-to-left
Positive, negative, bitwise NOT (unary
5 +x, -x, ~x Right-to-left
operators)
Multiplication, matrix multiplication,
6 *, @, /, //, % Left-to-right
division, floor division, remainder
7 +, - Addition and subtraction Left-to-right
8 <<, >> Bitwise left and right shifts Left-to-right
9 & Bitwise AND Left-to-right
10 ^ Bitwise XOR Left-to-right
11 | Bitwise OR Left-to-right
in, not in, is, is not, <, Comparisons, including membership
12 Left-to-right
<=, >, >=, !=, == and identity tests
13 not x Boolean NOT Right-to-left
14 and Boolean AND Left-to-right
15 or Boolean OR Left-to-right
16 if-else Conditional expressions Right-to-left
17 lambda Lambda expressions N/A
Assignment expressions (walrus
18 = Right-to-left
operator)
27
KMEC/II/SP/Unit-1 [Link] KRISHNA
Applications of Python
28
KMEC/II/SP/Unit-1 [Link] KRISHNA
Conclusion
Scientific computing is an indispensable field that bridges mathematics, computer science, and
domain-specific sciences to enable cutting-edge discoveries and innovations. It is the backbone
of modern research and technological advancements, making it a critical area of study for
scientists, engineers, and data analysts.
Output: 'abcxyz'
When we perform string concatenation with + operator we need to make sure that both the
objects must be string type only, otherwise we will get error.
29
KMEC/II/SP/Unit-1 [Link] KRISHNA
String unpacking
We can “unpack” the letters of a string and assign them to variables.
Example: s = "abc"
x,y,z=s
print('x=',x,'y=',y,'z=',z)
output: x=a y=b z=c
Membership operators
Using "in" and "not in" operator We can check whether the character or string is present in
the given string or not.
Let s='Python'
Example_1: 'P' in s
True
Example_2: 'th' in s
True
Example_3: 'yto' in s
False
Example_4: 'a' not in s
True
String length
Len() is used to find the total number of characters in a string.
Example: s='abcd'
print("Length=",len(s))
output: Length= 4
30
KMEC/II/SP/Unit-1 [Link] KRISHNA
Indexing in strings
String characters accessed by using index values of string.
Python supports positive and negative indexing.
Positive indexing traverse from left to right. Positive index values always starts from 0
from the left side.
Negative indexing traverse from right to left. Negative index values always starts from -1
from the left side.
Example: s='Python'
-6 -5 -4 -3 -2 -1
P y t h o n
0 1 2 3 4 5
Slicing in Strings
We can extract substring of a string using slicing operators [:].
Syntax: string_name[start : stop : step]
The start value in inclusive and default start value=0. It is optional
The stop value is end value, it is exclusive.
The step value is increment value, the default step value=1. It is optional.
Slicing supports both positive index as well as negative index.
If step value is positive (i.e. step=1) , then it operates on the left to right direction.
If step value is negative (i.e. step=-1) , then it operates on the right to left direction.
Examples:
To access first 3 characters of string, we can use:
s[0:3:1] 'Pyt'
s[:3:] 'Pyt'
To access entire string we can use:
s[::] 'Python'
To access string in reverse order (right to left):
s[::-1] 'nohtyP'
31
KMEC/II/SP/Unit-1 [Link] KRISHNA
String functions
Find substrings:
find() and index() are used to find substring in forward direction.
rfind() and rindex()are used to find substring in backward direction.
find(): It returns index of first occurrence of the given substring.
If the substring is not available then -1 will be returned.
Example: s='Python Programming'
[Link]('Python')
0
[Link]('thon')
2
[Link]('java')
-1
We can also specify the boundaries to search using slicing operator.
[Link]('Pro',4,11)
7
The above function dictates find the substring 'Pro' from index 4 to 10.
32
KMEC/II/SP/Unit-1 [Link] KRISHNA
33
KMEC/II/SP/Unit-1 [Link] KRISHNA
Splitting of Strings
split() function is used to divide the given string according to specified separator given as argument.
split(): convert string to list by splitting the string from left to right side.
Syntax: split( seperator, maxsplit )
Note : If we don’t specify any separator then by default it take ‘space’ as separator.
s="Python Programming"
[Link]()
['Python', 'Programming']
Example: price=100$200$300$400$
[Link]('$')
['100', '200', '300', '400', '']
[Link]('$',maxsplit=2)
['100', '200', '300$400$']
rsplit(): convert string to list by splitting the string from the right to left side.
Syntax: rsplit( separator, maxsplit)
Example: grade='A,B,C,D,F'
[Link](',')
['A', 'B', 'C', 'D', 'F']
[Link](',',maxsplit=2)
['A,B,C', 'D', 'F']
Joining of Strings
join(): Combine elements from iterable (list or tuple) with respect to seperator.
Syntax: 'seperator'.join(iterable)
Condtion: The iterable must contains only characters.
Example_1: l= ['Python', 'Programming']
''.join(l)
'PythonProgramming'
' '.join(l)
'Python Programming'
'-'.join(l)
'Python-Programming'
Example_2: marks={'Physics':86, 'Chemistry':70}
' and '.join(marks)
'Physics and Chemistry'
Note: If we give dictionary as argument in join(), it only joins keys, values of dictionary are ignored.
34
KMEC/II/SP/Unit-1 [Link] KRISHNA
35