What is Function?
Question-1
Assist Mrs. Johnson in simplifying her task by creating a function to
compute the class's average score. Mrs. Johnson meticulously assessed each
student's test and compiled their individual scores. As a conscientious
teacher, she intends to determine the class's average score to evaluate
their collective performance.
class_scores = [85, 92, 78, 69, 73, 88, 94, 80, 87, 90]
total_score = sum(class_scores)
total_students = len(class_scores)
average_score_class = total_score/total_students
print(f"The average score of the class is: {average_score_class:.2f}")
Question-2
During an exciting school sports event, students demonstrated their
impressive speed and agility on the track. Write a concise Python code
using the built-in function min() to promptly identify the athlete who
achieved the shortest race time.
import operator
race_times = { "John": 10.82, "Emily": 11.05, "Michael": 10.91, "Sophia": 11.25, }
if not race_times:
winner = "No athletes recorded their race times."
else:
winner = min(race_times.items(), key=operator.itemgetter(1))[0]
print(f"The winner is: {winner}")
Question-3
Picture yourself as an English teacher engaging in an enjoyable language
exercise with your students. Now, let's craft a program that demonstrates
how to utilize Python's count() function to determine the quantity of
vowels within a given word.
word = "Hello World I am here"
vowel_count = 0
word_lower = word.lower()
vowel_count = word_lower.count('a') + word_lower.count('e') + word_lower.count('i') +
word_lower.count('o') + word_lower.count('u')
print(f"The word '{word}' has {vowel_count} vowel(s).")
User-Defined Functions
Question-1
Assume that you’re working at a school and the school has a vision of
building a rectangular playground with a specific width and height. They
needed a quick and efficient way to calculate the playground's area.
Write a function with the name "calculate_playground_area" that will
accept the "width" and "height" as parameters to calculate the area of the
playground.
calcluate_playground_area = width*height
print(f"The area of the playground is {calcluate_playground_area} square units.")
Question-2
One sunny morning, the school's principal, Mrs. Anderson, gathered all the
students in the assembly hall to announce an exciting event: the first-
ever "Healthy Heights Health Fair. In this endeavor, they have decided to
launch a health awareness campaign to educate students about the
importance of maintaining a healthy lifestyle, including monitoring their
Body Mass Index (BMI).
def calculated_BMI(weight,height):
BMI=(weight/(height**2))*100
print(BMI)
if bmi < 18.5:
return "Underweight"
elif bmi >= 18.5 and bmi < 24.9:
return "Normal weight"
elif bmi >= 25.0 and bmi < 29.9:
return "Overweight"
else :
return "Obese"
BMI = calculated_BMI(weight,height)
print(f"Your BMI is {BMI}")
Lambda Functions
Question-1
To recognize and celebrate student achievements, the school administration
has decided to organise an honour roll event. 1. Design a Python program
that takes a list of student names and their corresponding scores as
input.
2. The program should use a lambda function to sort the list based on the
scores in ascending order.
3. After sorting, the program should display the list of students along
with their scores.
student_data = [ ("Alice", 85), ("Bob", 70), ("Charlie", 95), ("David", 60), ("Eve", 78) ]
student_data.sort(key=lambda student: student[1])
print("Students sorted by scores:")
for student in student_data:
print(f"{student[0]} - {student[1]}")
Question-2
You have two employee salaries, EmployeeX and EmployeeY, along with a
specific operation.
Write a Python code snippet that takes the values of EmployeeX, EmployeeY,
and operation, and then performs the specified operation on the salaries
using lambda functions. Write a Python code snippet that takes EmployeeX,
EmployeeY, and operation as input and performs the specified arithmetic
operation on the salaries using lambda functions. Print the result of the
operation.
EmployeeX = 150000
EmployeeY = 125000
add = lambda x,y:x+y
subtraction = lambda x,y:x-y
multiplication = lambda x,y:x*y
division = lambda x,y:x/y
if operation == "+":
result = add(EmployeeX,EmployeeY)
elif operation == "-":
result = subtraction(EmployeeX,EmployeeY)
elif operation == "*":
result = multiplication(EmployeeX,EmployeeY)
elif operation == "/":
result = division(EmployeeX,EmployeeY)
else:
result = "Invalid operation"
print("Result:", result)
Recursive Functions
Question-1
You are given a sorted list of integers as follows:
sorted_list = [3, 8, 12, 15, 21, 27, 36, 42, 53, 60]
Write a Python function called binary_search_index that takes in three
parameters: the sorted list, the target integer to search for, and the
indices left and right representing the search range.
The function should return the index of the target integer in the list if
it is present, otherwise, it should return -1.
Implement the binary_search_index function using the binary search
algorithm and test it with the provided sorted_list and target integers:
21, 8, and 37.
def binary_search(array, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
return binary_search(arr, target, mid + 1, right)
else:
return binary_search(arr, target, left, mid - 1)
sorted_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
index = binary_search(sorted_list, target, 0, len(sorted_list) - 1)
if index != -1:
print(f"{target} found at index {index}")
else:
print(f"{target} not found in the list")
Question-2
Your task is to write a Python program that calculates the result of
raising a given base number to a specified exponent using recursion.
Write a Python code that defines a function power(base, exponent) to
accomplish this calculation. The function should return the result of
raising the base to the power of exponent using a recursive approach. You
can assume that both the base and exponent are non-negative integers.
def power(base,exponent):
if exponent == 0:
return 1
elif exponent > 0:
return base * power(base, exponent - 1)
result = power (base,exponent)
print(f"{base} raised to the power of {exponent} is {result}")
Question-3
Palindrome detection is a common problem in computer science, involving
identifying strings that read the same forwards and backward. To tackle
this, recursion offers an elegant solution.
Your task is to write a Python program that determines whether a given
string is a palindrome or not. A palindrome is a string that remains the
same when its characters are reversed.
def is_palindrome(s):
s = s.lower().replace(" ", "")
if len(s) <= 1:
return True
elif s[0] != s[-1]:
return False
else:
return is_palindrome(s[1:-1])
if is_palindrome(string):
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")
Capstone
Question-1
Create a simple banking interface that welcomes the account owner "Alice",
provides her with the option to inquire about her account balance, and
then displays her current balance of $3000.
account_owner = "Alice"
current_balance = 3000
def welcome(username):
print("Welcome,", username)
def balance_inquiry(account_balance):
print("Current balance:",account_balance)
Question-2
You are tasked with creating a simple ATM application interface that
allows an account owner to perform deposit and withdrawal operations on
their account balance. You need to implement the code following the
provided instructions and demonstrate its functionality with examples of
both deposit and withdrawal operations. Instructions:
Eve, has an initial account balance of $1800 Create a Welcome Function:
Implement a function named welcome that takes an account_owner as a
parameter and displays a welcome message. The function should then display
the available options: "1. Deposit" and "2. Withdrawal".
Handle User Choice: Take input from the user for their choice of operation
(1 for deposit, 2 for withdrawal). Store this choice in a variable named
choice. (Do not use the input function, directly save the value in the
variable eg. choice = 1) Withdrawal Operation:
1. If the user's choice is 2, calculate the predefined withdrawal amount
as 500.
2. Call a function named withdrawal with the following parameters:
account_owner, withdrawal_amount, and current_balance.
3. Inside the withdrawal function, check if the withdrawal_amount is
greater than the current_balance. If it is, display an "Insufficient
Balance" message. Otherwise, subtract the withdrawal_amount from the
current_balance and display a success message with the updated balance.
Invalid Choice Handling:
If the user's choice is neither 1 nor 2, display an "Invalid choice"
message.
account_owner = "Eve"
account_balance = 1800
def welcome(username):
print("Welcome,", username, "! Please select an option.")
def deposit(account_balance, amount):
account_balance += amount
return account_balance
def withdrawal(account_balance, amount):
if account_balance >= amount:
account_balance -= amount
return account_balance
return None
welcome(account_owner)
print("1. Deposit")
print("2. Withdrawal")
if choice == 1:
print("You have chosen the Deposit option")
deposit_amount = 1000
updated_balance = deposit(account_balance, deposit_amount)
print("Deposit successful! Updated balance:", updated_balance)
elif choice == 2:
print("You have chosen the Withdrawal option")
withdrawal_amount = 500
updated_balance = withdrawal(account_balance, withdrawal_amount)
if updated_balance:
print("Withdrawal successful! Updated balance:", updated_balance)
else:
print("Insufficient balance for withdrawal.")
else:
print("Invalid choice.")
Question-3
You are tasked with extending the functionality of the existing ATM
application interface to include two new features: viewing a mini
statement and changing the PIN. You need to implement the code according
to the provided instructions and demonstrate the functionality of both
mini statement viewing and the change PIN operation.
account_owner_pin = "Grace"
current_pin = "4321"
account_owner_mini = "David"
transaction_history = ["Deposit +$100", "Withdrawal -$50", "Deposit +$200", "Transfer -$30",
"Withdrawal -$20", "Transfer +$50"]
new_pin ="5678"
def welcome(username):
print("Welcome,", username, "! Please select an option.")
def mini_statement(transactions):
return transactions[-5:]
def change_pin(current_pin, new_pin):
if len(new_pin) == 4:
return "PIN changed successfully"
else:
return "Invalid PIN format"
if choice == 1:
welcome(account_owner_mini)
print("1. Mini Statement")
recent_transactions = mini_statement(transaction_history)
print("Recent transactions:", recent_transactions)
elif choice == 2:
welcome(account_owner_pin)
print("2. Change PIN")
result = change_pin(current_pin, new_pin)
print(result)
else:
print("Invalid choice.")
Question-4
Create a function named "main_menu" with the account number as a parameter
(2346289024444). Display a welcome message, including the user's account
number. Display the following options to the user:
NOTE: USER INPUT is not supported in this code box. So, You can hardcode
the input in the 'choice' variable. While submitting the code. Remove the
choice variable.
1. Check Account Balance
2. Make a Withdrawal
3. Make a Deposit
4. Mini statement
5. Exit Banking Services
def main_menu(account_number):
print(f"Welcome to your account {account_number}!")
while True:
print("1. Check Account Balance")
print("2. Make a Withdrawal")
print("3. Make a Deposit")
print("4. Mini statement")
print("5. Exit Banking Services")
if choice == 1:
print("You have checked the account balance, Balance enquiry function called")
break
elif choice == 2:
print("Withdrawal function is called")
break
elif choice == 3:
print("Deposit function is called")
break
elif choice == 4:
print("Mini statement function called")
break
elif choice == 5:
print("Thank you for using our banking services. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
break
Question-5
The variables given below are already defined: account_owner = "Alice"
current_balance = 3000 choice = 4 transaction_history = ["Deposit +$100",
"Withdrawal -$50", "Deposit +$200", "Transfer -$30", "Withdrawal -$20",
"Transfer +$50"] withdrawal_amount = 1000 deposit_amount = 2000
account_number = "2346289024444" current_pin = 3456 new_pin = 1899
With reference to the previously attempted presentations, you should now
merge all the created functions in one system. You are required to call
the functions in the main menu.
account_owner = "Alice"
current_balance = 3000
transaction_history = ["Deposit +$100", "Withdrawal -$50", "Deposit +$200", "Transfer -$30",
"Withdrawal -$20", "Transfer +$50"]
withdrawal_amount = 1000
deposit_amount = 2000
account_number = "2346289024444"
current_pin = 3456
new_pin = 1899
def welcome(username):
print("Welcome,", username, "! Please select an option.")
def balance_inquiry(account_balance):
return account_balance
def deposit(account_balance, amount):
account_balance += amount
return account_balance
def withdrawal(account_balance, amount):
if account_balance >= amount:
account_balance -= amount
return account_balance
def mini_statement(transactions):
return transactions[:5]
def change_pin(current_pin, new_pin):
if len(str(new_pin)) == 4:
return "PIN changed successfully"
else:
return "Invalid PIN format"
def main_menu(account_number):
global transaction_history
global current_balance
print(f"Welcome to your account {account_number}!")
while True:
print("1. Check Account Balance")
print("2. Make a Withdrawal")
print("3. Make a Deposit")
print("4. Change password")
print("5. Exit Banking Services")
if choice == 1:
print("You have checked the account balance:", balance_inquiry(current_balance))
break
elif choice == 2:
current_balance = withdrawal(current_balance, withdrawal_amount)
if current_balance:
print("Withdrawal successful! Updated balance:", current_balance)
transaction_history.insert(0, f"Withdrawal -${withdrawal_amount}")
recent_transactions = mini_statement(transaction_history)
print("Recent transactions:", recent_transactions)
break
else:
print("Insufficient balance for withdrawal.")
break
elif choice == 3:
current_balance = deposit(current_balance, deposit_amount)
print("Deposit successful! Updated balance:", current_balance)
transaction_history.insert(0, f"Deposit +${deposit_amount}")
recent_transactions = mini_statement(transaction_history)
print("Recent transactions:", recent_transactions)
break
elif choice == 4:
result=change_pin(current_pin, new_pin)
print(result)
break
elif choice == 5:
print("Thank you for using our banking services. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
break
welcome(account_owner)