0% found this document useful (0 votes)
5 views19 pages

Python Programs

The document contains various Python programming tasks and examples related to student records, calculations, and class structures. It includes functions for calculating grades, averages, and handling user input, as well as creating classes for students and laptops. The document emphasizes the use of loops, conditionals, and data structures like lists, dictionaries, and sets.

Uploaded by

zainabzf098
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)
5 views19 pages

Python Programs

The document contains various Python programming tasks and examples related to student records, calculations, and class structures. It includes functions for calculating grades, averages, and handling user input, as well as creating classes for students and laptops. The document emphasizes the use of loops, conditionals, and data structures like lists, dictionaries, and sets.

Uploaded by

zainabzf098
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

Create a list of marks for at least 10 students.

Use a loop to process every mark.

Count how many students passed and failed.

Find the class average.

Print a grade for each student using if, elif, and else.

Print a final summary: total students, passed, failed, average, highest,


and lowest marks.

Add comments that explain each main step of your program. give
easy n beginer python code

# List of marks for 10 students


marks = [78, 45, 90, 67, 32, 55, 81, 49, 60, 39]

# Variables to store pass/fail counts and total marks


passed = 0
failed = 0
total = 0

# Finding highest and lowest marks


highest = marks[0]
lowest = marks[0]

# Loop through every student's marks


for i in range(len(marks)):

mark = marks[i]

# Add marks to total for average calculation


total = total + mark
# Check pass or fail
if mark >= 50:
passed = passed + 1
else:
failed = failed + 1

# Find highest mark


if mark > highest:
highest = mark

# Find lowest mark


if mark < lowest:
lowest = mark

# Assign grades using if, elif, else


if mark >= 80:
grade = "A"
elif mark >= 70:
grade = "B"
elif mark >= 60:
grade = "C"
elif mark >= 50:
grade = "D"
else:
grade = "F"

# Print student result


print("Student", i + 1)
print("Marks:", mark)
print("Grade:", grade)
print()

# Calculate class average


average = total / len(marks)

# Print final summary


print("----- Final Summary -----")
print("Total Students:", len(marks))
print("Passed Students:", passed)
print("Failed Students:", failed)
print("Class Average:", average)
print("Highest Marks:", highest)
print("Lowest Marks:", lowest)
Write a program that asks for marks and prints Pass or
Fail.

Write a program that prints the table of any number


from 1 to 10.

Create a list of five temperatures and print only the


temperatures greater than 30.

Create a list of student marks and calculate total,


average, highest mark, and lowest mark.

Write a while loop that counts from 10 down to 1.


1. Program to Check Pass or Fail
# Ask user to enter marks
marks = int(input("Enter your marks: "))

# Check pass or fail


if marks >= 50:
print("Pass")
else:
print("Fail")

2. Program to Print Table of Any Number


# Ask user for a number
num = int(input("Enter a number: "))

# Print table from 1 to 10


for i in range(1, 11):
print(num, "x", i, "=", num * i)
3. Program to Print Temperatures Greater
Than 30
# List of temperatures
temps = [25, 32, 28, 35, 40]

# Print temperatures greater than 30


for t in temps:
if t > 30:
print(t)

4. Program to Find Total, Average, Highest,


and Lowest Marks
# List of student marks
marks = [78, 45, 90, 67, 55]

# Calculate total
total = sum(marks)

# Calculate average
average = total / len(marks)

# Find highest and lowest


highest = max(marks)
lowest = min(marks)

# Print results
print("Total Marks:", total)
print("Average Marks:", average)
print("Highest Marks:", highest)
print("Lowest Marks:", lowest)

5. While Loop Counting from 10 Down to 1


# Start from 10
count = 10

# Loop until count becomes 0


while count >= 1:
print(count)
count = count - 1
Create a function named greet_teacher() that prints a
welcome message.

Create a function named add_two_numbers(a, b) that returns


the sum.

Create a function named calculate_square(number) that


returns number * number.

Create a function named is_adult(age) that returns True if age


is 18 or above.

Call each function with at least two different examples.

# Function that prints a welcome message


def greet_teacher():
print("Welcome Teacher!")
print("Have a great day.")
print()

# Function that returns the sum of two numbers


def add_two_numbers(a, b):
return a + b

# Function that returns the square of a number


def calculate_square(number):
return number * number

# Function that checks if a person is adult


def is_adult(age):
return age >= 18
# Calling greet_teacher() two times
greet_teacher()
greet_teacher()

# Calling add_two_numbers() with different examples


print("Sum 1:", add_two_numbers(5, 3))
print("Sum 2:", add_two_numbers(10, 7))
print()

# Calling calculate_square() with different examples


print("Square 1:", calculate_square(4))
print("Square 2:", calculate_square(9))
print()

# Calling is_adult() with different examples


print("Age 20 Adult?", is_adult(20))
print("Age 15 Adult?", is_adult(15))

Ask the user for student name, assignment marks, quiz marks,
and final exam marks.

