0% found this document useful (0 votes)
7 views29 pages

Basic Python Programs and Functions

The document contains a series of basic Python programming exercises, including printing messages, performing arithmetic operations, and using data structures like lists and dictionaries. It also covers functions, user input, and basic control flow, along with examples of using the NumPy library for numerical computations. Each example includes a program, output, and sometimes additional context or requirements.

Uploaded by

A S MOHAMED ASIL
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)
7 views29 pages

Basic Python Programs and Functions

The document contains a series of basic Python programming exercises, including printing messages, performing arithmetic operations, and using data structures like lists and dictionaries. It also covers functions, user input, and basic control flow, along with examples of using the NumPy library for numerical computations. Each example includes a program, output, and sometimes additional context or requirements.

Uploaded by

A S MOHAMED ASIL
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

Date: 24/07/2025

LAB: 1 BASIC PYTHON PROGRAMS

Aim: To write basic python programs

Example Question 1: Program to print simple words

Program:

print("[Link].U4EEE24001; A.S MOHAMED ASIL")


print("Hello world")

Output:

Example Question 2: Program to add two numbers

Program:

print("[Link].U4EEE24001; A.S MOHAMED ASIL")


a = 66
b = 70
sum = a + b
print("Sum:", sum)

Output:

Example Question 3: Program to check data type

Program:

print("[Link].U4EEE24001; A.S MOHAMED ASIL")


x = 10
y = 3.14
z = "Python"
print(type(x))
print(type(y))
print(type(z))
Output:

Example Question 4: Program to swap variables

Program:

print("[Link].U4EEE24001; A.S MOHAMED ASIL")


a = 56
b = 43
a, b = b, a
print("a:", a, "b:", b)

Output:

Example Question 5: Program to perform arithmetic operations

Program:

print("[Link].U4EEE24001; A.S MOHAMED ASIL")


a = 198
b = 100
print("+:", a + b)
print("-:", a - b)
print("*:", a * b)
print("/:", a / b)
print("%:", a % b)

Output:
Example Question 6: Write a python program to display the name, age, and register no. of 5
students, and display the total of all ages.
1. Create list of five students
2. Display the sum of all ages

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
students = [
{"name": "Asil", "age": 19, "reg_no": "1001"},
{"name": "Mithin", "age": 20, "reg_no": "1002"},
{"name": "Darshan", "age": 19, "reg_no": "1003"},
{"name": "Abhishek", "age": 20, "reg_no": "1004"},
{"name": "Varshit", "age": 20, "reg_no": "1005"}
]

print("Student Details:")
for s in students:
print(f"Name: {s['name']}, Age: {s['age']}, Register No: {s['reg_no']}")

total_age = sum(s["age"] for s in students)


print("Total of all ages:", total_age)

Output:

Example Question 7: Program to use comparison operators

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
x = 10
y = 20
print("x > y:", x > y)
print("x == y:", x == y)
Output:

Example Question 8: Program to use logical operators

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
a = True
b = False
print("a and b:", a and b)
print("a or b:", a or b)
print("not a:", not a)

Output:

