Chapter 3:
Python
Instructor: Mr. Abdul Salam Shaikh, Lecturer – IT
Input/Output in Python
Page 106
Input/Output in Python
Page 107
Data Types / Variable Types
How to convert data type ?
Operators in python
Assignment operators
Bitwise Operator
• Bitwise operators in Python work on binary (bit) level.
They compare numbers bit-by-bit.
• These operators are mostly introduced with logic gate concepts (AND, OR,
NOT, XOR).
• And Or
XOR ^
NOT ~
• ~5 = -6
• ~6 = -7
• ~2 = -3
• Formula = ~5 = -(5+1)
Left shift <<
Right Shift >>
Membership operators
Comparison Operators
Comparison operators compare two values and return True or False.
Code Level Examples
Logical Operators
Logical operators combine multiple conditions and return True or
False.
• and
• or
• not
Conditional Statements
Conditional statements are used to check a condition. If the
condition is True, a certain block of code runs; otherwise, another
block runs.
if condition:
statement(s)
if temperature > 30:
print("It's hot outside.")
Using Multiple if Statements
if–else Statement
if–elif–else Statement ( 3 possible results)
3.9 Iteration and loops
• Iteration means repeating a block of code multiple times.
• In Python, loops allow us to repeat tasks without writing repeated
code.
Why we use loops:
• Save time
• Avoid writing same code again and again
Print a message 5 times ( without loop)
Print a message 5 times ( with loop)
Loop Syntax
Part Meaning Explanation
for Loop keyword Tells Python to start a loop
Stores values one-by-one (0, 1, 2,
i Loop variable / counter
3, 4)
Keyword → tells Python where
in Membership check
values are coming from
Generates numbers from 0 to 4
range(5) Range function
(not 5)
: Colon Shows the start of the loop body
print(i) Loop body Runs for every value of i
Loop: Step by step execution
Loop repeats automatically
Now i = 1
Code runs again: print(1)
Now i = 2
print(2)
• range(5) gives numbers: 0, 1, 2, 3, 4
Now i = 3
• First value goes into i
Print (3)
• i=0
Now i = 4
• Code inside loop runs:
Print (4)
print(0) 0
print(1) 1
Print(2) 2
Print(3) 3
Print(4) 4
Loop ( Change in range) 3.22
Loop Breakdown
Part Meaning Explanation
Loop begins
11 Start value
from 11.
Loop stops
before 15
15 Stop value
(15 is not
included).
Value of i
Step /
1 increases by
Increment
1 every time.
Loop ( Change in range) 3.23
Loop: sum of first 10 Numbers (3.24)
Loop: Printing characters (Ascending Index)
Part Meaning
range(5) Loop repeats 5 times → i = 0, 1, 2, 3, 4
Increases count by 1 each time (so we
(i + 1)
get 1 star first, then 2, 3 and 4)
* Character to repeat
Multiplies * with number — prints that
(i + 1) * '*'
many stars
Loop: Printing characters (Ascending Index)
Part Meaning
Start = 5, Stop = 0
range(5, 0, -1) (excluded), Step = -1 (go
backwards)
Prints decreasing stars
i * '*'
each time
3.10: List
A List in Python is a data type that represents collection of
elements that can be:
• Of different data types
• Changeable (mutable)
• Indexed (index starts from 0)
list_name = [item1, item2, item3, ...]
i.e. my_list = [10, "apple", 3.14]
Sngl_Dgt_Odd_Nums = [1, 3, 5, 7, 9]
List: Accessing elements in list
myList= [1, 3, 5, 7, 9]
print(myList)
[1, 3, 5, 7, 9]
print(myList[2])
5
List: Basic List Function ( used in fig 3.27)
Sngl_Dgt_Odd_Nums = [1, 3, 5, 7, 9]
Function Description Example Output
len(Sngl_Dgt_Odd_Num
len() Counts total elements 5
s)
sum(Sngl_Dgt_Odd_Nu
sum() Adds all elements 25
ms)
min(Sngl_Dgt_Odd_Num
min() Finds smallest element 1
s)
max(Sngl_Dgt_Odd_Nu
max() Finds largest element 9
ms)
List: Code level Example
List: Code level Example
List: insert() and index() functions
insert() → adds a new element at a specific index.
index() → returns the index of the first occurrence of a value.
Use of randint() function
• Randint(): generate a random integer between two given numbers
from random import randint
randint(start, end)
from random import randint
x = randint(1, 10)
print(x)
Output: any random number between 1 and 10.
Use of append()
append(): To add a new element at the end of a list.
list_name.append(element)
numbers = [1, 2, 3]
[Link](4)
print(numbers)
Output: [1, 2, 3, 4]
Generating random numbers: Code level example
Create a list of 10 random numbers between 1 and 99.
Searching a number in a list
Use of membership operator in list
L = [1, 3, 5, 7]
print(5 in L)
Output: True
Try Activity 4
Take a random 2-digit number
Subtract it from 100
Print the absolute difference (magnitude only)
Page 114
Functions in Python
What is a Function?
• A function is a block of code that performs a specific task.
• Helps divide large programs into smaller, manageable parts.
• Makes code reusable and easier to understand.
• Defined using the keyword def.
Function: Function defination
def function_name():
statement(s)
• A function runs only when it is called.
def my_first_func():
print("This line is printed, when my_first_func() is called")
How to call function
my_first_func()
Function: Drawing Lines (Fig 3.32)
def draw_hline():
print('-' * 10)
def draw_vline():
print('|')
Code level example
Function: What is an Argument in Python?
• An argument is a value passed to a function when it is called.
• Functions use arguments to work with different inputs.
def draw_hline(n): function declaration
print('-' * n)
draw_hline(10)
Function: Code level example
Multiple Arguments in functions
Basic Function
Debugging
• Debugging means finding and fixing errors or bugs in a program.
• Most bugs are logical errors, where the program runs but gives
wrong output.
• Debugging helps us check values step-by-step to see where the
mistake happens.
Ways to debug
1. Debugger in IDE (Python IDLE Debugger)
2. Breakpoints
3. Python Debugger (pdb) – From Command Prompt
4. Debugging Using Print Statements
5. Assert Keyword
Debugger in IDE & Breakpoints
Assert Keyword
• To catch logical errors early
• If the condition is True → program continues normally.
• If the condition is False → Python stops the program and shows an
AssertionError.
x = 5 # initialize
x = 5 * -1 # maybe a typing error
assert x > 0
print(x)
Assert Keyword
age = int(input("Enter your age: "))
assert age >= 0
print("Your age is:", age)
If user enters 10 → condition is True → program continues.
If user enters -5 → condition fails →Program stops with
AssertionError.
Assert Keyword
• marks = int(input("Enter marks: "))
• assert 0 <= marks <= 100
• print("Marks entered:", marks)