0% found this document useful (0 votes)
2 views20 pages

50 Python Programs

Uploaded by

Shakila Khan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views20 pages

50 Python Programs

Uploaded by

Shakila Khan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

50 Python Programs

With Code and Verified Output

Unit 2: Python Programming


Topics: Basics & Variables • Operators • Conditional Statements • Loops • Functions, Modules & Lists

Every program below has been run and its output verified.
Contents
Section 1: Python Basics, Comments & Variables (Programs 1–10)
Section 2: Operators (Arithmetic, Comparison, Assignment, Logical) (Programs 11–20)
Section 3: Conditional Statements (if, if-else, if-elif-else) (Programs 21–32)
Section 4: Loops (while Loop and for Loop) (Programs 33–42)
Section 5: Functions, Modules, Libraries & Lists (Programs 43–50)
Section 1: Python Basics, Comments & Variables

Program 1: Print a simple welcome message


Topic: Basic Python Syntax (print function)
Code:
print("Welcome to Python Programming!")

Output:
Welcome to Python Programming!

Program 2: Display single-line and multi-line comments


Topic: Python Comments
Code:
# This is a single-line comment
print("K2 is the second-highest mountain in the world")

"""
This is a multi-line comment.
It can span multiple lines.
"""
print("Edhi Foundation is the largest volunteer ambulance network.")

Output:
K2 is the second-highest mountain in the world
Edhi Foundation is the largest volunteer ambulance network.

Program 3: Create and display variables of different types


Topic: Variables and Data Types
Code:
age = 17
price = 19.99
name = "Ali"
is_student = True

print("Age (int):", age, "| Type:", type(age))


print("Price (float):", price, "| Type:", type(price))
print("Name (str):", name, "| Type:", type(name))
print("Is Student (bool):", is_student, "| Type:", type(is_student))

Output:
Age (int): 17 | Type: <class 'int'>
Price (float): 19.99 | Type: <class 'float'>
Name (str): Ali | Type: <class 'str'>
Is Student (bool): True | Type: <class 'bool'>
Program 4: Take user's name and age and greet them
Topic: Input/Output Operations
Code:
# Simulating input since this runs non-interactively
user_name = "Ahmad"
user_age = "20"
print("Hello, " + user_name + "! You are " + user_age + " years old.")

Output:
Hello, Ahmad! You are 20 years old.

Program 5: Concatenate strings using the print function


Topic: String concatenation / I/O
Code:
age = 71
print("Ahmad lived for", age, "years")
age = 60
print("Iqbal lived for", age, "years")

Output:
Ahmad lived for 71 years
Iqbal lived for 60 years

Program 6: Handle integer input and display it


Topic: Type Casting (int())
Code:
user_age = int("25") # simulating int(input("Enter your age: "))
print("Your age is:", user_age)

Output:
Your age is: 25

Program 7: Handle float input and display it


Topic: Type Casting (float())
Code:
user_height = float("1.75") # simulating float(input(...))
print("Your height is", user_height, "meters")

Output:
Your height is 1.75 meters

Program 8: Demonstrate variable naming rules (valid vs reserved)


Topic: Variable Naming Rules
Code:
_age = 18
student_name = "Sara"
Age = 21 # different from 'age' due to case sensitivity
age = 17

print("_age =", _age)


print("student_name =", student_name)
print("Age =", Age, "| age =", age, "(case-sensitive, different
variables)")

Output:
_age = 18
student_name = Sara
Age = 21 | age = 17 (case-sensitive, different variables)

Program 9: Swap two variables without a third variable


Topic: Variables / Assignment
Code:
a = 5
b = 10
print("Before swap: a =", a, ", b =", b)
a, b = b, a
print("After swap: a =", a, ", b =", b)

Output:
Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5

Program 10: Display Python's basic data types together


Topic: Data Types Summary
Code:
my_int = 10
my_float = 3.14
my_str = "Python"
my_bool = False

print("Integer:", my_int)
print("Float:", my_float)
print("String:", my_str)
print("Boolean:", my_bool)

Output:
Integer: 10
Float: 3.14
String: Python
Boolean: False
Section 2: Operators (Arithmetic, Comparison, Assignment,
Logical)

Program 11: Perform all arithmetic operations on two numbers


