CPG101
Module 1 & 2
Dr. Snehal B Shinde
Computer Science and Engineering
Indian Institute of Information Technology, Nagpur.
1
17-06-2025
Day 1
Python Overview
• Developed during 1985- 1990 by Guido van Rossum.
• Python is a interpreted, general-purpose (Multipurpose), and High Level
Programming Language.
Source Code Machine Code
Python Overview
• Developed during 1985- 1990 by Guido van Rossum.
• Python is a interpreted, general-purpose (Multipurpose), and High Level
Programming Language.
Python Overview
• Developed during 1985- 1990 by Guido van Rossum.
• Python is an interpreted, general-purpose (Multipurpose), and High Level
Programming Language.
Python Overview
• Like Perl, Python source code is also available under the GNU General Public
License (GPL).
• Intuitive and minimal coding is required and dynamically typed, type
declarations is not required, data type is tracked at runtime.
• Automatic memory management.
• Spacing (Indentation) defines blocks of code such as control structures and
blocks.
Python Overview
• Python allows programming in Object-Oriented and Procedural paradigms.
• Python programs generally are smaller than other programming languages
like Java.
• To download Python for windows click here.
• Python is Hybrid Language (Compiled and Interpreted)
• To see the bytecode of program
1. import py_compile
2. py_compile.compile('[Link]')
3. '__pycache__\\[Link]'
Verify the python installation
• To ensure if Python is successfully installed on your system. Follow the given
step
1. Open the command prompt
2. Type python and press enter.
3. The version of the python which you have installed will be displayed if the
python is successfully installed on your windows
Types of modes in IDLE editor
• IDLE Interactive Shell :
• IDLE interactive shell is shows the (>>>) symbol
• Interactive shell runs simple Python expressions and statements in a Shell
Types of modes in IDLE editor
• IDLE editor to run scripts- Python IDLE editor for scripting
What is IDE?
• IDE stands for Integrated Development Environment
• It enables programmers to consolidate the different aspects of writing a
computer program
• Features of IDE
1. Syntax Highlighting
2. Auto-complete
3. Debugging
4. Builds the code
What is IDE?
• Top Python IDEs & Code Editors: Download for Free & Paid
• PyCharm
• Spyder
• Dreamweaver
• IDLE
• Sublime Text 3
• Visual Studio Code
• Atom
• Jupyter
• Pydev
• Thonny
Jupyter Notebook
• Web interface to Python, introduced in 2015
• Rich text, improved graphical capabilities
• Integrate many existing web libraries for data visualization
• Allow to create and share documents that contain live code, equations,
visualizations and explanatory text.
• Interface with over 40 languages, such as R, Julia and Scala
An Introduction To Google Colab
• What is Colab?
• Colab, or "Colaboratory", allows you to write and execute Python in your
browser, with
• Zero configuration required
• Access to GPUs free of charge
• Easy sharing
An Introduction To Google Colab
Python Identifiers
• An identifier is a name given to entities like class, functions, variables, etc.
• It helps to differentiate one entity from another.
• 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.
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. An identifier can be of any length.
Variable
1. Variable type in Python is dynamically determined from the value it is
assigned, no data type is declared
2. Assign meaningful variable names
3. Some keywords are reserved such as ‘print’, ‘assert’, ‘while’, ‘lambda’, 'for',
'if', etc
import keyword
kwd=[Link]
print(len(kwd))
print(kwd)
Variable
• The following identifiers are used as reserved words, or keywords of the
language, and cannot be used as ordinary identifiers.
• All the keywords except True, False and None are in lowercase and they must
be written as they are.
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
• A variable is assigned a value using the ‘=’ operator, example: a = 5
Python Statement, Indentation and Comments
• Python Statement:
• Instructions that a Python interpreter can execute are called statements.
• if statement, for statement, while statement.
• Multi-line statement:
• In Python, the end of a statement is marked by a newline character.
• we can use to extend the statement to multi line.
Python Indentation
name = 'Rahul'
Output:
if name == 'Rahul':
print('Welcome Rahul..')
Welcome Rahul..
print('How are you?')
How are you?
else:
Have a great day!
print('Dude! whoever you are ')
print('Why you here?')
print('Have a great day!')
Python Comments
Single line comment
• In Python, we use the hash (#) symbol to start writing a comment.
# This is single line comment Output:
# That will print Hello Hello
print("Hello")
Python Comments
• Multi line comment
• Another way of doing this is to use triple quotes, either "“”
"""
This is a multi-line comment Output:
print("Hello world")
print("Hello universe") Hello campers
print("Hello everyone")
"""
print("Hello campers")
Rules and Naming Convention for Variables and
constants
• Constant and variable names should have a combination of letters in lowercase
(a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_)
• Create a name that makes sense
• If you want to create a variable name having two words, use underscore to
separate them
• Use capital letters possible to declare a constant
• Don’t start a variable name with a digit
my_name, student_marks
#example of constant
PI
SPEED_OF_LIGHT
Python Variables, Constants and Literals
Variables:
• A variable is a named location used to store data in the memory
• We can think variables as a container
number = 1
number = 1.1
website = " [Link] .in “ Output:
#Assigning multiple values to multiple variables 5
a , b , c = 5 , 3.2 , "Hello“ 3.2
print(a) Hello
print(b) <class 'int'>
print(c) <class 'float'>
print(type(a)) <class 'str'>
print(type(b))
print(type(c))
Python Variables, Constants and Literals
Variables:
• A variable is a named location used to store data in the memory
• We can think variables as a container
x=10
print(x,id(x),type(x)) Output:
x=50
print(x,id(x),type(x)) 10 135974612304400 <class 'int'>
x="IIITN" 50 135974612305680 <class 'int'>
print(x,id(x),type(x)) IIITN 135973911877808 <class 'str'>
y=x IIITN 135973911877808 135973911877808
print(x,id(x),id(y))
Taking Input
• Taking input is a way of interact with users, or get data to provide some
result.
• Python provides a built-in method to read the data from the keyboard.
1. input(prompt)
Taking Input
m=input("Enter first number") OUTPUT:
n=input("Enter second number") Enter first number5
print(m+n) Enter second number10
510
OUTPUT:
a=int(input("Enter 1st Number: ")) Enter 1st Number: 10
b = int(input("Enter 2nd Number: ")) Enter 2nd Number: 20
print(a+b) 30
Key takeaways
• When input() function executes program flow will be stopped until the user
has given input.
• The text or message displayed on the output screen to ask a user to enter
an input value is optional i.e. the prompt, which will be printed on the
screen is optional.
• Whatever you enter as input, the input function converts it into a string. if
you enter an integer value still input() function converts it into a string.
• You need to explicitly convert it into an integer in your code using
typecasting.
Literals
• Literals in Python is defined as the raw data assigned to variables or
constants while programming.
• Python literals also known as constants are quantities/ notations whose
value does not change during the execution of a program.
• Python has different types of literals
1. Numeric Literals
2. String Literals
3. Boolean Literals
4. Special Literals
1. Numeric Literals
• They are immutable (unchangeable) and there are three types of numeric
literal
1. Integer
2. Float
3. Complex
• Decimal- It contains digits from 0 to 9. The base for decimal values is 10.
• Binary- It contains only two digits- 0 and 1. The base for binary values is 2 and
prefixed with “0b”.
• Octal- It contains the digits from 0 to 7. The base for octal values is 8. In Python,
such values are prefixed with “0o”.
• Hexadecimal- It contains digits from 0 to 9 and alphabets from A to F and
prefixed as "0x".
1. Numeric Literals
• They are immutable (unchangeable) and there are three types of numeric
literal
1. Integer
2. Float
3. Complex
1. #Integer Literals
a = 0b100 #Binary Literal
b = 99 #Decimal Literal
c = 0o170 #Octal Literal (64+56) Output:
d = 0x10a #Hexadecimal Literal (256+10)
print(a, b, c, d) 4 99 120 266
print(int("422", 5)) 112
#Converting 422 in base 5 number system to integer
in decimal 4*25+ 2*5+ 2
1. Numeric Literals
• They are immutable (unchangeable) and there are three types of numeric
literal
1. Integer
2. Float
3. Complex
• Float literals decimal points and are primarily of two types-
1. Fractional- Fractional literals contain both whole numbers and decimal points.
2. Exponential- Exponential literals in Python are represented in the powers of 10.
The power of 10 is represented by e or E. An exponential literal has two parts-
the mantissa and the exponent.
• Mantissa-The digits before the symbol E in an exponential literal is known as the
mantissa. In computing, it denotes the significant digits of the floating-point numbers.
• Exponent- The digits after the symbol E in an exponential literal are the exponent. It
denotes where the decimal point should be placed.
1. Numeric Literals
• They are immutable (unchangeable) and there are three types of numeric
literal
1. Integer
2. Float
3. Complex
#Float Literals Output:
f = 9.8
g = 2.3e3 # 1e3 is equivalent to 1×103. 253700.0
print(2.537E5) 9.8 2300.0
print(f, g)
1. Numeric Literals
• They are immutable (unchangeable) and there are three types of numeric
literal
1. Integer
2. Float
3. Complex
• Complex literals are represented by A+Bj.
• A is the real part.
• And the entire B part, along with j, is the imaginary or complex part. j here
represents the square root of -1, which is nothing but the iota
#Complex Literals Output:
h = 2 + 3.14j
print(h) (2+3.14j)
print(complex(2, 3.14)) (2+3.14j)
2. Boolean Literals
• There are only two Boolean literals in Python.
• They are True and False
x = (1 == True)
y = (0 == False)
z = (2 == False) Output:
r = (3 == True)
a = True + 10 x is True
b = False + 10 y is True
print("x is", x) z is False
print("y is", y) r is False
print("z is", z) a: 11
print("r is", r) b: 10
print("a:", a)
print("b:", b)
3. String Literals
• Enclose the text or the group of characters in single, double or triple quotes.
char = 'S‘
Name = "Snehal B Shinde"
st="Welcome \ Output:
to \
IIITN \ S Snehal B Shinde Welcome to IIITN
Nagpur" #multi line literal Nagpur Residential block, IIIT Nagpur
Address_Mul = """Residential block, IIIT Nagpur Campus,
Campus, Flat 902, Butibori
Flat 902, Butibori""" # multi line literal
print(char ,Name, st, Address_Mul)
3. String Literals: String Methods
• Enclose the text or the group of characters in single, double or triple
quotes.
1. len(name) ==== Function
2. [Link]() ==== Method
3. [Link]()==== Method
4. [Link]()===== Each letter capital
5. "abcadab".count('a') =====mention character to be counted
6. [Link](), [Link]()========= Removes space
7. [Link]()======Removes both left and right
3. String Literals: String Methods
• Enclose the text or the group of characters in single, double or triple
quotes.
1. len(name) ==== Function
2. [Link]() ==== Method
3. [Link]()==== Method
4. [Link]()===== Each letter capital
5. "abcadab".count('a') =====mention character to be counted
6. [Link](), [Link]()========= Removes space
7. [Link]()======Removes both left and right
3. String Literals: String Methods
name="SNehal Shinde" Output:
print(len(name))
print([Link]()) 13
print([Link]()) snehal shinde
print([Link]()) SNEHAL SHINDE
print([Link]('S')) Snehal Shinde
name=" Snehal " 2
print(name) Snehal
print([Link]()) Snehal
print([Link]()) Snehal
print([Link]()) Snehal
4. Special Literals
• Python contains one special literal (None)
• It defines the NULL variable
• If ‘None’ is compared with anything else other than a ‘None’, It will return
false
Operators in Python:
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Arithmetic Operators in Python
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 second
/ x/y
(10/3=3.333)
// Division (floor): divides the first operand by the second (10//3=3) x // y
Modulus: returns the remainder when the first operand is divided
% x%y
by the second
** Power: Returns first raised to power second x ** y
Operators in Python:
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Comparison Operators
It either returns True or False according to the condition.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
Greater than or equal to True if the left operand is greater than or
>= x >= y
equal to the right
Less than or equal to True if the left operand is less than or equal
<= x <= y
to the right
Operators in Python:
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Logical Operators in Python
It is used to combine conditional statements.
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x
Operators in Python:
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Bitwise Operators in Python
• Python Bitwise operators act on bits and perform bit-by-bit operations.
• These are used to operate on binary numbers.
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
Operators in Python:
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Operator Description Syntax
= Assign the value of the right side of the expression to the left side operand x=y+z
+= Add AND: Add right-side operand with left-side operand and then assign to left operand a+=b a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b a=a-b
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a*=b a=a*b
/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b a=a/b
%= Modulus AND: Takes modulus using left and right operands and assign the result to left operand a%=b a=a%b
//= Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operand a//=b a=a//b
**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a**=b a=a**b
&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b
|= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left operand a <<= b a= a << b
Operators in Python:
Types of Operators in Python
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Operators in Python:
Identity Operators in Python
is True if the operands are identical
is not True if the operands are not identical
Membership Operators in Python
in True if value is found in the sequence
not in True if value is not found in the sequence
Python if...else Statement
• Decision making is required when we want to execute a code only if a certain
condition is satisfied.
• The if. . . elif. . . else statement is used in Python for decision making.
if condition:
# body of if statement
##if
if 10 > 5:
print('7 is Greater') OUTPUT:
print(7*7) 7 is Greater
print(3+5) 49
8
Python if...else Statement
• Decision making is required when we want to execute a code only if a certain
condition is satisfied.
• The if. . . elif. . . else statement is used in Python for decision making.
if condition:
# block of code if condition is True
else:
# block of code if condition is False
number = 10
if number > 0:
print('Positive number') OUTPUT:
else: Positive number
print('Negative number') This statement is always executed
print('This statement is always executed')
Python if...else Statement
Python if...elif...else Statement
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Python if...else Statement
Python if...elif...else Statement
number = 0
if number > 0:
OUTPUT:
print("Positive number")
Zero This statement is always
elif number == 0:
executed
print('Zero')
else:
print('Negative number')
print('This statement is always executed')
Python if...else Statement
Python Nested if statements number = 5
# outer if statement
if (number >= 0):
# outer if statement # inner if statement
if condition1: if number == 0:
# statement(s) print('Number is 0')
# inner if statement # inner else statement
if condition2: else:
# statement(s) print('Number is positive')
# outer else statement
else:
print('Number is negative')
OUTPUT:
Number is positive
Iteration Statement (Repeating statements)
•Loops are used to repeat a block of code.
• There are 2 types of loops in Python:
1. for loop : It is used to iterate over any sequences such as list, tuple, string.
for val in sequence:
# statement(s)
range()
• The Python range() allows the user to generate a series of numbers within
a given range.
• The most common use of it is to iterate sequence on a sequence of
numbers using Python loops.
• Syntax: range(start, stop, step)
Python range() function takes can be initialized in 3 ways.
• range (stop) takes one argument. (the user will get a series of numbers
that starts at 0 )
• range (start, stop) takes two arguments. (to generate a series of numbers
from X to Y using range(X, Y).)
• range (start, stop, step) takes three arguments.
range()
# print first 5 integers OUTPUT:
# using python range() function 0
for i in range(5): 1
print(i) 2
3
4
OUTPUT:
# using python range() function 1
for i in range(1, 7): 2
print(i) 3
print() 4
5
6
OUTPUT:
##for using range 3
for i in range(3,12,2): 5
print(i) 7
9
11
Python for Loop
Friends = ['Sagar', 'snehal','Amol', 'Roshan', OUTPUT:
'Akshay', 'Sachin'] Sagar : 5 : SAGAR
for i in Friends: snehal : 6 : SNEHAL
print(i,":", len(i),":", [Link]()) Amol : 4 : AMOL
Roshan : 6 : ROSHAN
Akshay : 6 : AKSHAY
Sachin : 6 : SACHIN
Python while Loop
• Python while loop is used to run a block code until a
certain condition is met.
• The syntax of while loop is: while condition:
# body of while loop
# program to display numbers from 1 to 5
OUTPUT:
# initialize the variable 1
i = 1 2
n = 5 3
# while loop from i = 1 to 5 4
while i <= n: 5
print(i)
i = i + 1
Python While loop with else
• In Python, a while loop may have an optional else block.
• Here, the else part is executed after the condition of the loop evaluates to
False.
counter = 0
while counter < 3: OUTPUT:
print('Inside loop') Inside loop
counter = counter + 1 Inside loop
else: Inside loop
print('Inside else') Inside else
Python While loop with else
• In Python, a while loop may have an optional else block.
• Here, the else part is executed after the condition of the loop evaluates to
False.
i = 0
while i < 3: OUTPUT:
print(i) 0
i += 1 1
else: 2
print(0) 0