Write a function to calculate total marks.

Write a function to calculate percentage.

Write a function to return grade using if, elif, and else.

Use try and except to handle invalid numeric input.


Print a clean result card with name, total, percentage, and
grade.

Add comments explaining the purpose of each function.

# Function to calculate total marks


def calculate_total(assignment, quiz, final_exam):
# Add all marks and return total
total = assignment + quiz + final_exam
return total

# Function to calculate percentage


def calculate_percentage(total):
# Total marks are assumed to be 300
percentage = (total / 300) * 100
return percentage

# Function to calculate grade


def calculate_grade(percentage):

# Check percentage and return grade


if percentage >= 80:
return "A"

elif percentage >= 70:


return "B"

elif percentage >= 60:


return "C"

elif percentage >= 50:


return "D"

else:
return "Fail"

# Try block to handle invalid input


try:

# Ask user for student name


name = input("Enter student name: ")

# Ask user for marks


assignment_marks = float(input("Enter assignment marks: "))
quiz_marks = float(input("Enter quiz marks: "))
final_exam_marks = float(input("Enter final exam marks: "))
# Call total function
total_marks = calculate_total(
assignment_marks,
quiz_marks,
final_exam_marks
)

# Call percentage function


percentage = calculate_percentage(total_marks)

# Call grade function


grade = calculate_grade(percentage)

# Print result card


print("\n------ Result Card ------")
print("Student Name:", name)
print("Total Marks:", total_marks)
print("Percentage:", percentage, "%")
print("Grade:", grade)

# Handle invalid input


except ValueError:
print("Invalid input! Please enter numeric values for marks.")

# This program has mistakes. Students should fix it.


def calculate_average(mark1, mark2, mark3)
total = mark1 + mark2 + mark3
average = total / 2
return avrage
result = calculate_average(70, 80, 90)
print("Average:", result)
# Tasks:
# 1. Fix syntax error.
# 2. Fix logic error in average formula.
# 3. Fix spelling mistake.
# 4. Add comments. Use debugging steps to fix and
improve this program.

# Program to calculate average marks


# Debugging steps were used to fix errors

# Function to calculate average of 3 marks


def calculate_average(mark1, mark2, mark3):

# Add all marks


total = mark1 + mark2 + mark3

# Divide by 3 to get correct average


average = total / 3

# Return average value


return average

# Call the function with sample values


result = calculate_average(70, 80, 90)

# Print the result


print("Average:", result)

Debugging Steps Used


1. Fixed Syntax Error
o Added : after the function definition.
2. Fixed Logic Error
o Average should be divided by 3 because there are 3 marks.
3. Fixed Spelling Mistake
o Changed avrage to average.
4. Fixed Indentation
o Proper indentation was added inside the function.
5. Added Comments
o Comments explain each important step of the program.

Ask the user for a full name and print it in title case.

Create a list of five marks and calculate total and


average.
Print only the marks greater than or equal to 80.

Create a dictionary for one student with name, roll


number, and marks.

Create a set from a list with duplicate city names and


print unique cities.
# Ask user for full name
full_name = input("Enter your full name: ")

# Convert name into title case


print("Title Case Name:", full_name.title())

# List of five marks


marks = [85, 72, 90, 67, 80]

# Calculate total marks


total = sum(marks)

# Calculate average marks


average = total / len(marks)

# Print total and average


print("\nTotal Marks:", total)
print("Average Marks:", average)

# Print marks greater than or equal to 80


print("\nMarks greater than or equal to 80:")
for mark in marks:
if mark >= 80:
print(mark)

# Create a dictionary for one student


student = {
"name": "Ali",
"roll_number": 101,
"marks": 88
}

# Print student dictionary


print("\nStudent Dictionary:")
print(student)

# List with duplicate city names


cities = ["Lahore", "Karachi", "Lahore", "Islamabad", "Karachi"]

# Create set to store unique cities


unique_cities = set(cities)

# Print unique cities


print("\nUnique Cities:")
print(unique_cities)

Build a small student record analysis program.

Create a list of at least eight student dictionaries.

Each dictionary should store name, roll number, city, and marks.

Clean each student name using strip() and title().


Calculate class average marks.

Print students who passed and students who failed.

Print all unique cities using a set.

Add comments explaining strings, lists, dictionaries, and loops in your


code.

# Student Record Analysis Program

# A list stores multiple student dictionaries


students = [
{"name": " ali ", "roll_number": 1, "city": "Lahore",
"marks": 85},
{"name": " sara ", "roll_number": 2, "city": "Karachi",
"marks": 45},
{"name": " ahmed ", "roll_number": 3, "city":
"Islamabad", "marks": 72},
{"name": " hina ", "roll_number": 4, "city": "Lahore",
"marks": 39},
{"name": " usman ", "roll_number": 5, "city": "Multan",
"marks": 91},
{"name": " fatima ", "roll_number": 6, "city": "Karachi",
"marks": 67},
{"name": " zain ", "roll_number": 7, "city":
"Faisalabad", "marks": 50},
{"name": " ayesha ", "roll_number": 8, "city":
"Islamabad", "marks": 28}
]
# Variable to store total marks
total_marks = 0