Example Question 9: Program to identify whether a number is even or odd

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
num = int(input("Enter a number: "))
if num == 0:
print(“enter valid number")
elif num % 2 == 0:
print("Even")
else:
print("Odd")

Output:
Example Question 10: Write a python program to display the name, register no. and grades of 3
students, and display list in order, such as the highest grade should be at top of the list.
1. Create list of 3 students
2. Display the list of students according to their grades

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
students = [
{"name": "Asil", "reg_no": "001", "grade": 85},
{"name": "Abhishek", "reg_no": "002", "grade": 88},
{"name": "Aditya", "reg_no": "003", "grade": 89}
]

for i in range(len(students)):
for j in range(i + 1, len(students)):
if students[i]["grade"] < students[j]["grade"]:
students[i], students[j] = students[j], students[i]

print("Students in order of grades (highest first):")


for s in students:
print(f"Name: {s['name']}, Reg No: {s['reg_no']}, Grade: {s['grade']}")

Output:

Example Question 11: Program to identify whether a number is positive, negative or zero

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
for I in range(5):
num = int(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Output:

Example Question 12: Program to identify largest of three numbers

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
a = int(input("Enter 1st: "))
b = int(input("Enter 2nd: "))
c = int(input("Enter 3rd: "))
if a >= b and a >= c:
print("Largest:", a)
elif b >= c:
print("Largest:", b)
else:
print("Largest:", c)

Output:

Example Question 13: Program print number from 1 to 10 using for loop

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
for i in range(1, 11):
print(i)

Output:
Example Question 14: Program print first n natural numbers using while loop

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
n = int(input("Enter n: "))
i=1
while i <= n:
print(i)
i += 1

Output:

Example Question 15: Program print sum of n natural numbers

Program:

print("[Link].U4EEE24001; A.S MOHAMED ASIL")


n = int(input("Enter n: "))
total = 0
for i in range(1, n+1):
total += i
print("Sum:", total)

Output:
Example Question 16: Program to check whether a number is prime number or not

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
for i in range(2):
num = int(input("Enter a number: "))
is_prime = True
if num < 2:
is_prime = False
else:
for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
if is_prime:
print("Prime")
else:
print("Not Prime")

Output:

Example Question 17: Program for a simple calculator

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
for i in range(5):
a = float(input("Enter 1st: "))
b = float(input("Enter 2nd: "))
op = input("Enter operator: ")
if op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(a / b)
else:
print("Invalid operator")
Output:
Example Question 18: Program to calculate shopping discount

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
purchase = float(input("Enter a purchase amount: "))
if purchase > 1000:
discount = purchase * 0.10
else:
discount = 34
final_amount = purchase - discount
print("Discount:", discount)
print("Final:", final_amount)

Output:

Example Question 19: Program to assign grades

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
for i in range(5):
score = int(input("Enter a score: "))

if score >= 90:


grade = "A"
elif score >= 75:
grade = "B"
elif score >= 50:
grade = "C"
elif score >= 35:
grade = "P"
else:
grade = "F"
print("Grade:", grade)

Output:

Example Question 20: Program for a simple ATM system

Program:

print("[Link].U4EEE24001; A.S MOHAMED ASIL")


balance = 999
withdraw = int(input("Withdraw amount: "))
if withdraw > balance:
print("Insufficient balance")
elif withdraw % 100 != 0:
print("Multiple of 100 only")
else:
balance -= withdraw
print("New balance:", balance)

Output:
Example Question 21: Program to calculate even-odd sum

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
n = int(input("Enter number of inputs "))
even_sum = 0
odd_sum = 0
for i in range(n):
num = int(input(f"Enter {i+1}: "))
if num % 2 == 0:
even_sum += num
else:
odd_sum += num
print("Even sum:", even_sum)
print("Odd sum:", odd_sum)

Output:

Example Question 22: Program for a simple login screen

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
username = input("Username: ")
password = input("Password: ")
if username == "User" and password == "666":
print("Login successful")
else:
print("Invalid credentials")

Output:

Date: 07/08/2025
LAB: 2 PROGRAMS ON FUNCTIONS

Aim: To write python programs using functions

Example Question 1: Students performance tracker with functions


1. Accept name, reg number and marks in 3 subjects for 3 students
2. Use a function to calculate total and average
3. Print each student's details along with their average
4. Display the student with the highest average

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
def accept_student_data():
students = []
for i in range(3):
print(f"\nEnter details for Student {i+1}:")
name = input("Name: ")
reg_no = input("Registration Number: ")
marks = []
for j in range(3):
mark = float(input(f"Enter marks for Subject {j+1}: "))
[Link](mark)
[Link]({
"name": name,
"reg_no": reg_no,
"marks": marks
})
return students

def calculate_total_and_average(student):
total = sum(student["marks"])
average = total / len(student["marks"])
student["total"] = total
student["average"] = average

def display_students(students):
print("\n--- Students Details ---")
for student in students:
calculate_total_and_average(student)
print(f"Name: {student['name']}, Reg No: {student['reg_no']}, Marks: {student['marks']},
Average: {student['average']:.2f}")

def display_topper(students):
topper = max(students, key=lambda s: s["average"])
print("\n--- Topper ---")
print(f"Name: {topper['name']}, Reg No: {topper['reg_no']}, Average: {topper['average']:.2f}")

students_list = accept_student_data()
display_students(students_list)
display_topper(students_list)

Output:
Example Question 2: Program for functions with arguments

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
def greet(name):
print(f"Hello, {name}!")
greet("Bob")

Output:

Example Question 3: Program on function with return value

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
def add(a, b):
return a + b
result = add(10, 5)
print("Sum:", result)

Output:

Example Question 4: Program on function with default argument

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
def greet(name = "Guest"):
print(f"Hello, {name}!")
greet()
greet("John")

Output:

Example Question 5: Program on function with keyboard arguments

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
student_info(age=20, name="Ravi")

Output:

Example Question 6: Program on function returning multiple values

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
def calculate(a, b):
sum_ = a + b
product = a * b
return sum_, product
s, p = calculate(4, 5)
print("Sum:", s)
print("Product:", p)

Output:
Example Question 7: Program on using *args for variable number of arguments

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
def total_sum(*numbers):
return sum(numbers)
print(total_sum(1, 2, 3))
print(total_sum(5, 10, 15, 20))

Output:

Date: 14/08/2025
LAB: 3 PROGRAMS ON NUMPY

Aim: To write python programs using numpy

Example Question 1: Program to calculate sum of array of numbers

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
def sum_array(arr):
return [Link](arr)
numbers = [Link]([10, 20, 30, 40])
print("Sum:", sum_array(numbers))

Output:

Example Question 2: A shop owner stores daily sales amounts for a week in an array. Write a
function to calculate the total sales for the week using numpy
1. Get user input
2. Create a sales interface in output window
3. Display all sales and total sales for the week

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np

def total_sales(sales_array):
return [Link](sales_array)

def average_sales(sales_array):
return [Link](sales_array)

print("=" * 40)
print(" Weekly Sales Entry ")
print("=" * 40)

sales = []
for i in range(7):
amount = float(input(f"Enter sales for Day {i+1}: ₹"))
[Link](amount)

sales_array = [Link](sales)
total = total_sales(sales_array)
average = average_sales(sales_array)

print("\n" + "=" * 40)


print(" Sales Summary ")
print("=" * 40)
for i, amount in enumerate(sales, start=1):
print(f"Day {i}: ₹{amount:.2f}")
print("-" * 40)
print(f"Total Sales for the Week : ₹{total:.2f}")
print(f"Average Daily Sales : ₹{average:.2f}")
print("=" * 40)

Output:
Date: 21/08/2025
LAB: 4 PROGRAMS ON NUMPY

Aim: To write python programs using numpy

Example Question 1: Program to calculate mean and standard deviation

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
def stats(arr):
return [Link](arr), [Link](arr)
data = [Link]([1, 2, 3, 4, 5])
mean, std_dev = stats(data)
print("Mean:", mean, "Std dev:", std_dev)

Output:

Example Question 2: Teacher records students scores in an exam.


1. Create score data for 5 students and 3 subjects
2. Write a function to calculate the average score and standard deviation to understand performance
variation.

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
scores = [Link]([
[85, 78, 92],
[88, 74, 90],
[72, 81, 79],
[95, 89, 94],
[68, 76, 80]
])
def calculate_average(scores):
return [Link](scores, axis=1)
def calculate_std(scores):
return [Link](scores, axis=1)
avg_scores = calculate_average(scores)
std_devs = calculate_std(scores)
print("=== Student Performance ===")
for i in range(len(scores)):
print(f"Student {i+1}: Scores = {scores[i]}, "
f"Average = {avg_scores[i]:.2f}, "
f"Std Dev = {std_devs[i]:.2f}")

Output:

Example Question 3: Program for element wise multiplication

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
def multiply_array(arr1, arr2):
return [Link](arr1, arr2)
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print("Product:", multiply_array(a, b))

Output:
Example Question 4: A warehouse has 10 products with quantites and prices stored in two arrays
1. Write a function to calculate the total cost of each item by multiplying corresponding elements
2. Display product name, quantity and price in user window

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
products = [Link](["Rice", "Sugar", "Wheat", "Oil", "Milk",
"Eggs", "Biscuits", "Tea", "Coffee", "Butter"])
quantities = [Link]([5, 12, 8, 20, 15, 10, 6, 14, 9, 11])
prices = [Link]([100, 50, 75, 30, 120, 60, 45, 80, 25, 150])
def calculate_total_cost(qty, price):
return qty * price
total_costs = calculate_total_cost(quantities, prices)
print("=" * 55)
print(f"{'Product':12} {'Quantity':>10} {'Price(Rs)':>10} {'Total(Rs)':>12}")
print("=" * 55)
for i in range(len(products)):
print(f"{products[i]:12} {quantities[i]:10d} {prices[i]:10.2f} {total_costs[i]:12.2f}")
print("=" * 55)
print(f"{'Grand Total':>34} {[Link](total_costs):12.2f}")
print("=" * 55)

Output:

Example Question 5: Program to normalize an array

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
def normalize(arr):
return (arr - [Link](arr)/([Link](arr) - [Link](arr)))
scores = [Link]([40, 50, 40, 55, 90])
print("Normalized:", normalize(scores))

Output:

Example Question 6: Program to find even numbers

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
def find_even(arr):
return arr[arr % 2 == 0]
nums = [Link]([1, 2, 3, 4, 5, 6, 10, 90, 30, 99, 32, 123])
print("Even numbers:", find_even(nums))

Output:

Example Question 7: A sensor produces an array of readings. You need to extract only even
numbered readings for further processing
1. Write a function to achieve this
2. To extract the data for a machine learning model that process the sensor data, all input data to be
between 10 and 150
3. Write a function to normalize a dataset using numpy

Program:
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
import numpy as np
def extract_even_readings(readings):
return readings[readings % 2 == 0]
def filter_range(readings, low=10, high=150):
return readings[(readings >= low) & (readings <= high)]

def normalize_data(data):
return (data - [Link](data)) / ([Link](data) - [Link](data))

sensor_readings = [Link]([5, 12, 18, 33, 145, 200, 88, 132, 7, 151, 149])

print("Original readings:", sensor_readings)


even_readings = extract_even_readings(sensor_readings)
print("Even readings:", even_readings)
filtered_readings = filter_range(even_readings)
print("Filtered readings (10-150):", filtered_readings)
normalized = normalize_data(filtered_readings)
print("Normalized readings (0 to 1):", normalized)

Output:

LAB: 5 OOPS(class)

Program:1
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
class Car:
def __init__(self, brand, color):
[Link] = brand
[Link] = color

def drive(self):
print(f"The {[Link]} {[Link]} is driving")

car1 = Car("Toyota", "Red")


car2 = Car("Tesla", "Blue")
[Link]()
[Link]()

Output:

Program:2
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
class Student_list:
def __init__(self, name, reg_no, year, dept):
[Link] = name
self.reg_no = reg_no
[Link] = year
[Link] = dept

def details(self):
print(f"Name: {[Link]}, [Link]: {self.reg_no}, Year: {[Link]}, Dept: {[Link]}")
s1 = Student_list("Abhishek", "21", "Year-2", "ECE")
s2 = Student_list("Ritika", "14", "Year-2", "ECE")
s3 = Student_list("Arjun", "09", "Year-2", "ECE")
s4 = Student_list("Sana", "33", "Year-2", "ECE")
[Link]()
[Link]()
[Link]()
[Link]()

Output:

Program:3
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
class BankAccount:
def __init__(self, name, account_number, balance=0.0):
[Link] = name
self.account_number = account_number
[Link] = balance

def display_details(self):
print("\n--- Account Details ---")
print(f"Name: {[Link]}")
print(f"Account Number: {self.account_number}")
print(f"Balance: ₹{[Link]:.2f}")

def deposit(self, amount):


if amount > 0:
[Link] += amount
print(f"\n₹{amount:.2f} deposited successfully!")
else:
print("\nDeposit amount must be positive.")

def withdraw(self, amount):


if amount > [Link]:
print("\nInsufficient balance!")
elif amount <= 0:
print("\nWithdrawal amount must be positive.")
else:
[Link] -= amount
print(f"\n₹{amount:.2f} withdrawn successfully!")

def check_balance(self):
print(f"\nCurrent Balance: ₹{[Link]:.2f}")

# --- Main Program ---


def main():
print(" Welcome to SBI")
name = input("Enter your name: ")
account_number = input("Enter your account number: ")

account = BankAccount(name, account_number)

while True:
print("\nChoose an option:")
print("1. Display Account Details")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Check Balance")
print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == '1':
account.display_details()
elif choice == '2':
amount = float(input("Enter amount to deposit: ₹"))
[Link](amount)
elif choice == '3':
amount = float(input("Enter amount to withdraw: ₹"))
[Link](amount)
elif choice == '4':
account.check_balance()
elif choice == '5':
print("\nThank you for banking with us!")
break
else:
print("\nInvalid choice! Please select a valid option.")

if __name__ == "__main__":
main()

Output:
LAB: 6 String Manipulations

Program:1
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#Concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)

Output:

Program:2
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#String Slicing
text = "Hello, World!"
print(text[0:5])
print(text[-6:-1])

Output:
Program:3
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#Changing Case
text = "Python Programming"
print([Link]())
print([Link]([Link]())
print([Link]())

Output:

Program:4
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#Strip Whitespace
text = " Hello, Python! "
print([Link]()) # Output: Hello, Python!
print([Link]()) # Output: Hello, Python!__
print([Link]()) # Output: ___Hello, Python!

Output:

Program:5
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#Find and Replace
text = "I love C. C is awesome!"
print([Link]("C"))
print([Link]("C", "python"))

Output :

Program:6
Exercise:- Q1. Execute a python program to get the first name, second name, and date of
birth(DD/MM/YY) of the user and display in uppercase and print the date of birth in reverse
order(YY/MM/DD).

first_name = input("Enter your first name: ")


second_name = input("Enter your second name: ")
dob = input("Enter your Date of Birth (DD/MM/YY): ")
first_name = first_name.upper()
second_name = second_name.upper()
day, month, year = [Link]('/')
reversed_dob = f"{year}/{month}/{day}"
print("\n--- User Details ---")
print(f"First Name: {first_name}")
print(f"Second Name: {second_name}")
print(f"Date of Birth (reversed): {reversed_dob}")

Output

Program:7
#Splitting and Joining Strings
text = "apple,banana,cherry"
fruits = [Link](",")
print(fruits)
new_text = "-".join(fruits)
print(new_text)

Output

Program:8
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#Check for Substring
sentence = "Learning Python is fun!"
print("Python" in sentence)
print("Java" not in sentence)

Output

Program:9
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#String Formatting
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output

Program:9
print("[Link].U4EEE24001; A.S MOHAMED ASIL")
#Count Occurrences
text = "banana"
print([Link]("a"))

Output

You might also like