Guido van Rossum
Python
Programming for
Business
Prerequisite
1. Learn the difference between front-end and back-end –
the front-end is what you see (HTML, CSS-Cascading Style Sheets, and JavaScript) Vs the
back-end code is what goes on behind the scenes (Python, Ruby, PHP-Hypertext Pre-
processor)
Right Click or Ctrl + U
2. Anyone can be a Python developer without knowing “everything” about
Python - virtually no developers will know the entirety of a programming
language
3. Understand what you can do with Python
what you can do with Python ?
Develop Cool Software Web Scraping
Web Development Speed Up and Automate Your
Workflow
CLI Development
DevOps
GUI Development Development Environment
Game Development Software Packaging and
Dive Into Data Science and Deployment
Math Database Systems
Machine Learning Software Testing
Scientific Computing Develop Embedded Systems and
Robots
Data Analysis and Visualization
• Content Streaming on Netflix -
• Instagram currently features the world’s largest deployment of the Django
web framework, which is written entirely in Python - https://instagram-engineering.com/web-service-efficiency-at-
instagram-with-python-4976d078e366
• Instacart - demand forecasting - https://stackshare.io/posts/the-tech-behind-instacarts-grocery-delivery-service
• Spotify uses Python for its back-end services and for data analysis.
Refer : https://www.trio.dev/python/resources/companies-using-python
Course Code: 24PGDBA302
Course Title: Python Programming for Business
Number of Credits: 3 Number of Hours: 36
Course Objective : To proficiently use Python programming and its libraries to
analyze data, perform exploratory data analysis (EDA), conduct hypothesis
testing, build predictive models, and apply basic natural language processing
(NLP) techniques.
Course Outcomes
1. Understand and develop a solid technical foundation in
Python programming.
2. Learn to Create and manipulate data frames and apply
arithmetic operations to determine data statistics.
3. Discover the value of performing comprehensive exploratory
data analysis to uncover patterns and insights in data.
4. Perform diagnostic analysis to draw meaningful conclusions
and make data-driven predictions.
5. Recognize the significance of applying basic NLP techniques to
analyze and process language data to discover hidden
insights.
Syllabus
Module Topic CO Number of hours
No.
1 Introduction to Python Programming 1 8
2 Working with Data frames 2 6
3 Exploratory Data Analysis 3 8
Hypothesis Testing and Predictive
4 Analysis 4 7
5 Introduction to Natural Language 5 7
Processing
Total 36
Recommended & Reference Books
1. Martelli, A., Ravenscroft, A. M., Holden, S., & McGuire, P. (2023). Python in a
Nutshell. " O'Reilly Media, Inc.".
2. Matthes, E. (2023). Python crash course: A hands-on, project-based
introduction to programming. no starch press.
3. Mckinney, W. (2017). Python for data analysis : data wrangling with pandas,
NumPy, and IPython. O’reilly Uuuu-Uuuu.
4. Molin, S., & Jee, K. (2021). Hands-On Data Analysis with Pandas : A Python
Data Science Handbook for Data Collection, Wrangling, Analysis, and
Visualization, 2nd Edition. Packt Publishing, Limited.
5. Yuli Vasiliev. (2020). Natural Language Processing Using Python. O’reilly Media.
Assessment Plan
S. No. Timelines Component Details CO Coverage Weightage
Marks Attendance
1 February MCQ 1 16 4
2
2 March Assignment I 3 8 2
3 April Practical Test 4 8 2
5 8 2
Teaching Methodology
Getting Started……….
Python is powerful... and
fast;
plays well with other
programming languages;
runs everywhere;
is friendly & easy to learn;
is Open.
Introduction
Python is a high-level, interpreted and general-
purpose dynamic programming language that
focuses on code readability. The syntax in
Python helps the programmers to do coding in Python is a computer programming language
often used to build websites and software,
An interpreted language is a programming automate tasks, and conduct data analysis. The
fewer steps as compared to Java or C++.
language whose implementations execute
name Python comes from Monty Python. When
Guido van Rossum was creating Python, he was
instructions directly and freely also reading the scripts from BBC’s Monty
Python’s Flying Circus.
www.Python.org
What is Python?
• Supports dynamic data type
• Independent from platforms - Python code can be run on different
types of operating systems, such as Windows, Mac, or Linux, without any
modifications
• High-level internal object data types
• Automatic memory management with API
• Glue language & It’s free (open source)!
IDE - Integrated Development Environment
• IDE-Software for building applications that combines common
developer tools into a single graphical user interface (GUI).
• Tools provided by an IDE include a text editor, a project editor, a tool
bar, and an output viewer.
• IDEs can perform a variety of functions. Notable ones include write
code, compile code, debug code, and monitor resources.
Time Line
• Designed by: Guido van Rossum
• Developer: Python Software Foundation
• First appeared: 20 February 1991; 34 years ago
• OS: Windows, macOS, Linux/UNIX, Android and more
• Stable release:Python 3.12.8 (Dec. 3, 2024)
• Filename extensions: .py,.pyi,.pyc,.pyd,.pyo (prior to 3.5),.pyw,.pyz (since 3.5)
• Paradigm: Multi-paradigm: object-oriented, procedural (imperative),
functional, structured, reflective
ipynb file extension is used for computational notebooks that can be open with Jupyter
Notebook. The Jupyter Notebook was formerly named IPython Notebook. The extension *. ipynb
is from letters IPython Notebook
Running Python Interactively ……
1. ANACONDA Distribution - https://www.anaconda.com/products/distribution
2. Spyder - https://www.spyder-ide.org/
3. Jupyter Notebook - https://jupyter.org/
4. Colaboratory, or “Colab”
https://colab.research.google.com/?utm_source=scs-index
5. Kaggle Notebook -
https://www.kaggle.com/code/scratchpad/notebook9e73eda9cd/edit
Running Python Interactively ……
1. ANACONDA DISTRIBUTION - The world’s most popular open-source Python
distribution platform –
2. Spyder is a free and open source scientific environment written in Python -
(Integrated development environment)
3. Jupyter Notebook: The Classic Notebook Interface
4. 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
5. Kaggle Notebook is a cloud computational environment which enables
reproducible and collaborative analysis. Notebooks, previously known as
kernels, help in exploring and running machine learning codes.
Python Installation
How to Install?
Step : 1 https://www.anaconda.com/
Step : 2 Click free download
Step: 3 Download and Install
Python Shell Prompt
OR Command Line
File Name with extension
Output User Program
Output – Python
is Interactive
The Basics
Object Oriented Programming language
Object-oriented programming (OOP) is a computer
programming model that organizes software design around
data, or objects, rather than functions and logic.
• An object can be defined as a data field that has unique
attributes and behavior.
Interpreted Language
Python is an interpreted language, which means the source code
of a Python program is converted into bytecode, Which is then
executed by the Python virtual machine.
Bytecode : it is a set of instructions for a virtual machine
(PVM).
Is Python Case Sensitive?
Yes
Case-Sensitive: Any computer function or a program
that differentiates between upper and lowercase
letters is called a case-sensitive program.
How to Executive Python Programs?
• Shift + Enter run the current cell, select below
• Ctrl + Enter run selected cells
• Alt + Enter run the current cell, insert below
• H show all shortcuts
Jupyter Notebook
Shortcuts
https://towardsdatascience.com/jypyter-notebook-shortcuts-bf0101a98330
Comments – Python using # tag
• Comments are non executable statements in a program.
• A comment in Python starts with the hash character “ # “, and
extends to the end of the physical line
• A hash character within a string value is not seen as a comment.
• To be precise, a comment can be written in three ways - entirely on its
own line, next to a statement of code, and as a multi-line comment
block
Interacting with Python Programs
• Python program communicates its results to user
using print
print()
Example - print()
#Example Print
age=input('How old are you')
print('you are',age,'years old')
Dynamic Data Type
X = 10 a=10
print(X) x="Hello" b=15
print(x) a>b
X=“Hello”
print(X) x=10.5
print(x)
https://medium.com/@mycodingmantras/understanding-the-dynamic-typing-nature-of-python-a-
comprehensive-guide-8f825fda0d01
Python Character set
What is Character Set?
Character set is a bunch of identifying elements
in the programming language.
Python Character set
PYTHON
CHARACTER
SET
• Letters:- A-Z, a-z
• Digits:- 0 to 9 American Standard
• Special Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? & Code for
Interchange
Information
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab, Carriage Return(a simple
escape character).
• Other Characters:- Python can process all 256 ASCII and Unicode Characters.
Tokens Or Lexical Unit
What is Token?
Individual elements that are identified by programming
language are called tokens or lexical unit.
TOKENS / LEXICAL UNITS
1. Key
Words
5. 2.
Punctuators Identifiers
TOKENS
4.
3. Literals
Operators.
1. Keyword/Reserved Word
What is Keyword?
• Python keywords are special reserved words that have
specific meanings and purposes and can't be used for
anything but those specific purposes.
• The words are defined in the python interpreter
hence these cant be used as programming
identifiers.
Some Keywords of Python Language
FALSE await else import pass
None break except in raise
TRUE class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Example - 1
def = 10 # 'def' is a keyword in Python
print(def)
Error: SyntaxError:
invalid syntax
Example - 2
class = "Data Science" # 'class' is a keyword
print(class) Error: SyntaxError:
invalid syntax
Can we use Class ( C with Upper case )? = Yes, you can use Class (with an
uppercase "C") as a variable name because Python is case-sensitive, and
class (lowercase) is the reserved keyword.
2. Identifiers
What is an identifier?
An identifier is a name assigned to entities such as
classes, functions, and variables. It helps distinguish
one entity from another in a program
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore _.
• Names like myClass, var_1 and print_this_to_screen, all are valid example.
2.An identifier cannot start with a digit.
• 1variable is invalid, but variable1 is a valid name.
3. Keywords cannot be used as identifiers.
Output
Input: File "<interactive input>", line 1
global = 1 global = 1
^
SyntaxError: invalid syntax
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier
Input:
a@ = 0
Output
File "<interactive input>", line 1
a@ = 0
^
SyntaxError: invalid syntax
5. An identifier can be of any length.
Rule ✅ Valid Example ❌ Invalid Example
Starts with a _temp, data1 1data
letter/underscore
Can contain letters, student_123 student@123
digits, and underscores
Cannot be a keyword my_class class
Case-sensitive DataScience vs. -
datascience
No spaces first_name first name
Cannot contain special value_100 value#100
characters
Cannot contain score_total score-total
operators
Python Naming Conventions
SOME VALID IDENTIFIERS:
Myfile1 DATE9_7_8
y3m9d3 _xs
MYFILE _FXd The hyphen is the
SOME INVALID IDENTIFIERS: subtraction operator
MY-REC 28dre break
elif false del
Variables in Python ( Identifier)
In Python, a variable is a name that represents or points to a
specific object. Once an object is assigned to a variable, the variable
can refer to the object using that name.
However, the data itself is stored within the object. It is worth
noting that variables in Python are not restricted to a specific type.
This means that a variable can be assigned a value of one type and
later be reassigned a value of a different type. This is known as
dynamic typing.
Example
#Type I Integer
Variable=26
print(Variable)
#Type II String
Variable="Data Science"
print(Variable)
n=300
This assignment creates an integer object with
the value 300 and assigns the variable n to point
to that object.
Variables And Assignments
Named labels are called variables.
For example: marks =86
78 79 80 81 82 83 84 85 86 87
2000 2016 2018 2026 2032 2044 2048 2050 2054 2068
Note: Variables in python do not have fixed
marks refers to
locations unlike other programming languages location 2054
Object Identity
Python assigns a unique number to each newly created object.
Python guarantees that no two objects will share the same
identifier during any period where their lifetimes overlap.
• The built-in Python function id() returns an object’s integer
identifier.
Example
n=100 n=200
m=n m=400
id(n) id(n)
Output:11262432
Output:11259232
id(m)
id(m)
Output: 11259232 Output: 139904828706096
Variables And Assignments
lvalues & rvalues
Lvalue: Expressions that is on LHS (Left Hand Side) is
called Lvalue.
Rvalue: Expressions that is on RHS (Right Hand Side) is
called Rvalue.
Variables And Assignments
Multiple Assignments
Python is very versatile with assignment statements.
1. Assigning same value to multiple variables:
a=b=c=d=e=10
Variables And Assignments
Multiple Assignments
2. Assigning Multiple values to multiple variables:
p,q,r =5,10,15
print(q, r)
will print 10 15
p,q=q,p
print (p,q)
will print 10 5
Variables And Assignments
Multiple Assignments
#3. Assigning Multiple values to multiple variables:
a,b,c = 5,10,7
b,c,a = a+1, b+2, c-1
print(a,b,c)
will print 6 6 12
Variables And Assignments
Multiple Assignments
4. Expressions separated by commas are evaluated from left to
right.
Now, x=10
y,y=x+2,x+5
print(y)
y,y=12,15
First It will assign y = 12 then y = 15
So print(y) will print 15
Variables And Assignments
x=10
print(x)
x=“ Hello World”
print(x)
Variables And Assignments
Output will be
10 ?
x
Hello World ?
10
10
Hello World
Variables And Assignments
Caution with Dynamic Typing:
x = ‘day’
y = x/2 Error! String can not be divided.
print(y)
3. Literals / Constant Values
What is literals?
Values which never change during the execution of
program.
Types Of Literals / Constant Values
What are the types of literals?
1) String Literals or Constants
2) Numeric Literals or Constants
3) Boolean Literals or Constants
4) Special Literal -None
5) Literal Collections
1.String literals
# string literals
• A string literal can be created
# in single quote by writing a text(a group of
A = ‘Data Science' Characters ) surrounded by
the single(”), double(“”), or
# in double quotes print(A) triple inverted commas.
B= “Data Science" print(B)
print(C)
# multi-line String
C = ''‘ Data Science'''
Size Of Strings
‘\\’ Size is 1 (\ is an escape sequence)
‘abc’ size is 3
“\ab” size is 2
“Raama\’s Laptop” size is 14
How to find =len()
https://www.w3schools.com/python/
gloss_python_escape_characters.asp
Python String Concatenation
String concatenation means add strings together.
Use the “+” character to add a variable to another variable
x = "Python is "
y = "awesome"
z= x+y
print(z)
To convert a string to upper or lower case,
use the following codes:
# Converting to upper case string0.upper()
# Similarly string.lower() can be used to convert to lower
case.
string0=‘python’
string0.upper()
‘PYTHON’
2.Data Types in Python
• int
• Bounded integers,
e.g. 732 or -5
• float
• Real numbers, e.g.
3.14 or 2.0
• str
• Strings, e.g. ‘hello’
or ‘C’
Data Types in Python
• Scalar
• Indivisible objects that do not have internal
structure
• int (signed integers), float (floating point), bool
(Boolean), NoneType
• NoneType is a special type with a single value
• The value is called None
• Non-Scalar
• Objects having internal structure
• str (strings)
print(10 > 9)
3.Booleans
• While comparing two values, the print(10 == 9)
expression is evaluated and Python print(10 < 9)
returns the Boolean answer
• Almost any value is evaluated to True if
it has some sort of content.
• Any string is True, except empty strings. bool("abc")
bool(123)
• Any number is True, except 0. bool(["apple", "cherry
", "banana"])
• Any list, tuple, set, and dictionary are
True, except empty ones.
Command used to identify data type
type()
type(500)
Type Conversion (Type Cast)
• Conversion of value of one type to other
• We are used to int float conversion in Math
• Integer 3 is treated as float 3.0 when a real
number is expected
• Float 3.6 is truncated as 3, or rounded off as 4
for integer contexts
80
Type Conversion Examples
Note that float to int conversion
is truncation, not rounding off
round() – rounding
off numbers
81
4.Operators-Operators are tokens that trigger some
computation when applied to a variable
• Arithmetic + - * // / % **
• Comparison == != > < >= <=
• Assignment = += -= *= //= /= %= **=
• Logical and or not
• Bitwise & | ^ ~ >> <<
• Membership in not in
• Identity is is not
https://www.programiz.com/python-programming/operators#assignment
82
Operator Operation Example
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2*3=6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
Arithmetic Operators in Python
a=7 # division
b=2 print ('Division: ', a / b)
# addition # floor division
print ('Sum: ', a + b) print ('Floor Division: ', a // b)
# subtraction # modulo
print ('Subtraction: ', a - b) print ('Modulo: ', a % b)
# multiplication # a to the power b
print ('Multiplication: ', a * b)
print ('Power: ', a ** b)
Operator Name Example
= Assignment Operator a=7
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
**= Exponent Assignment a **= 10 # a = a ** 10
Python Assignment Operators
# assign 10 to a
a = 10
# assign 5 to b
b=5
# assign the sum of a and b to a
a += b # a = a + b
print(a)
Python Comparison Operators
Operator Meaning Example
== Is Equal To 3 == 5 gives us False
!= Not Equal To 3 != 5 gives us True
> Greater Than 3 > 5 gives us False
< Less Than 3 < 5 gives us True
>= Greater Than or Equal To 3 >= 5 give us False
<= Less Than or Equal To 3 <= 5 gives us True
Comparison Operators
a=5
b=2 # less than operator
print('a < b =', a < b)
# equal to operator
print('a == b =', a == b) # greater than or equal
to operator
print('a >= b =', a >= b)
# not equal to operator
print('a != b =', a != b)
# less than or equal to
operator
# greater than operator
print('a <= b =', a <= b)
print('a > b =', a > b)
Operator Description Syntax
+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the x/y
second
// Division (floor): divides the first operand by the x // y
second
Modulus: returns the remainder when the first
% operand is divided by the second x%y
** Power: Returns first raised to power second x ** y
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
Bodmas stands for B-Brackets, O-Orders
(powers/indices or roots), D-Division, M-
Multiplication, A-Addition, S-Subtraction.
Assignment Statement
• A simple assignment statement
Variable = Expression
= is known as the assignment operator
Example
a=5
b=6
print(a+b)
5. PUNCTUATORS
Punctuators
Punctuators are also called as separators
The Followings are used as punctuators:
Brackets [ ]
Parentheses ( )
Braces { }
Comma ,
Semicolon ;
Colon :
Asterisk *
Ellipsis …
Equal Sign =
Pound Sign # (number sign, hash, or pound sign)
WHITE SPACE
White Space
1. Whitespace is simply a character that is used for
spacing and has an “empty” representation
2. Indentation is a type of horizontal whitespace
strategically used to enhance the readability of our
code
j=1
while(j<=5):
print(j)
j=j+1
White Space
•Use consistent indentation instead
•The first line with less indentation is outside of the
block
•The first line with more indentation starts a nested
block
•Often a colon appears at the start of a new block.
(E.g. for function and class definitions)
Statements
• In computer terminology statement refers to an
instruction
• Program contains several statements
• A collection of statements makes program
• Another name for a program is code
Python Programming for Business – Part II
How to use emoji's on a laptop ?
Windows:
Press Windows + . (dot) or Windows + ; (semicolon) to
open the emoji keyboard.
Mac:
Press Control + Command + Space to open the emoji
picker.
Python Basics
Overview and its features:
1. Declaring variables
2. Functions
3. Conditional Statements
4. Control flow statements
5. Collections
6. Functional Programming
7. Modules and packages
Functions
• A function is a block of organized, reusable code
that is used to perform a single, related action
Types of Functions
There are three types of functions:
• Built-in functions or Pre-defined - a function that is already available
in a programming language, application, or another tool that can be
accessed by end users (refer Python function.xlsx) – Library
functions
• User-defined functions -A function is a block of code that performs a
specific task, allows to define functions according to need
• Anonymous functions-which are also called lambda functions
because they are not declared with the standard def keyword
Built-in functions or Pre-defined
#Example
M=20,30,24,35,4,56,1,78,86
min(M)
len(M)
type(M)
Syntax: User Defined-Python Functions
Example-Code-1:
def addElements(a,b):
return (a+b)
Invoking(Calling) the User-defined function
#1. Two integer values #2. Two float values
print(addElements(5,6)) print(addElements(5.5,6.3))
#3. Two strings
print(addElements("Python ","Programming"))
#Example Code-2
def number(a):
return a*a
#Example-1
print(number(12))
Class Work : Create a programme that takes two
arguments, name and age, and prints their values.
# Fun1 is the function name
def Fun1(Name, Age):
print(Name, Age) # call function
Fun1(“Ram", 23)
The Anonymous Functions- lambda
• These functions are called anonymous because they are
not declared in the standard manner by using the def
keyword.
• Lambda forms can take any number of arguments but
return just one value in the form of an expression
• An anonymous function cannot be a direct call to print
because lambda requires an expression
Example-1
# Anonymous Function- lambda
sum = lambda A,B: A+ B
# Call sum as a function
print(sum(10,20))
Input function
• Input( ) Function is a built in function of python used to
read values from the user
The general format or syntax of the input() is:
Variable Name =input(message)
#For Example:
p = input(“Enter the value”)
#Example : Input function
Name=input(“Enter the Name:”)
Age = input("Enter age: ")
print(Name,Age)
Type(Age)
How to take integer/float input
in Python using input() ?
This input() function returns string data and it
can be stored in a string variable. int() or float()
function convert string to into an integer/float
value.
#Example-1
A=int(input("Enter the Number:"))
B=float(input("Enter the Number:"))
C=A+B
print(C)
#Example : Input function
def square(num):
return num * num
n = int(input("Enter a number: "))
print("Square of", n, "is", square(n))
How to take integer/float input in Python using input() ?
A=input("Enter the Number: ")
B=input("Enter the Number: ")
C=A+B
print(C)
Example:
A=float(input("Enter A value: "))
B=float(input("Enter B Value: ")) A=int(input("Enter the Number: "))
C=A+B B=int(input("Enter the Number: "))
print(C) C=A+B
print(C)
1. Control flow statements: Use the if-else statements in Python
for conditional decision-making
2. for loop: To iterate over a sequence of elements such as list,
string.
3. range() function: Using a for loop with range(), we can repeat
an action a specific number of times
4. while loop: To repeat a block of code repeatedly, as long as the
condition is true.
5. Break and Continue: To alter the loop’s execution in a certain
manner.
6. Nested loop: loop inside a loop is known as a nested loop
Conditional / Control Flow Statements
Decision-making in a programming language is
automated using conditional statements.
• Python evaluates the code to see if it meets the
specified conditions
Types of Conditional Statements
1. If Statement
2. If Else Statement
3. If…Elif..else Statement
4. Nested If Statement
Indentation:
Python relies on indentation (whitespace at the beginning of a line) to
define scope in the code. Other programming languages often use curly-
brackets for this purpose.
If Statement
Python supports the usual logical
conditions from mathematics: These conditions can be
used in several ways, most
commonly in "if
Equals: a == b statements" and loops.
Not Equals: a != b
Less than: a < b An "if statement" is
Less than or equal to: a <= b written by using the if
Greater than: a > b keyword.
Greater than or equal to: a >= b
Syntax – if statement
In Python, a colon is required at the beginning of every
block of code.
if condition:
code code code
1.Write a program to find the largest of two numbers
#Example-1 #Example-2
a=35 a=35
b=45 b=45
if a>b: if a>b:
print("a is greater than b") print("a is greater than b")
print("b is greater than a") If a<b:
print("b is greater than a")
2. Write a program to check if the entered number is positive or negative
#Example-3
Number=int(input("Enter your number"))
if Number>0:
print("The given number is Positive")
If Number<0:
print("Negative")
Write a Python program using a user-defined function and
an if statement to check if a number is a multiple of 5. If the
number is a multiple of 5, print an appropriate message.
def check_multiple_of_five(num): The % symbol in Python
if num % 5 == 0: is the modulus
operator. It returns the
remainder when one
print(num, "is a multiple of 5 🎉") number is divided by
another.
n = int(input("Enter a number: "))
check_multiple_of_five(n)
if-Multiple Block
Joseph is visiting a hypermarket to purchase apples at
his mother's request and donate them to an old age
home. His mother has given him only ₹1,000. Find the
price of apples as of today. How many kilograms of
apples can Joseph buy without exceeding ₹1,000?
• Write a Python program to compute and display the
results.
A = 1000 # Money in hand
Price = float(input("Enter the price of apples per kg: "))
Quantity = float(input("Enter the quantity (in kg): "))
B = Price * Quantity # Total cost
if B > A:
print("The purchase price exceeds ₹1,000.")
print("Total cost: ₹", B)
if B <= A:
print("The purchase price does not exceed ₹1,000.")
print("Total cost: ₹", B)
If else statement
This statement is used when both the true and false parts
of a given condition are specified to be executed. When the
condition is true, the statement inside the if block is
executed; if the condition is false, the statement outside the
if block is executed. Syntax:
if condition :
#Will executes this block if the condition is
true
else :
#Will executes this block if the condition is
false
#Example-Write a program to find the largest of two numbers
A=35
B=25
if A>B:
print("A is Greater")
else:
print("B is Greater")
Example-1 Write a program to identify Odd
and Even numbers
A=int(input("Enter a Number: "))
if A%2==0:
print("A is an even number")
else:
print("A is an odd number")
Class Work
A content creator is planning to buy a new microphone for
streaming. The microphone costs ₹3,000, but they only
have a certain amount of money in their digital wallet.
Write a Python program that asks how much money they
have and checks whether they can afford the microphone.
• If they have ₹3,000 or more, print "You can buy the
microphone!“
• Otherwise, print "You need to save more before buying
the microphone."
mic_price = 3000 # Cost of the microphone
money = float(input("Enter the amount of money in
your digital wallet: "))
if money >= mic_price:
print("You can buy the microphone!")
else:
print("You need to save more before buying the
microphone.")
If…Elif..else Statement
In this case, the If condition is evaluated first. If it is false, the Elif
statement will be executed; if it also comes false, the Else
statement will be executed.
syntax:
if condition :
Body of if
elif condition :
Body of elif
else:
Body of else
Example-1.Write a program to check if the entered number
is positive or negative or Zero.
num =int(input("Enter Number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Class work
A gamer is buying a new graphics card based on their budget.
The options are:
• ₹50,000 or more → High-end GPU (RTX 4080, RX 7900 XTX)
• ₹30,000 to ₹49,999 → Mid-range GPU (RTX 4060 Ti, RX
7700 XT)
• Less than ₹30,000 → Entry-level GPU (RTX 3050, RX 6600)
Write a Python program that asks the user how much money
they have and suggests a suitable GPU based on their budget.
Code
budget = float(input("Enter your budget for a graphics card: "))
if budget >= 50000:
print("You can buy a high-end GPU (RTX 4080, RX 7900 XTX).")
elif budget >= 30000:
print("You can buy a mid-range GPU (RTX 4060 Ti, RX 7700 XT).")
else:
print("You can buy an entry-level GPU (RTX 3050, RX 6600).")
Loops and Control Statements
Loops are used for executing a block of code multiple times. Python
provides two types of loops:
1. for loop
2. while loop
Difference Between for and while Loops in
Python
Feature for Loop while Loop
Usage Used when the number of iterations Used when the number of iterations is
is known beforehand. unknown and depends on a condition.
Syntax Iterates over a sequence (list, tuple, Repeats as long as a condition remains
string, range, etc.). True.
Control Uses an iterator (in keyword) to go Uses a condition that is checked before
through elements. each iteration.
TerminationStops automatically after iterating Requires an explicit condition to
over the sequence. become False for termination.
Example for i in range(5): print(i) i = 0; while i < 5: print(i); i += 1
for Loop
Used to iterate over sequences such as lists, tuples,
strings, or ranges. Iterating over a sequence is called
traversal.
for variable in sequence:
# code block
Python Membership Operators
Operator Description Example
Returns True if a sequence
in with the specified value is x in y
present in the object
Returns True if a sequence
not in with the specified value is x not in y
not present in the object
Example - 1
Bigtech = ["Apple", "Google", "Samsung"]
for Bigtech in Bigtech:
print(Bigtech)
Example - 2
for i in range(10): # Runs exactly 10 times
print(i)
#Example:3
s=0
a = [2, 3, 1, 3, 3]
for i in a:
s += i # note this is equivalent to s = s + i
print(s)
while loop
Executes a block of code as long as a condition is
True.
Syntax:
while condition:
statements(code)
#Example:1
count = 0
while (count < 5):
count = count + 1
print("RIM Analytics")
#Example :2.Write a program to add natural numbers
# Program to add natural
# numbers up to n
# sum = 1+2+3+...+n
# To take input from the user
n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
Control Statements in Python
Control statements modify the execution
flow within loops.
break Statement : Exits the loop
immediately
for num in range(1, 6):
if num == 3:
break Output:
print(num)
1
2
continue Statement - Skips the rest of the current
iteration and moves to the next iteration.
for num in range(1, 6):
if num == 3: Output:
continue 1
2
print(num) 4
5
pass Statement : Acts as a placeholder when a
statement is syntactically required but no
action is needed.
for num in range(1, 6):
if num == 3:
pass # Placeholder
print(num)
else with Loops : The else block in loops executes
if the loop is not terminated by a break.
for num in range(1, 4):
print(num)
else:
print("Loop completed")
Data Structure : Working with Collections
Python provides several built-in data structures to store and
manipulate data efficiently. The primary data structures are:
1. List
2. Tuple
3. Set
4. Dictionary
List
• Lists are used to store data of different types in a
sequential manner.
• Each element in the list is assigned an address, called
an index.
• The index value starts at 0 and increments until the
last element, which is referred to as the positive
index.
• There is also negative indexing, which starts at -1,
allowing access to elements from the last to the first.
List
1. Lists can contain heterogeneous items, meaning a single
list can include integers, floats, strings, or objects.
2. Additionally, lists are not unique sets of items, allowing
values to be repeated.
3. Lists are mutable and are typically initialized with a set
of values inside square brackets or as an empty list.
#Example - List
# list with elements of different data types
list1 = [1, "Hello", 3.4]
# list with duplicate elements
list2 = [1, "Hello", 3.4, "Hello", 1]
# empty list
list3 = []
Activity 1 – Create a list of Batsmen and
Bowlers
Batsmen = [‘Rohit’,……….]
Bowlers = [‘Hardik’,……..]
Batsmen = [‘Rohit’, ‘Kohli’, ‘Shubman’, ‘Shreyas’, ‘Rahul’]
#The list index starts with 0. An item in the list can be
accessed using index as follows:
Batsmen[0]
Slicing a list
1. A slice of the list can be obtained using an index range
separated by a colon (:)
2. A range [0:2] means starting with index 0 until index 2,
but not including 2
Slicing a list
Batsmen[0:5]
#To find the last batsman, an index value of –1 can be used
## Accessing the last element
batsmen[-1]
# how many elements in the list
len(batsmen)
Can slicing starts from middle?
Yes, slicing can start in the middle of a sequence in Python. You can
specify the starting index to begin slicing from any position in the
sequence.
1.
my_list = [10, 20, 30, 40, 50, 60, 70]
sliced_list = my_list[3:] # Starts from index 3 (40) to the end
print(sliced_list)
2.
sliced_list = my_list[2:5] # Starts from index 2 (30) and stops at
index 5 (excluding 60)
print(sliced_list)
Two separate lists can be concatenated into one list using + operator
bowlers = [‘Hardik’, ‘Siraj’, ‘Kuldeep’, ‘Sundar’]
All_Players=Batsmen+Bowlers
All-Players
Finding if an item exists in a list or not,
the in operator can be used. It returns
True if exists, else returns False
‘Jadeja’ in Bowlers
Finding the index of an item in the list.
all_players.index(‘Ahmed’)
reverse()
• The items in a list can be arranged in reverse
order by calling reverse() function on the list
All_players.reverse()
All_players
Tuple - Built in Data Structure
Python mutability refers to being able
to change an object
Tuple : tuple_A = (item 1, item 2, item 3,…, item n)
• The primary differing characteristic between lists and tuples is
mutability
• Lists are mutable, whereas tuples are immutable
• Tuples cannot be modified, added, or deleted once they’ve
been created
• Tuples are defined by using parentheses to enclose the
elements, which are separated by commas.
Creating a Tuple
Create a tuple using parenthesis or using the
tuple() function.
#Input Appending Elements:
To append the values, you use the
my_tuple = (1, 2, 3) #create tuple ‘+’ operator which will take
another tuple to be appended to it
print(my_tuple)
#Input
my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add
elements
Output
print(my_tuple)
(1, 2, 3)
Output:
(1, 2, 3, 4, 5, 6)
Difference between List and Tuple
Mylist=[1,2,3]
Mytuple=(1,2,3)
Mylist[0]=5 Mytuple(0)=5
print(Mylist) print(Mytuple)
Sets
• Sets are a collection of unordered elements that
are unique
• If the data is repeated more than once, it will be
entered into the set only once
Creating a set
• Sets are created using the curly / flower brackets {}
• Sets are used to store multiple items in a single
variable
• A set is a collection which is unordered,
unchangeable*, and unindexed
* Note: Set items are unchangeable, but you can
remove items and add new items.
Input
The set supports
setOfNumbers = {6,1,1,2,4,5} operations such as union,
setOfNumbers intersection, and
difference.
Create a set of graduation
streams of your class
Output
{1, 2, 4, 5, 6}
Dictionary
Dictionary is a list of key and value pairs. All the keys in a
dictionary are unique.
Example:
• UDAI directory - Aadhar
Creating a Dictionary
Dictionaries can be created using the flower braces or using
the dict() function.
Create dictionaries by placing key:value pairs inside curly
brackets {}, separated by commas.
Example - 1
# Dictionary representing a few Indian states and their capitals
india_states = {
"Maharashtra": "Mumbai",
# Output: Bengaluru
"Karnataka": "Bengaluru",
"Tamil Nadu": "Chennai",
"West Bengal": "Kolkata",
"Rajasthan": "Jaipur"
}
print(india_states["Karnataka"])
Feature List Tuple Set Dictionary
Ordered ✅ ✅ ❌ ✅ (Python 3.7+)
Mutable ✅ ❌ ✅ ✅
Allows
✅ ✅ ❌ Keys: ❌, Values: ✅
Duplicates
Indexing ✅ ✅ ❌ Keys as index
Working with Libraries -Modules in Python
A module is a Python file containing functions, classes, or
variables that can be reused in other programs. Modules help
organize code efficiently.
How to import modules?
In Python, the import statement is used to import the whole
module.
How to use Python Modules?
• To incorporate the module into our program: Use
the import keyword
• To get only a few or specific methods or functions
from a module: Use the from keyword
#Example
import random
import math, random
from math import factorial
Import with renaming a module
import pandas as pd
import numpy as np
import seaborn as sns
Python Built-in Modules
To display a list of all of the available modules in
Python Programming Language:
help('modules') or help(“modules”)
pip freeze or pip list
https://www.crayondata.com/top-20-python-libraries-for-data-science/
#Example-1
import math
# Taking square root of a value
math.sqrt(16)
Output: 4.0
#Example-2
# import only factorial function from math module
from math import factorial
print(factorial(5))
#Example-1
range(), random.sample() takes the range function and
number of random numbers to be generated as parameters
Import random
RandomList=random.sample(range(0, 11), 3)
RandomList
[8, 7, 2]
#Example-2
Import random
randomList=random.sample(range(0,1000),50)
randomList
#Example-3
import random
randomList = random.sample(range(0, 100), 20)
randomList
[67, 13, 56, 19, 65, 8, 2, 28, 75, 35, 32, 16, 43, 57,
11, 81, 64, 46, 3, 6]
#Example-4
import random
# Random float number
for i in range(3):
print(random.random())
A random.random() function of a random module to
generate a random float number uniformly in the
semi-open range (0.0, 1.0).
#Example-5 - Generate a list of random floats between a range
import random
random_float_list = []
# Set a length of the list to 25
for i in range(0, 25):
x = round(random.uniform(50.50, 500.50), 2)
random_float_list.append(x)
print(random_float_list)
random.uniform() function to get a
random float number within a range.
#Example-3-Other Features
import random
randomlist=random.sample(range(240,680),20)
print(randomlist)
randomlist.reverse()
print(randomlist)
sum(randomlist)
Python List reverse() is an inbuilt method in the Python
programming language that reverses objects of the List in
place.
Syntax: list_name.reverse()
Question
Write a python program to reverse a series of numbers
and find the sum of digits in the reversed series. Input data
of 20 random numbers to be generated between the range
(20,680).
Example-1
import random
randomlist=random.sample(range(20,680),20)
print(randomlist)
randomlist.reverse()
print(randomlist)
sum(randomlist)