# Set stores only unique values


unique_cities = set()

# Loop is used to process each student one by one


for student in students:

# Strings can be cleaned using strip() and title()


student["name"] = student["name"].strip().title()

# Add marks to total


total_marks = total_marks + student["marks"]

# Add city into set


unique_cities.add(student["city"])

# Calculate class average


average = total_marks / len(students)

# Print class average


print("Class Average Marks:", average)

# Print passed students


print("\nPassed Students:")

for student in students:

# Dictionary stores data in key-value form


if student["marks"] >= 50:
print(
student["name"],
"- Roll No:",
student["roll_number"],
"- Marks:",
student["marks"]
)

# Print failed students


print("\nFailed Students:")

for student in students:

if student["marks"] < 50:


print(
student["name"],
"- Roll No:",
student["roll_number"],
"- Marks:",
student["marks"]
)

# Print all unique cities


print("\nUnique Cities:")
print(unique_cities)

Practice creating small classes before building larger programs.

Create a Laptop class with brand, model, and price attributes.


Create two laptop objects and print their details.
Add a method named apply_discount() that reduces the price.
Add a method named show_details() that prints a clean output.
Test your methods with at least two objects.

# Create a Laptop class


class Laptop:

# Constructor to initialize attributes


def __init__(self, brand, model, price):

# Attributes of the laptop


[Link] = brand
[Link] = model
[Link] = price

# Method to apply discount on price


def apply_discount(self, discount_amount):

# Reduce the price


[Link] = [Link] - discount_amount

# Method to show laptop details


def show_details(self):

# Print clean output


print("Laptop Brand:", [Link])
print("Laptop Model:", [Link])
print("Laptop Price:", [Link])
print()

# Create first laptop object


laptop1 = Laptop("Dell", "Inspiron", 120000)

# Create second laptop object


laptop2 = Laptop("HP", "Pavilion", 150000)

# Show original details


print("Original Laptop Details:\n")

laptop1.show_details()
laptop2.show_details()
# Apply discount
laptop1.apply_discount(10000)
laptop2.apply_discount(15000)

# Show updated details after discount


print("After Applying Discount:\n")

laptop1.show_details()
laptop2.show_details()

Create a Person class with name and age.


Create a Student class that inherits from Person.
Add roll_no and marks to Student.
Add a method named show_student_info().
Create one object and print all information.

# Parent class
class Person:

# Constructor for Person class


def __init__(self, name, age):

# Attributes of Person
[Link] = name
[Link] = age

# Child class inheriting from Person


class Student(Person):

# Constructor for Student class


def __init__(self, name, age, roll_no, marks):

# Call parent class constructor


super().__init__(name, age)
# Additional attributes of Student
self.roll_no = roll_no
[Link] = marks

# Method to display student information


def show_student_info(self):

print("Student Information")
print("-------------------")
print("Name:", [Link])
print("Age:", [Link])
print("Roll Number:", self.roll_no)
print("Marks:", [Link])

# Create object of Student class


student1 = Student("Ali", 20, 101, 88)

# Call method to print all information


student1.show_student_info()

Create a Student class with name, roll


number, marks, and attendance.
Use __init__() to initialize all values.
Create a method to calculate percentage.
Create a method to return Pass or Fail.
Create a method to print a clean student
report.
Create at least five student objects.
Use a loop to print reports for all students.
Add comments explaining attributes,
methods, and objects.
# Student Management Program using Class and Objects

# Creating Student class


class Student:

# __init__() method initializes attributes


def __init__(self, name, roll_no, marks, attendance):

# Attributes (variables of class)


[Link] = name
self.roll_no = roll_no
[Link] = marks
[Link] = attendance

# Method to calculate percentage


def calculate_percentage(self):

# Assuming total marks are 500


percentage = ([Link] / 500) * 100
return percentage

# Method to check Pass or Fail


def check_result(self):

if [Link] >= 250:


return "Pass"
else:
return "Fail"

# Method to print student report


def print_report(self):

print("----------- Student Report -----------")


print("Name:", [Link])
print("Roll Number:", self.roll_no)
print("Marks:", [Link])
print("Attendance:", [Link], "%")
print("Percentage:", self.calculate_percentage(), "%")
print("Result:", self.check_result())
print("--------------------------------------\n")

# Creating student objects


# Object = real instance of class

student1 = Student("Ali", 101, 430, 90)


student2 = Student("Sara", 102, 380, 85)
student3 = Student("Ahmed", 103, 220, 70)
student4 = Student("Ayesha", 104, 470, 95)
student5 = Student("Bilal", 105, 260, 75)

# Storing all objects in a list


students = [student1, student2, student3, student4, student5]

# Loop to print reports of all students


for student in students:
student.print_report()

You might also like