Python Class 2025
Chapter# 1
Introduction to Programming
What is Computer program?
• A computer program is set of instructions written using
a computer language to perform a specific task by the
computer
• Examples
• MS word a
• MS excel
• MS power point
• Adobe photoshop
• Interne explorer
• Chrome
World’s first programmer
What is computer language?
• A computer language is a language used to write instructions
that a computer can understand and execute.
• Purpose:
Understanding how humans communicate with computers
• Example:
Python, C++, Java etc etc…
What is a programming Language ?
• A programming language is a set of instructions used to communicate with a
computer.
• Just like we speak English, Urdu, or Pashto to communicate with people, we use
programming languages to give commands to a computer so it can perform
tasks.
• These tasks can range from simple things like adding two numbers to complex
tasks like creating video games or running websites.
• Examples of Programming Languages Programming languages are used to write
software or programs:
• Python – print("Hello, World!")
• C++ – cout << "Hello";
• Java – [Link]("Hello");
What is a language processor?
A language processor is a type of software that translates Source •
Code written in high level language into machine code so that
computer can understand.
Language processor
Source code Machine Code
Exe File
Examples : C++,JAVA C#
A compiler checks the whole program first, then tells you all the errors it
found.
Examples : Python , PHP
Interpreters help you find errors faster — especially when
you’re learning or testing small pieces of code.
What is Python?
Python is a high-level programming •
language that is easy to read and write,
even for beginners.
High-level means it’s close to human •
language (English-like), not just 0s and 1s.
Programming language means it’s a set of •
rules to tell a computer what to do.
Python is a widely used high-level language for •
general-purpose programming
History of Python
The programming language Python is named
after the British sketch comedy series "Monty
Python's Flying Circus."
When Guido van Rossum, the creator of
Python, was developing the language, he was
also reading the published scripts from the
show. He sought a name that was concise,
distinctive, and slightly enigmatic, and he
found "Python" to be a fitting choice.
Python Latest Version is 3.14
What is Python Used For?
Top companies working in Python
Chapter#2
GETTING STARTED WITH PYTHON
You must create a folder in which you
can save all python related files
Steps:
1. Open Visual Studio
2. cntrl+N
3. Save the file first → cntrl +S
4. save the file with [Link]
extension
If run python file 🔼 button is not showing on top right corner
then double click here and click on accept
2nd program
Print ( “ my name is Ahmad “) •
Print (“ what is your name ?”) •
Print(“ my name is Ahmad”,”what is your name”)➔ it prints in single line •
Print (80) •
Print (90+90) •
32
Adding Newlines
To add a newline in a string, use the character
combination \n:
print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript
what is the purpose of Code in Python?
Input → process→ output •
Example Google •
34
Python Syntax & Comments
Enter key is used to end the statement
Don’t use Indentation (space or tab at left side)
Comments
Some Special Characters used
in python programs
1. () → parenthesis
2. “ “→ double quote
3. # → hash for comments
If we miss some symbols in
syntax it gives error
Benefits of Comments
• Easy to Understand Code
• Comments help explain what each part of the code is doing. This makes it easier for you
(or someone else) to understand the code later.
• Helps in Debugging
• You can temporarily "turn off" parts of your code by commenting them out while testing
or fixing errors.
• Better Teamwork
• If you're working in a group, comments help your friends or classmates understand your
logic.
• Remind Yourself
• If you come back to your code after a few days or weeks, comments will help you
remember what you wrote and why.
36
Python Benefits
• Easy to learn and understand
• Simple and readable syntax
• Free and open-source
• Cross-platform (Windows, Mac, Linux)Large
community support
• Rich standard library
• Supports multiple programming styles
• Widely used in:
37
Programming Errors
Programming errors can be categorized into three types:
1. syntax errors
2. runtime errors
3. logic errors
1. Syntax Errors
A syntax error means that you broke the rules of the Python
language while writing your code.
Syntax Error = Problem in writing
Example
print("Hello“ ➔ you forgot the symbol “)”
If you see a "Syntax Error" in your code,
carefully check:
Spelling
Brackets [], ()
Colons :
Indentation
2. Runtime errors
A runtime error is an error that happens while the program
is running.
It means your code is written correctly (no syntax error), but
something goes wrong when the program runs.
Runtime Error = Problem while running
Example
a = 10
b=0
print(a / b)
Common Runtime Errors:
[Link] by zero
[Link] a variable that doesn't exist
The syntax is correct, but when you run it, Python will give [Link] to open a file that isn’t
this error: there
Because you can't divide any number by zero — it crashes [Link] type used in math (e.g.,
adding a string to a number)
while running.
3. Logic Error
a = 10
A logical error is when: b = 20
c = 30
✅ The code runs
average = a + b + c / 3
✅ No error is shown print("Average is:", average)
❌ But the result is wrong Output:
Average is: 20.0
because the logic (thinking) is incorrect. Because the math or logic is not
correct, even if the code is.
Python doesn’t know your logic is wrong — only you can find it.
Chapter#3
Variables / data types / operators
Variables and data types
• Variable is name given to a memory location in a program
• Name=“khan” ➔ string data
• Age=30 ➔ integer data
• Price=5.9 ➔ float data Variables names on memory location
Name age price
Khan 30 5.9
Print(name)
Print (age) String data Float data
Print(price)
variable
Print “myname is “,name) Integer data
43
Data types of Variables
1. Integer data type ➔ whole number (0-9) positive or negative values
2. String Data type➔ collection of character is called String
3. Float data type ➔ decimal number ➔ 3.9 or 2.5 etc…
4. Boolean data type ➔ It contain True or False
5. none
44
String data type
• The collection of character is called string
• It is written in sinlge double or triple quote
• Example
• Name1=“khan”
• Name2 =‘jan’
• Name3 =“’ zakir”’
• Print (name1)
• Print(name2)
• Print(name3)
• ➔ “khan,zakir,jan” is a string
45
Examples
• Name=“khan”
• Age=50
• Marks=90.5
• Print(type(name)
• Print(type(marks)
• Print(type(marks)
46
Floats
Python calls any number with a decimal point a float.
0.1 + 0.1
0.2
0.2 + 0.2
0.4
2 * 0.1
0.2
2 * 0.2
0.4
Integers and Floats
When you divide any two numbers, even if they are integers that result in a whole number, you will always
get a float:
4/2
2.0
If you mix an integer and a float in any other operation, you will get a float as well:
1 + 2.0
3.0
2 * 3.0
6.0
3.0 ** 2
9.0
Rules for Naming Variables
1. Variable names can contain only letters, numbers, and underscores.
2. They can start with a letter or an underscore, but not with a
number. For instance, you can call a variable message_1 but not
1_message.
3. Spaces are not allowed in variable names, but underscores can be
used to separate words in variable names. For example,
greeting_message works, but greeting message will cause errors.
4. Variable names should be short but descriptive. For example, name
is better than n, student_name is better than s_n, and
name_length is better than length_of_persons_name.
49
Variable Declaration Variable Initialization
x X=7
y Y=2
A=x+y
Operators
• an operator is a symbol that performs an action on
one or more values (called operands)
• Example
• A=3
• B=60
• Sum=a+b
• ➔ here (=,+) are operators
• ➔ a and b are operand
51
1. Arithmetic Operators
Arithmetic Operators are used to
perform operation on data
For example
1. + Addition
2. - Subtraction
3. / Division
4. * Multiplication
5. ** Exponentiation (Power)
6. //Floor division
7. % Modulus ( reminder)
Float Division
2. Membership Operator ( “In” , “Not in”)
• Membership operators are used to test if a sequence is presented in
an object:
Python is Case Sensitive
Order of Operations
• You can use parentheses to modify the order of operations so Python can evaluate
your expression in the order you specify.
2+3*4
Output:
14
(2 + 3) * 4
Output:
20
3. Assignment Operator (=)
Assignment Operator is used to assign any value to a variable
Multiple assignment operators
There are 8 Assignment operators
Multi assignment Operators
________________________________
1. = Assignment Operator
2. += Addition Assignment Operator
3. -= Subtraction Assignment Operator
4. *= Multiplication assignment Operator
5. /= division Assignment Operator
6. **= exponential Assignment operator
7. //= float division assignment operator
8. %= Modulus assignment operator
4. Comparison Operators
Comparison Operator is used to compare values.
Comparison Operators
The result will be Boolean it means two either
== equal to
True or False
!= not equal to
> Greater than
< Less than
<= Greater than or equal to
>= Less than or equal to
5. Logical Operators ( Boolean Operators)
Logical Operators are used express logic The result will
be Boolean it means two either True or False
1. Logical Operators
2. And
3. Or
4. not
6. Boolean Data type
• Boolean data in Python is a data type that represents only two
values: True or False
• Boolean data is used to represent yes/no, true/false, on/off
conditions.
• The Boolean values in Python are True and False (note the
capital letters).
• Boolean Data comes from
• Membership operator
• Logical operators
• Comparison operators
Use of Built-in function type()
The type() function is a built-in function in Python. It helps us find out what type of value
something is.
type() tells what kind of thing
something is.
Type Casting ( type conversion)
Type Conversion and Type Casting are basically the same
thing.
Both mean changing one data type into another.
Example: turning a word into a number, or a number into a
word.
Type Casting = Type Conversion = Changing things so Python
can understand it.
For Type Casting we use Int(), Float() and Str() functions
63
# Example 1: float to int
num = 9.8
converted = int(num)
print(converted) # Output: 9 (decimal part is dropped)
# Example 2: string to int
s = "100"
converted = int(s)
print(converted + 50) # Output: 150
# Example 3: int to string
age = 25
text = "I am " + str(age) + " years old"
print(text) # Output: I am 25 years old
You manually used int() or str() to change the type.
64
1. Implicit Typecasting (Automatic)
•Python changes the type [Link] gniksa tuohtiw
[Link] Typecasting (Manual)
You tell Python exactly what type to change.
Input function is used to take the data from users while program is running
67
Chapter #4
Working with Strings
String Concatenation
String concatenation means combing or adding strings together.
Use + character to add strings together
x = “Hello Python Class”
y = “Python is fun”
z=x+y
print(z)
Use + character to add strings together
message = “Hello Python Class” + “Python is fun”
print(message)
Repeating Strings
We can use * Operator to repeat a string multiple times.
message = “Hello World”
print(message * 10)
Strings Built-in methods (functions)
• The collection of character or symbol is called string
• In python string built in methods are also called string functions
• String functions are those functions which are applied on strings
• Strigs are written inside double quote “”
capitalize ()
lower()
upper()
len()
strip()
replace()
startwith()
ends with()
capatilize() method
The capitalize() method returns a string where the first
character is uppercase and the rest is lower.
message = “welcome to python class”
print([Link]())
The first character is converted to uppercase and the rest are
converted to lowercase.
upper() and lower() methods
The upper() method returns a string where all characters are
in uppercase.
message = “my favorite programming language is python”
print([Link]())
The lower() method returns a string where all characters are
in lowercase.
message = “PYTHON IS FUN”
print([Link]())
len() method
• The len() method returns the length of a string.
message = “python is fun”
print(len(message))
strip() method
• The strip() method removes any leading and trailing whitespaces.
• Leading means at the beginning of the string, trailing means at the
end.
fruit = " apple “
message = "my favorite fruit is" + [Link]()
print(message)
replace() method
• The replace() method is used to replace the contents of a string.
message = "I like python and python is a great language"
replaced_message = [Link](“python", “C++")
Print(replaced_message)
• An optional parameter is the number of items that will be replaced.
message = “Hello world world”
replaced_message = [Link](“World”, ”People”, 2)
print(replaced_message)
startswith() method
• The startswith() method returns True if the string starts with the specified
value, otherwise False.
message = “Hello, welcome to python class"
x = [Link](“Hi")
print(x)
False
endswith() method
• The endswith() method returns True if the string ends with the specified value, otherwise
False.
url_string = “ [Link] ”
check_url = url_string.endswith (“ .com “)
print(check_url)
Python Input function
Chapter # 5
Working with list
Working with List
• A list is a collection of items in a particular order. used to store multiple
items in a single variable.
• In Python, square brackets ([]) indicate a list, and individual elements in the list are
separated by commas.
Syntax list_name = [item1, item2, item3, ...]
fruits = ["apple", "banana", "cherry"]
example print(fruits)
output ['apple', 'banana', 'cherry']
List examples
Adding Elements to a List
To add an item to the end of the list, use the append() method.
favorite_sports = [‘cricket’, ‘football’, ‘tennis’, ‘badminton’]
print(favorite_sports)
favorite_sports.append("Karate")
print(favorite_sports)
Removing an Element from a list
Use the remove() method to remove a specified element from a list
my_list = ['apples’, 'bananas’, 'mangoes’, 'cherry']
print(my_list)
my_list.remove(‘mangoes')
print(my_list)
Forward Accessing
• To access an element in a list, write the name of the list followed by the
index number of the item enclosed in square brackets.
favorite_fruits = [‘apples’, ‘bananas’, ‘mangoes’, ‘cherry’]
print(favorite_fruits[0])
Positive indexing is called forward acccesing
Backward Accessing
Python has a special syntax for accessing the last element in a list. By
asking for the item at index -1, Python always returns the last item in
the list:
favorite_fruits = [‘apples’, ‘bananas’, ‘mangoes’, ‘cherry’]
print(favorite_fruits[-1])
Negative indexing is called backward accessing
Changing (replacing) Elements in a List
To change an element, use the name of the list followed by the index of
the element you want to change, and then provide the new value you
want that item to have.
friends = [‘Ahmad’, ‘Khan’, ‘Hamza’]
print(friends)
friends[0] = ‘Musa’
print(friends)
Inserting Elements in a list
Use the insert() method to insert an element at a specified index.
my_list = ['apples’, 'bananas’, 'mangoes’, 'cherry']
print(my_list)
my_list.insert(2, 'oranges')
print(my_list)
Slice a list
Slice means to show list items in the form of range or in a
specific range
Here we use (:) symbol
For example (start:end)
my_list = ['apples’, 'bananas’, 'mangoes’, 'oranges’,
'pineapples’]
my_list(start:end)
Start : the index where you want to start slicing
Stop: the index where you want to stop slicing
Using membership operators in list
In , not in
What is tuple?
A tuple in Python is like a list, but it cannot be changed after you
create it.
Think of it like a sealed box — you can look at the items inside, but
you can’t add, remove, or change them.
Syntax my_tuple = (item1, item2, item3) output
exmaple fruits = ("apple", "banana", "cherry")
print(fruits)
('apple', 'banana', 'cherry')
91
Tuple
Chapter # 6
Conditional Statements
Conditional Statements
A conditional statement in programming is a decision-making
structure that runs certain code only if a specified condition is True.
It’s like telling the computer:
"If this happens, do this… otherwise, do something else."
In Python, the main conditional statements are:
if → runs code if the condition is true.
elif → checks another condition if the first one is false.
else → runs code if none of the conditions are true.
Syntax
if condition:
# code if condition is true
elif another_condition:
# code if second condition is true
else:
# code if all above conditions are false
95
If Statement
An if statement executes the statements if the condition is true.
The statement(s) must be indented at least one space to the right of the if keyword
and each statement must be indented using the same number of spaces.
a = 33
b = 200
if b > a:
print(“b is greater than a")
Else statment
Example
age = 18
if age > 18: Output
print("Adult")
elif age == 18:
print("Just became an
adult")
else:
print("Minor") Just became an adult
98
Logical operators
Equals to: ==
Not Equals: !=
Less than: <
Less than or equal to: <=
Greater than: >
Greater than or equal to: >=
If Statement
An if statement executes the statements if the condition is true.
The statement(s) must be indented at least one space to the right of the if keyword
and each statement must be indented using the same number of spaces.
a = 33
b = 200
if b > a:
print(“b is greater than a")
If else Statement
An if-else statement decides which statements to execute based on whether the condition
is true or false
x = 20
if x % 2 == 0:
print(x, ‘ is even number')
else:
print(x, ‘ is odd number')
Elif Statement
score = 30
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print("Your grade is:", grade)
Nested if
Loops
Loop
A loop is like a set of instructions that repeat over and over until
a certain condition is met.
For Loop
A loop in programming is a structure that repeats a block of code multiple
times until a certain condition is met or for a fixed number of times.
In simple words — instead of writing the same code again and again, you
put it inside a loop, and the computer repeats it for you.
Types of loop
for loop – repeats for each item in a sequence.
while loop – repeats as long as a condition is True
General syntax of for loop
for variable in sequence:
Example Output
for x in range(5): 0
print(x) 1
2
3
4
107
While Loops
A while loop in Python is a loop that repeats a block of code as long
as a given condition is True.
General Syntax while condition:
Example Output
count = 1 1
while count <= 5: 2
print(count) 3
count += 1 4
5
Break
We use the break statement with the loop to terminate the loop when a
certain condition is met.
for i in range(10):
if i == 7:
break
print(i)
Postfix and prefix
Type Placement Example What Happens
Increment first,
Prefix Before value ++x
then use
Use value first,
Postfix After value x++
then increment
Postfix increment is used in java and C++ it is not available in Python
110
Continue
The continue statement is used to skip the current repeating of the loop
and the control flow of the program goes to the next iteration.
for i in range(10):
if i == 3:
continue
print(i)
Functions
Understanding Functions
A function is like a mini-program inside your code. It’s a block of code that
does a specific task.
Instead of writing the same code again and again, you write it once inside a
function, and then call the function whenever you need it.
def greet():
print("Hello! Welcome to Python.")
greet()
greet()
Creating a Function
How to Create a Function in Python
1. Use the def keyword
2. 2. Give your function a name
3. 3. Use parentheses ()
4. 4. Add a colon :
5. 5. Write the code inside (indented)
def say_hello():
print("Hello, world!")
Call a Function
you can call it by writing its name followed by parentheses ().
def say_hello():
print("Hello!")
----------------------------- call a function----------------------------
say_hello()
Print Function
The print() function prints the specified message to the screen.
print("how are you?")
Return Keyword
return is used in a function to give back an answer.
You can store this answer in a variable or use it in another calculation.
example
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Simple Key Differences
• print shows things on the screen
• return gives back a result that you can use later
Local variable and global variable
A local variable is created inside a function and can be used only inside
that function.
def my_function():
x = 10 # local variable
print(x)
A global variable is created outside of all functions and
can be used anywhere in the program.
y = 5 # global variable
def my_function():
global y
y = y + 10
print(y) # Can read and change y
my_function() # Output: 15
print(y) # Output: 15
119
Python Practical
Practical 1 Question
Write a script to display “Hello World!! “On console.
Practical 1 Solution
# Use the print function to display "Hello World!!"
print("Hello World")
Practical 2 Question
The electricity bills for the last three months have been
23000, 32000 and 64000.
What is the average monthly electricity bill over the three-
month period?
Write an expression to calculate the mean, and use print()
to view the result.
Practical 2 Solution
# Given electricity bills for the last three months
bill_1 = 23000
bill_2 = 32000
bill_3 = 64000
# Calculate the average (mean) bill
average_bill = (bill_1 + bill_2 + bill_3) / 3
# Print the result
print(average_bill)
Practical 3 Question
Write a script to calculate the area of circle. (Area of Circle: 𝐴
= 𝜋𝑟2 ).
Practical 3 Solution
# Assign a value to radius
radius = 20
# Compute area
area = radius * radius * 3.14159
# Display results
print ("The area for the circle of radius", radius, "is", area)
Practical 4 Question
Write a script that Count all letters, digits, and special symbols
from a given string.
inputString = "P@#yn26at^&i5ve"
text= input(" enter any text:\n\n")
letters = 0
digits = 0
symbols = 0
for char in text:
if [Link]():
letters+=1
elif [Link]():
digits+=1
else:
symbols+=1
print(" total letters =",letters)
print(" total digits =",digits)
print(" total symbols =",symbols))
Practical 6 Question
Write a script to split a given string on hyphens and display each
substring.
inputString = Bareera-is-a-data-scientist
Practical 6 Solution
inputstring="bareera_is_a_data_scientist"
substrings=[Link]('_')
for substring in substrings:
print(substring)
Practical 7 Question
Write a script to check whether a number entered by user is
even or odd.
Practical 7 Solution
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"The number {number} is Even.")
else:
print(f"The number {number} is Odd.")
Practical 8 Question
Write a script to check whether a number is divisible by 7 or
not.
Practical 8 Solution
number = int(input('Enter a number: ‘))
if number % 7 == 0:
print(f"{number} is divisible by 7.")
else:
print(f"{number} is not divisible by 7.")
Practical 9 Question
Write a script to take score from a user between (1 and 100)
and display its grade according to score.
(Score: 1-50 Grade: Average)
(Score: 51-70Grade: Good)
(Score: 71-100 Grade: Excellent)
Practical 9 Solution
if score >= 1 and score <= 50:
print("Your grade is: Average")
elif score >= 51 and score <= 70:
print("Your grade is: Good")
elif score >= 71 and score <= 100:
print("Your grade is: Excellent")
elif score < 1 or score > 100:
print("Please enter a score between 1 and 100")
Practical 10 Question
Write a script to print first 10 natural numbers using loop
(while, for).
Practical 10 Solution
Using for loop:
for number in range (1, 11):
print(number)
Using while loop:
count = 1
while count <= 10:
print(count)
count = count + 1
Practical 11
Write a program in python to add 2 number in run time
139
Write a program in python to find square of a
number
# Find square of a number
num = int(input("Enter a number: "))
square = num * num
print("The square of", num, "is", square)
140
What is Python library?
A library in Python is a collection of ready-made code that we can use to do different
tasks easily without writing it ourselves.
Library Name Use / Purpose
Turtle Drawing shapes, graphics, and patterns
Working with numbers, arrays, and
NumPy
mathematical calculations
Making charts, graphs, and
Matplotlib
visualizations
Creating graphical user interface (GUI)
Tkinter
applications
Django Building websites and web applications
Pandas is a Python library that helps us store,
Panda organize, and work with data easily, like
rows and columns in a table.
Making simple games and multimedia
PyGame
programs141
Python Turtle Graphics
What is Turtle in Python?
Turtle is a toolkit which provides simple and enjoyable way to draw pictures on
Screen or Window.
It is developed for Kids
142
Write a program to print circle on screen?
import turtle
# Screen setup
wn = [Link]()
[Link]("Move the Circle")
[Link]("lightyellow")
[Link](width=600, height=600)
# Create the circle
player = [Link]()
[Link]("circle")
[Link]("blue")
[Link](3) # make bigger
[Link]()
# Movement
def move_up():
[Link]([Link]() + 20)
def move_down():
[Link]([Link]() - 20)
def move_left():
[Link]([Link]() - 20)
def move_right():
[Link]([Link]() + 20)
# Keyboard controls
[Link]()
[Link](move_up, "Up")
[Link](move_down, "Down")
[Link](move_left, "Left")
[Link](move_right, "Right")
143
[Link]()