BSSS IAS
Barkatullah University
PGP Term 1
Title:
Assignment for Business Analytics
Topic:
Theory and practical summary of class teaching in python
Submitted by: Submitted to:
Kulraj Suri Mr. Yogesh Payasi
Table of Content
Python & Its History
How to install IDE
Variables and Operators
Boolean and Comparison
Important Functions
Control Flow and Loops
Functions
Strings
Data Structures
What is Python?
Python is a high-level, interpreted programming language.
It is easy to read and write, with simple syntax that emphasizes code
readability.
Python supports multiple programming paradigms:
Procedural
Object-oriented
Functional
It comes with a large standard library and has a huge ecosystem of
external packages.
Common uses: Web development, data science, machine learning,
automation, game development, scripting, and more.
History of Python
Created by: Guido van Rossum
First released: 1991
Original goal: Make programming easier and more fun, while still being
powerful.
Python 2: Released in 2000, widely used, but now deprecated (official
support ended in 2020).
Python 3: Released in 2008, fixed many design issues, current standard
version.
Python is open source, which means anyone can contribute to its
development.
Interesting facts
Named after “Monty Python’s Flying Circus”, not the snake.
Python emphasizes simplicity and readability over complexity.
Its motto: “There should be one—and preferably only one—obvious way to do it.”
Variables and Operators
Data Types
int - Integer Date/Time
float - Float Geographical data
str - String
bool - Boolean
complex
Variables
+ Basic Addition c=a+2
- Basic Substraction c = 50 - a
* Basic Multiplication c=a*3
/ Basic Division c=a/5
Operators
+ Basic Addition c=a+2
- Basic Substraction c = 50 - a
* Basic Multiplication c=a*3
/ Basic Division c=a/5
% Modulus Gives remainder 27%5 R=2
** Raise to the power Raises to the power c = 2**2 ; c = 4
// Floor Division Gives quotient in integer 100/3 = 33.33
and not in decimal
Rules for naming a variable
Dos:
always start with an alphabet or underscore
abc = 1
_abc =2
should only include alphabet, underscore and number
ab12_cd = 3
should be meaningful
stud_id2024 ##(student id of batch 2024)
Dont’s:
not start with a number
12_bc = 1 X
not have any operator in between like + - etc
ab-cd = 23 X
not have any spaces in between
total marks = 120 X
not include python keywords
class = 52 X
Assigning Variable
a = 52
b = 34 + a ## works only when a is pre defined
xy = 23
total_marks = 23
a,b,xy= 52, 34+a, 23 ## multiple assignment
Functions related to Variables
print() ## Display output
print (x+y)
return ##Send value from function
return a + b
type() ##Check data type
a = 12.4
print(type (a))
<class ‘float’>
del ##Delete variable
del a
print (a) ##error
input () ## takes input from user
name = input("Enter name: ")
%whos ##List variables (Jupyter)
a= 12.3
b = 2+j
c = 15
d = “hi Sir”
%whos
Variable type data/info
a float 12.3
b complex 2+j
c int 15
d str hi Sir
Type Bool and Comparison
Boolean Operators
== True if equal to
!= True, if not equal to
< True, if less than
> True, if greater than
<= True, if less than or equal to
>= True if greater than or equal to
and (x) True, if both conditions are True
or (+) True, even if one of the condition is True
Boolean Usage
Bool assigned to variables:
a = true
b = true
c = false
%whos
Variable type data/info
a bool true
b bool true
c bool false
Bool output with and/or:
a = True
b = True ##True and False (case sensitive)
c = False
print ( a and b) ## True
print ( b and c) ## False
print ( a and c) ## False
print ( a or b) ## True
print ( b or c) ## True
Bool output with Not:
a = True
b = True ##True and False (case sensitive)
c = False
e = a and b
print (not (a)) ## false
d = not(c) ##true
print (not(e)) ## False
Comparison
a=5
b=4
c = a<b
print(type(c)) ##bool
print c ##false
a=5
b=4
d = a==b
print(type(d)) ##bool
print d ##false
5==5.0 ##True
print ((not(2!=3) and True) or (False and True))
Other Useful Functions
divmod(x,y) ## gives quotient and remainder as output in tuple
isinstance(x, int) ##returns True, if argument is instance of that class
round(float) ##rounds of a number
pow(x,y) ## raises x to the power of y
Control Flow and Loops
Control Flow Loops
if for
else while
elif break
Nested if continue
pass
Control Flow
Determines how python will execute a code
By default, python executes codes line by line
Control flow helps to change the order
Concerned with if, elif and else and invloves the concepts of
indentation and nesting, these help python to make decisions
upon the inputs
Indentation: enables pyhton to understand which statement
belongs to which coniditon
if a statement below if condition is indented; it belings to this
condition
if (a>b):
print (a) ## belongs to if condition of (a>b)
print (“not bigger than b”) ## not a part of condition
Nested if: Basically indents another if condition under an already
existing if or elif condition.
The following is the program of a grade calculator which is based on
control flow using if, elif and else and uses nested if as well.
How does it works
It asks user if they want to open the grade calculator or not using A
(to open) or B (to close)
then it asks user to input marks
it assigns level of proficiency and Grade to the marks entered
A+, A, B+, B, C, Passed and Failed
Limitations
It does not goes back to ask the user whether they want to do it again
it can not break in between if the user wishes to not continue the
calculation
Loops - A type of control flow
Types of loops: Types of flow control:
for pass
while continue
break
Difference between for and while loop:
For loop: While loop:
sequence-driven, condition-driven,
executes a fixed number of executes until a Boolean condition
times, becomes False.
updation is automatic updation of variable is manual
Less Risky as it has fixed Risk is more, if conditions become
number of iterations false
No usual initialisation of Manual initialisation of variable
variable required needed
Both loops can use break and continue, and can have an optional else block.
Continue: skips the current iteration and continues to the next iteration of
the loop
Pass: has syntactical usage and just use as placeholder and has no real use
Break: Stops the loop immediately, regardless of how many iterations are
left
Infinite output
n = int(input()) ## sets the number of iterations
i=1
while i<n: ## loop for the condition till i is less than 1 it is true
if i%2==0: ## condition 2 but inside the loop
print(i)
else:
pass
print (i) ## i + 1 only when the if condition is false
i +=1
print ("out of the loop")
Once the iteration matches the if condition, it has no escape.
The loop will not terminate as:
if condition became true and:
it can neither get out of the loop:
it has no break,
anything that makes if temporarliy or permanenely false
Corrected version
## helps to add 1 to i and break out of the if while
not stopping the iterations
Using Continue and Break
Continue
## we cant see a lot
The continue is placed in such a manner that we cant see how
many times else was executed before finally executing the break
in if condition
The continue is placed in such a
manner that we can now see
how many times else was visited
before breaking the while loop.
Also here loop was exited using
break and not by making the
condition false.
Using while loop
While is dependent on the bool condition of (i<n)
This loop shows:
how many times loop was visited before the condition was false
a statement of printing (i to power 2) was executed without affecting the
actual i
iterations were continued by i+=1 i.e. i = i+1
this loop was terminated when the condition turned false and not using
break
Using while loop (another example)
Functions
In Python, a function is a reusable block of code that performs a specific
task. Instead of writing the same code again and again, you put it inside a
function and call it whenever you need it.
Characteristics
Reusable
Perfroms specific task
can take input parameters
may or may not return a value
executes only when called
makes code readable
Points to remember:
Keep meaningful names
Keep it short and simple
Use proper indentation
Add doc string if needed
Use return (in place of print) when needed
Test the function
Do not use global variables and use parameters
defining a function main body of function
docstring of function
calling a
function
Docstring
Docstring is a part of function which may or may not be used by the user. It
basically hihglights what a function is used for and is stored in __doc__ unlike
comments which are not stored.
these doctring can not be called but can be used in any part of a code to
understand the iportance of the function.
it can be obtained using:
help()
?? and ? ##in jupyter only
While help() and ? gives out just docstring
?? gives out the entire source of it and tells us what the function entirely is
Inputing (arguments)
Single (arguments)
Multiple (arguments)
Keyword (arguments)
##here we jumbled the order
##Keyword argument defines explicitly
return instead of print()
Returning value using a variable
Returning value using return only
Global vs Local Variable
##defining the global variable
##defining the local variable
They can have same names if they are global and local yet they will have different values assigned to them.
Return ending function
##see how return ends the function
None type function
##return defines the data type of function
## type of function
Tuple packing and unpacking
## tuple packing return (a,b,c)
## tuple unpacking
Variable-length positional arguments
## takes all possible arguments
## loop helps to keep running the sum process
## giving various arguments using function
The hero of this function is ‘*’.
The aestrik sign guides python to run into a mode where it can
take ‘n’ number of arguments.
These arguments are together then processed by the function’s
operation.
Strings
Strings are a data type in Python.
Strings enclosed in “hi world” and ‘hi world’ are treated as same
Adding two string together
Adding two string together (with some other string in between)
Adding two string together (using addition)
## just to know the type of data type
Adding two string together (using addition with space in between)
Printing a string and another data type together during print
Adding a string and another data type together during print
This gives error because python does not allows string to be added with
another data type but only string.
## we just made a simple tweak by
converting integer to string
Multiline String
Indexing and Slicing
-11 -10 -9 -8-7 -6 -5 -4 -3 -2 -1
s= “ h e l l o w o r l d ”
0 1 2 3 4 5 6 7 8 9 10
Feature Indexing Slicing
Accesses One character Multiple characters
Syntax s[i] s[start:end:step]
Output Single character Substring
Out of range ❌ Error ✅ No error
Length Always 1 Can be 0 or more
Indexing
## indexes the first alphabet
## prints the indexed fourth alphabet
## reverse indexing last third alphabet
## reverse indexing last first alphabet
## no reverse indexing last first
alphabet with 0
Slicing
## len() function helps to know the
length of the string
## len() function helps to know the
length of sliced string
## simple slicing
## slicing from beginning to certain
point in string
## negative slicing - correct syntax
## negative slicing - incorrect syntax
Slicing with skipping using STEPS
Reverse Indexing and Reverse Printing
Functions Used in Strings
strip()
lower()
upper()
replace()
split()
capitalize()
strip()
This function is used to remove gaps, texts, or characters from the start and end of a string.
## There are gaps at the start in
the middle and in the end of the
string
## function removes the gaps
at the start and at the end of the
string
## function removes the ‘*’ at
the start and at the end of the
string
lower() | upper() | capitalize()
This function is used to turn a string to lower, upper and capitalize case.
## function turns all letters to lowercase
## function turns all letters to uppercase
## function turns string to sentence case by
capitalizing the first letter only. It does not work
for the letter after full stop.
replace()
This function replaces a particular part of the string with the argument given in the function.
split()
This function splits the string into parts already separated in the string but it is identified by
the argument given in the function.
List, Set, Tuple, Dictionary
List
A collection of items
Ordered and changeable
Allows duplicate values
Uses
You need order
You need to modify data
Duplicates matter
Functions used
append() # add one item
extend() # add multiple items
insert() # add at specific index
remove() # remove item
pop() # remove by index
clear() # remove all
sort() # sort list
reverse() # reverse list
Tuple
Like a list, but cannot be changed
Ordered and indexed
Uses
Data should not change
Fixed data
Safer & faster than lists
Functions used
del
There are no functions because tuples are immutable
Set
A collection of unique items
Unordered
No Indexing
Uses
You want no duplicates
Order Does not matter
Fast membership checking
Functions used
add() # add one item
update() # add many items
remove() # remove item (error if not found)
discard() # remove item (no error)
Dictionary
A collection of key-value pairs
Ordered
Indexed by keys (not numbers like lists)
Keys must be unique, values can be duplicates
Uses
Fast lookups by key
Store related information (like name → age)
When key-value mapping is needed
Avoid duplicates in keys automatically
Functions used
dict[key] = value # add or update a key-value pair
update() # add multiple key-value pairs
get() # get value for a key (None or default if not found)
keys() # get all keys
values() # get all values
items() # get all key-value pairs
pop() # remove a key and return its value (error if not found)
pop(key, default) # remove a key safely, return default if not found
del dict[key] # delete a key (error if not found)
clear() # remove all items
copy() # return a shallow copy of the dictionary
setdefault() # return value if key exists, else set it to default
Codes for List Set Tuple and Dictionary