Topic: Arithmetic Operators
Code:
a, b = 10, 3
print(a, "+", b, "=", a + b)
print(a, "-", b, "=", a - b)
print(a, "*", b, "=", a * b)
print(a, "/", b, "=", a / b)
print(a, "//", b, "=", a // b)
print(a, "%", b, "=", a % b)
print(a, "**", b, "=", a ** b)

Output:
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 // 3 = 3
10 % 3 = 1
10 ** 3 = 1000

Program 12: Calculate the area and perimeter of a rectangle


Topic: Arithmetic Operators
Code:
length = 12
width = 5
area = length * width
perimeter = 2 * (length + width)
print("Rectangle: length =", length, ", width =", width)
print("Area =", area)
print("Perimeter =", perimeter)

Output:
Rectangle: length = 12 , width = 5
Area = 60
Perimeter = 34

Program 13: Convert temperature from Celsius to Fahrenheit


Topic: Arithmetic Operators / Expressions
Code:
celsius = 28
fahrenheit = (celsius * 9 / 5) + 32
print(celsius, "Celsius =", fahrenheit, "Fahrenheit")

Output:
28 Celsius = 82.4 Fahrenheit

Program 14: Calculate simple interest


Topic: Arithmetic Operators
Code:
principal = 5000
rate = 4.5
time = 3
simple_interest = (principal * rate * time) / 100
print("Principal:", principal, "| Rate:", rate, "% | Time:", time, "years")
print("Simple Interest =", simple_interest)

Output:
Principal: 5000 | Rate: 4.5 % | Time: 3 years
Simple Interest = 675.0

Program 15: Demonstrate all comparison (relational) operators


Topic: Comparison Operators
Code:
x, y = 10, 5
print(x, ">", y, "=", x > y)
print(x, "<", y, "=", x < y)
print(x, "==", y, "=", x == y)
print(x, "!=", y, "=", x != y)
print(x, ">=", y, "=", x >= y)
print(x, "<=", y, "=", x <= y)

Output:
10 > 5 = True
10 < 5 = False
10 == 5 = False
10 != 5 = True
10 >= 5 = True
10 <= 5 = False

Program 16: Check if two numbers are equal


Topic: Comparison Operators
Code:
num1 = 25
num2 = 25
if num1 == num2:
print(num1, "and", num2, "are equal")
else:
print(num1, "and", num2, "are not equal")

Output:
25 and 25 are equal

Program 17: Demonstrate all assignment operators


Topic: Assignment Operators (compound)
Code:
a = 10
print("a =", a)
a += 5
print("a after += 5:", a)
a -= 3
print("a after -= 3:", a)
a *= 2
print("a after *= 2:", a)
a /= 4
print("a after /= 4:", a)
a **= 2
print("a after **= 2:", a)

Output:
a = 10
a after += 5: 15
a after -= 3: 12
a after *= 2: 24
a after /= 4: 6.0
a after **= 2: 36.0

Program 18: Demonstrate logical operators (and, or, not)


Topic: Logical Operators
Code:
age = 20
has_id = True

print("age > 18 and has_id:", (age > 18) and has_id)


print("age > 18 or has_id:", (age > 18) or has_id)
print("not has_id:", not has_id)

Output:
age > 18 and has_id: True
age > 18 or has_id: True
not has_id: False

Program 19: Check eligibility to vote using logical operators


Topic: Logical Operators
Code:
age = 19
is_citizen = True

if age >= 18 and is_citizen:


print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Output:
You are eligible to vote.

Program 20: Calculate the average of three numbers


Topic: Arithmetic Operators
Code:
n1, n2, n3 = 85, 90, 78
average = (n1 + n2 + n3) / 3
print("Numbers:", n1, n2, n3)
print("Average =", average)

Output:
Numbers: 85 90 78
Average = 84.33333333333333
Section 3: Conditional Statements (if, if-else, if-elif-else)

Program 21: Check if a number is positive, negative, or zero


Topic: if-elif-else Statement
Code:
num = -7
if num > 0:
print(num, "is positive")
elif num < 0:
print(num, "is negative")
else:
print(num, "is zero")

Output:
-7 is negative

Program 22: Check if a number is even or odd


Topic: if-else Statement
Code:
number = 17
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")

Output:
17 is odd

Program 23: Check if a number is even or odd (short-hand if-else)


Topic: Short-Hand if-else Statement
Code:
number = 8
result = "even" if number % 2 == 0 else "odd"
print(number, "is", result)

Output:
8 is even

Program 24: Determine weather advice based on condition


Topic: if-elif-else Statement
Code:
weather = "rainy"
if weather == "sunny":
print("Wear sunglasses")
elif weather == "rainy":
print("Take an umbrella")
else:
print("Enjoy your day!")

Output:
Take an umbrella

Program 25: Grade calculator based on marks


Topic: if-elif-else Statement
Code:
marks = 72
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "F"
print("Marks:", marks, "-> Grade:", grade)

Output:
Marks: 72 -> Grade: B

Program 26: Check if a number is divisible by both 3 and 5


Topic: if-else with Logical Operators
Code:
num = 30
if num % 3 == 0 and num % 5 == 0:
print(num, "is divisible by both 3 and 5")
else:
print(num, "is not divisible by both 3 and 5")

Output:
30 is divisible by both 3 and 5

Program 27: Find the largest of three numbers


Topic: if-elif-else Statement
Code:
a, b, c = 23, 67, 45
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Among", a, b, c, "-> Largest is", largest)

Output:
Among 23 67 45 -> Largest is 67

Program 28: Check eligibility for a driving license (age-based)


Topic: if-else Statement
Code:
age = 16
if age >= 18:
print("You are eligible for a driving license.")
else:
print("You are not eligible. Wait", 18 - age, "more year(s).")

Output:
You are not eligible. Wait 2 more year(s).

Program 29: Classify BMI category


Topic: if-elif-else Statement
Code:
weight = 68 # kg
height = 1.7 # meters
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
print("BMI:", round(bmi, 2), "-> Category:", category)

Output:
BMI: 23.53 -> Category: Normal weight

Program 30: Check if a year is a leap year


Topic: if-elif-else Statement
Code:
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")

Output:
2024 is a leap year

Program 31: Ticket price calculator based on age category


Topic: if-elif-else Statement
Code:
age = 65
if age < 5:
price = 0
elif age < 18:
price = 5
elif age < 60:
price = 10
else:
price = 6
print("Age:", age, "-> Ticket price: $" + str(price))

Output:
Age: 65 -> Ticket price: $6

Program 32: Check vowel or consonant using short-hand if-else


Topic: Short-Hand if-else Statement
Code:
letter = "e"
result = "vowel" if [Link]() in "aeiou" else "consonant"
print("'" + letter + "' is a", result)

Output:
'e' is a vowel
Section 4: Loops (while Loop and for Loop)

Program 33: Print even and odd numbers from 1 to 20 using while loop
Topic: while Loop
Code:
number = 1
print("Even numbers:", end=" ")
while number <= 20:
if number % 2 == 0:
print(number, end=" ")
number += 1
print()

number = 1
print("Odd numbers:", end=" ")
while number <= 20:
if number % 2 != 0:
print(number, end=" ")
number += 1
print()

Output:
Even numbers: 2 4 6 8 10 12 14 16 18 20
Odd numbers: 1 3 5 7 9 11 13 15 17 19

Program 34: Add 1 to a number until it reaches 10 (basic while loop)


Topic: while Loop
Code:
number = 1
while number < 10:
print(number)
number += 1

Output:
1
2
3
4
5
6
7
8
9

Program 35: Calculate the sum of numbers from 1 to 100 using while loop
Topic: while Loop
Code:
total = 0
num = 1
while num <= 100:
total += num
num += 1
print("Sum of 1 to 100 =", total)

Output:
Sum of 1 to 100 = 5050

Program 36: Print even numbers from 2 to 10 using for loop and range()
Topic: for Loop with range()
Code:
for number in range(2, 11, 2):
print(number, end=" ")
print()

Output:
2 4 6 8 10

Program 37: Print the first 10 multiples of 3 using for loop and range()
Topic: for Loop with range()
Code:
for i in range(1, 11):
print(3 * i, end=" ")
print()

Output:
3 6 9 12 15 18 21 24 27 30

Program 38: Say "Hello" to each friend in a list of friends


Topic: for Loop (iterating over a list)
Code:
friends = ["Ahmad", "Ali", "Hassan"]
for friend in friends:
print("Hello,", friend)

Output:
Hello, Ahmad
Hello, Ali
Hello, Hassan

Program 39: Calculate the factorial of a number using a for loop


Topic: for Loop
Code:
n = 5
factorial = 1
for i in range(1, n + 1):
factorial *= i
print("Factorial of", n, "=", factorial)

Output:
Factorial of 5 = 120

Program 40: Generate the Fibonacci series up to 10 terms


Topic: while Loop
Code:
a, b = 0, 1
count = 0
print("Fibonacci series:", end=" ")
while count < 10:
print(a, end=" ")
a, b = b, a + b
count += 1
print()

Output:
Fibonacci series: 0 1 1 2 3 5 8 13 21 34

Program 41: Print the multiplication table of a number using for loop
Topic: for Loop with range()
Code:
num = 7
for i in range(1, 11):
print(num, "x", i, "=", num * i)

Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Program 42: Count down from 10 to 1 using a while loop


Topic: while Loop
Code:
counter = 10
while counter >= 1:
print(counter, end=" ")
counter -= 1
print("\nLiftoff!")

Output:
10 9 8 7 6 5 4 3 2 1
Liftoff!
Section 5: Functions, Modules, Libraries & Lists

Program 43: Define a function to greet a person


Topic: Defining and Invoking Functions
Code:
def greet(name):
print("Hello,", name)

greet("Ali")
greet("Sara")

Output:
Hello, Ali
Hello, Sara

Program 44: Define a function to add two numbers (with return value)
Topic: Function Parameters and Return Values
Code:
def add(a, b):
return a + b

result = add(15, 27)


print("15 + 27 =", result)

Output:
15 + 27 = 42

Program 45: Define a function with a default parameter


Topic: Default Parameters
Code:
def greet(name="Student"):
return "Hello " + name + "!"

print(greet())
print(greet("Umer"))

Output:
Hello Student!
Hello Umer!

Program 46: Define a function that returns the maximum value from a list
Topic: Functions + Lists (Class Activity from notes)
Code:
def find_max(numbers):
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest

nums = [12, 45, 3, 89, 27]


print("List:", nums)
print("Maximum value:", find_max(nums))

Output:
List: [12, 45, 3, 89, 27]
Maximum value: 89

Program 47: Use the random library to generate a random number


Topic: Importing and Using Libraries (random)
Code:
import random
number = [Link](1, 10)
print("The random number is:", number)

Output:
The random number is: 2
Note: Output will vary each time you run this program, since it generates a random number.

Program 48: Use the statistics library to calculate the mean


Topic: Importing and Using Libraries (statistics)
Code:
import statistics
data = [23, 45, 67, 89, 12, 44, 56]
mean_value = [Link](data)
print("Data:", data)
print("The mean value is:", mean_value)

Output:
Data: [23, 45, 67, 89, 12, 44, 56]
The mean value is: 48

Program 49: Create, modify, and use built-in methods on a list


Topic: Lists (creating, accessing, modifying, append, sort)
Code:
fruits = ["Mango", "Apple", "Banana"]
print("Original list:", fruits)
fruits[0] = "Orange"
[Link]("Pineapple")
print("After modifying:", fruits)

students = ["Ahmed", "Sara", "Ali"]


[Link]("Hina")
[Link]()
print("Sorted students list:", students)

Output:
Original list: ['Mango', 'Apple', 'Banana']
After modifying: ['Orange', 'Apple', 'Banana', 'Pineapple']
Sorted students list: ['Ahmed', 'Ali', 'Hina', 'Sara']

Program 50: List slicing, concatenation, and remove operation


Topic: List Operations (slicing, concatenation, remove)
Code:
numbers = [1, 2, 3, 4, 5]
slice_part = numbers[1:4]
extra_numbers = [6, 7]
combined = slice_part + extra_numbers
print("Original list:", numbers)
print("Sliced [1:4]:", slice_part)
print("Combined with [6, 7]:", combined)

student_names = ["Ahmed", "Sara", "Ali", "Hina"]


student_names.sort()
student_names.remove("Sara")
print("Sorted & 'Sara' removed:", student_names)

Output:
Original list: [1, 2, 3, 4, 5]
Sliced [1:4]: [2, 3, 4]
Combined with [6, 7]: [2, 3, 4, 6, 7]
Sorted & 'Sara' removed: ['Ahmed', 'Ali', 'Hina']

You might also like