Compute and display a person's weekly salary as determined by the following rules:
# -For the first 40 hours, the person receives $12 per hour
# -For each additional hour worked, the person receives $15 per hour
The function should return a string message telling the user their salary for
the week. See example below.
Example program 1:
# How many hours did you work? 22
# Your salary this week is $264
Example program 2
# How many hours did you work? 45
# Your salary this week is $555
Assistant
Here’s the implementation of the salary() function based on the given requirements:
def salary():
# Prompt the user for the number of hours worked
hours_worked = int(input("How many hours did you work? "))
# Calculate the salary based on the rules
if hours_worked <= 40:
total_salary = hours_worked * 12
else:
# Calculate overtime hours and salary
extra_hours = hours_worked - 40
total_salary = (40 * 12) + (extra_hours * 15)
# Return the message with the calculated salary
return f"Your salary this week is ${total_salary}"
# Example usage
print(salary())
Explanation:
The function prompts the user to input the number of hours worked. This input is converted to an integer.
For hours worked up to 40, the salary is calculated as $12 * hours_worked.
For hours beyond 40, the overtime hours (extra_hours) are multiplied by $15, and the base salary for the 40 hours (40 * $12) is added to it.
The function formats and returns the total salary message to the user.
User
A microwave oven manufacturer recommends that when heating two items, add 50%
to the heating time, and when heating three items double the heating time.
Heating more than three items at once is not recommended. Write a function
called microwave() that asks the user for the number of items and the single
item heating time. The function then returns the recommended heating time as
demonstrated below.
#Example program 1:
#How many items are you heating up? 2
#How many minutes does the single item take to heat up? 5
#7.5 minutes
Assistant
Here is the implementation of the microwave() function based on the provided requirements:
def microwave():
# Prompt the user for the number of items and the heating time for a single item
num_items = int(input("How many items are you heating up? "))
single_item_time = float(input("How many minutes does the single item take to heat up? "))
# Calculate the recommended heating time based on the rules
if num_items == 1:
recommended_time = single_item_time
elif num_items == 2:
recommended_time = single_item_time * 1.5
elif num_items == 3:
recommended_time = single_item_time * 2
else:
# If the user enters more than 3 items
return "Heating more than three items at once is not recommended."
# Return the recommended heating time
return f"{recommended_time} minutes"
# Example usage
print(microwave())
User
Practice Problems
Tracing programs. Determine the output of each program. Where x = 2 and y = 3
I. Program #1
if (x < y) and not(y == 10):
sum = x + y
print("x =", x, "y = ", y)
print("sum =", sum)
Output:
II. Program #2
if (x > y) or (x - y < 0):
x = x + 1
y = y + 1
print("x = ", x, " y = ", y)
Output:
III. Program #3
if (x > y) or (x * y < 0):
print("x = ", x, " y = ", y)
Output:
Assistant
Let’s trace each program step-by-step and determine the output. The values of x = 2 and y = 3 are given as input.
Program #1
if (x < y) and not(y == 10):
sum = x + y
print("x =", x, "y =", y)
print("sum =", sum)
Tracing:
x < y evaluates to 2 < 3, which is True.
User
Coding Practice
For all coding practices problems, make sure you are using IPO structure. You should also include proper comments! 1. A bank has the following rule: if a customer has more than 1500 dollars in their savings account, then there is no service charge for writing cheques. Otherwise, there is a 0
2. Car tire pressure is a major safety concern in cars. Improper pressure could cause a car accident. The tire pressure for Ms. Su’s car needs to be between 32 and 36 for all tires. Write a program that reads the pressure and writes a message that says if the inflation is safe.
Enter right front pressure: 34
Enter left front pressure: 32
Enter right rear pressure: 33
Enter left rear pressure: 30
Inflation is NOT ok. Please adjust tire pressure.
3. Write a program that asks a user how many boxes of cookies they want to order. There are three types of cookies: Chocolate Chip, Oatmearl, and Shortbread. If the user orders 5 boxes of one type or 10 boxes in total, they will receive a 10% discount before tax. Write a program that outputs the total cost including tax. Each box of cookies cost 89.50
Assistant
User
could you just write short answers
Assistant
Certainly! Here's the summarized code and examples for each program.
Problem 1: Bank Service Charges
def bank_service_charge():
chequing_balance = float(input("Enter your chequing account balance: "))
savings_balance = float(input("Enter your savings account balance: "))
num_cheques = int(input("How many cheques are you writing? "))
if chequing_balance > 1000 or savings_balance > 1500:
service_charge = 0
else:
service_charge = num_cheques * 0.15
print(f"Your service charge will be: ${service_charge:.2f}")
User
Practice Problems
Which of the two programs below is more efficient? Explain why. What is the output of each program? I. Program #1
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
z = int(input("Enter a value for z: "))
if (x >= y): # y isn't biggest
if (x >= z): # y, z not biggest
print("x is the biggest")
else: # y, x not biggest
print("z is the biggest")
elif (y >= z): # x, z not biggest
print("y is the biggest")
else: # x, y not biggest
print("z is the biggest")
Output:
II. Program #2
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
z = int(input("Enter a value for z: "))
if (x >= y) and (x >= z): # x is biggest
print("x is the biggest")
elif (y >= z): # x isn't biggest
print("y is the biggest")
else: # x, y not biggest
print("z is the biggest")
Output:
Assistant
User
Write two different programs to simplify the following sequence so that the effect is the same but fewer comparisons are required. Use nested ifs in one of the programs and elif in the other.
if (temperature > MAX_TEMP):
print("Porridge too hot")
if (temperature < MIN_TEMP):
print("Porridge too cold")
if (temperature <= MAX_TEMP) and (temperature >= MIN_TEMP):
print("Porridge just right - eat it all up.")
\
Assistant
User
What does this code do? Rewrite the code using the logical operator OR.
letter = input("Please enter an uppercase letter: ")
if (letter != "A"):
if (letter != "E"):
if (letter != "I"):
if (letter != "O"):
if (letter != "U"):
print(letter, "is a consonant.")
Assistant
Understanding the Code
User
A) Write a program to determine the smallest of three integers
B) Write a program to determine the largest of three integers
A medical conference needs place cards made with the appropriate title. If the person is a doctor, then the card should say Dr. plus the name. If the person is not a doctor, then if the person is female, the card should say Ms. plus the name, and if the person is male, then it should say Mr. plus the name. Write a program that asks the appropriate questions and outputs the correct title for the place card.
Write programs to solve each problem.
A) Determine the discount percentage for selling a TV, using the following rules:
If plasma, discount will be 5% of selling price.
If LCD, discount is 8% of selling price for a 30" model, and 10% of selling price for 42" model.
B) Determine if a given year is a leap year. Leap years are divisible by 4, but not by 100, unless they are also divisible by 400.
Assistant
User
Convert 3 homework coding practices into functions
Write 3 test cases for each of the functions
Assistant
Let's convert the previously provided homework coding practices into functions with 3 test cases for each function.
User
could you do 3 random problems
Assistant
Example Run:
Example 1:
How many hours did you work? 22
Your salary this week is $264
Example 2:
How many hours did you work? 45
Your salary this week is $555
Explanation:
The function prompts the user for the number of items (num_items) and the heating time for a single item (single_item_time), which is converted to the appropriate data types (int and float).
It evaluates the following conditions:
If there is only 1 item, the heating time is the same as the single item heating time.
If there are 2 items, 50% is added to the heating time, making it single_item_time * 1.5.
If there are 3 items, the heating time is doubled, making it single_item_time * 2.
If the user enters more than 3 items, a message is returned stating that heating more than 3 items is not recommended.
For valid inputs (1 to 3 items), the function returns the calculated heating time in minutes as a formatted message.
Example Runs:
Example 1:
Input:
How many items are you heating up? 2
How many minutes does the single item take to heat up? 5
Output:
7.5 minutes
Example 2:
Input:
How many items are you heating up? 3
How many minutes does the single item take to heat up? 4
Output:
8.0 minutes
Example 3:
Input:
How many items are you heating up? 5
How many minutes does the single item take to heat up? 6
Output:
Heating more than three items at once is not recommended.
y == 10 evaluates to 3 == 10, which is False.
not(y == 10) evaluates to not(False), which is True.
With the condition being (True) and (True), the overall condition is True and the body of the if statement executes.
The variable sum is computed as x + y = 2 + 3 = 5.
The values of x and y are printed, and then, sum is printed.
Output:
x = 2 y = 3
sum = 5
Program #2
if (x > y) or (x - y < 0):
x = x + 1
y = y + 1
print("x =", x, "y =", y)
Tracing:
x > y evaluates to 2 > 3, which is False.
x - y < 0 evaluates to (2 - 3) < 0, which simplifies to -1 < 0, so it is True.
With the condition being (False) or (True), the overall condition is True and the body of the if statement executes.
x = x + 1 updates x to 2 + 1 = 3.
y = y + 1 updates y to 3 + 1 = 4.
The updated values of x and y are printed.
Output:
x = 3 y = 4
Program #3
if (x > y) or (x * y < 0):
print("x =", x, "y =", y)
Tracing:
x > y evaluates to 2 > 3, which is False.
x * y < 0 evaluates to (2 * 3) < 0, which simplifies to 6 < 0, so it is also False.
With the condition being (False) or (False), the overall condition is False and the body of the if statement does not execute.
Below are the solutions for each of the provided problems. These programs use the Input-Process-Output (IPO) structure and include detailed comments for clarity.
Problem 1: Bank Service Charges
IPO Structure
Input: Get the chequing account balance, savings account balance, and the number of cheques written from the user.
Process: Apply the bank's rule to determine if there is a service charge. If the balance conditions are not met, calculate the total charge (0.15 * number of cheques).
Output: Display the total service charge.
Code:
def bank_service_charge():
# Input
# Ask for chequing and savings account balances
chequing_balance = float(input("Enter your chequing account balance: "))
savings_balance = float(input("Enter your savings account balance: "))
num_cheques = int(input("How many cheques are you writing? "))
# Process
# Check if there is a service charge based on the rule
if chequing_balance > 1000 or savings_balance > 1500:
service_charge = 0
else:
service_charge = num_cheques * 0.15
# Output
# Print the total service charge
print(f"Your service charge will be: ${service_charge:.2f}")
# Run the function
bank_service_charge()
Example Run:
Input:
Enter your chequing account balance: 650
Enter your savings account balance: 1770
How many cheques are you writing? 3
Output:
Your service charge will be: $0.00
Problem 2: Tire Pressure Safety Check
IPO Structure
Input: Get the tire pressures for all four tires (right front, left front, right rear, left rear).
Process: Check if all pressures are in the safe range (between 32 and 36 inclusive).
Output: Indicate whether the inflation is safe or not.
Code:
def tire_pressure_check():
# Input
# Ask the user for the pressure of each tire
right_front = int(input("Enter right front pressure: "))
left_front = int(input("Enter left front pressure: "))
right_rear = int(input("Enter right rear pressure: "))
left_rear = int(input("Enter left rear pressure: "))
# Process
# Check if all tire pressures are in the safe range (32 to 36)
if 32 <= right_front <= 36 and 32 <= left_front <= 36 and 32 <= right_rear <= 36 and 32 <= left_rear <= 36:
message = "Inflation is OK."
else:
message = "Inflation is NOT ok. Please adjust tire pressure."
# Output
# Print the result message
print(message)
# Run the function
tire_pressure_check()
Example Run:
Input:
Enter right front pressure: 34
Enter left front pressure: 32
Enter right rear pressure: 33
Enter left rear pressure: 30
Output:
Inflation is NOT ok. Please adjust tire pressure.
Problem 3: Cookie Order with Discounts
IPO Structure
Input: Get the number of boxes for each type of cookie (Chocolate Chip, Oatmeal, Shortbread).
Process: Calculate the total cost, apply a 10% discount if the user orders 5 or more boxes of one type or 10 boxes in total. Add tax to the discounted amount (assuming tax is 5%).
Output: Display the total cost including the discount (if any) and the final cost after tax.
Code:
def cookie_order():
# Input
# Ask for the number of boxes for each type of cookie
chocolate_chip = int(input("How many boxes of Chocolate Chip cookies would you like to buy? "))
oatmeal = int(input("How many boxes of Oatmeal cookies would you like to buy? "))
shortbread = int(input("How many boxes of Shortbread cookies would you like to buy? "))
# Process
# Cost per box
cost_per_box = 8.00
tax_rate = 0.05
# Calculate total cost before discounts
total_boxes = chocolate_chip + oatmeal + shortbread
total_cost = total_boxes * cost_per_box
# Check for discount
if total_boxes >= 10 or chocolate_chip >= 5 or oatmeal >= 5 or shortbread >= 5:
total_cost *= 0.90 # Apply 10% discount
discount_message = "You received a 10% discount for your purchase!"
else:
discount_message = "No discount applied."
# Add tax
final_cost = total_cost * (1 + tax_rate)
# Output
# Print the discount message and the final total cost
print(discount_message)
print(f"Your total is: ${final_cost:.2f}")
# Run the function
cookie_order()
Example Run:
Input:
How many boxes of Chocolate Chip cookies would you like to buy? 4
How many boxes of Oatmeal cookies would you like to buy? 4
How many boxes of Shortbread cookies would you like to buy? 3
Output:
You received a 10% discount for your purchase!
Your total is: $89.50
Summary of Results:
Bank Service Charges Program: Calculates service charges based on the user's account balances and number of cheques written.
Tire Pressure Safety Check Program: Checks the pressures of all four tires and indicates if any are outside the safe range.
Cookie Order Program: Calculates the total cookie order cost, applying a 10% discount if eligible, includes tax, and outputs the final total cost.
Example Input/Output:
Input:
650, 1770, 3
Output:
$0.00
Problem 2: Tire Pressure Safety Check
def tire_pressure_check():
rf = int(input("Enter right front pressure: "))
lf = int(input("Enter left front pressure: "))
rr = int(input("Enter right rear pressure: "))
lr = int(input("Enter left rear pressure: "))
if 32 <= rf <= 36 and 32 <= lf <= 36 and 32 <= rr <= 36 and 32 <= lr <= 36:
print("Inflation is OK.")
else:
print("Inflation is NOT ok. Please adjust tire pressure.")
Example Input/Output:
Input:
34, 32, 33, 30
Output:
Inflation is NOT ok. Please adjust tire pressure.
Problem 3: Cookie Order with Discounts
def cookie_order():
chocolate = int(input("Chocolate Chip? "))
oatmeal = int(input("Oatmeal? "))
shortbread = int(input("Shortbread? "))
total_boxes = chocolate + oatmeal + shortbread
total_cost = total_boxes * 8.00
if total_boxes >= 10 or chocolate >= 5 or oatmeal >= 5 or shortbread >= 5:
total_cost *= 0.90 # 10% discount
print("You received a 10% discount!")
final_total = total_cost * 1.05 # 5% tax
print(f"Your total is: ${final_total:.2f}")
Example Input/Output:
Input:
4, 4, 3
Output:
You received a 10% discount!
Your total is: $89.50
Comparison and Explanation:
Which program is more efficient?
Program #2 is more efficient because it uses fewer conditions and has a simpler structure. In Program #2, each condition checks for only one possibility (e.g., if x is the largest directly), which makes the logic clearer and reduces unnecessary nesting.
Program #1 uses nested conditionals, which introduces additional checks for possibilities that are already covered earlier (e.g., whether x is the largest). This adds slightly more complexity.
Outputs
Program #1:
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
z = int(input("Enter a value for z: "))
if (x >= y): # Check if x is at least equal to or larger than y
if (x >= z): # Check if x is also at least equal to or larger than z
print("x is the biggest") # If true, x is the largest
else: # If x >= y but x < z, then z is the largest
print("z is the biggest")
elif (y >= z): # Check if y is at least equal to or larger than z
print("y is the biggest") # If true, y is the largest
else: # If neither x nor y are the largest, then z is the largest
print("z is the biggest")
Example Runs for Program #1:
Input:
Enter a value for x: 5
Enter a value for y: 3
Enter a value for z: 2
Output:
x is the biggest
Input:
Enter a value for x: 2
Enter a value for y: 6
Enter a value for z: 4
Output:
y is the biggest
Input:
Enter a value for x: 3
Enter a value for y: 3
Enter a value for z: 7
Output:
z is the biggest
Program #2:
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
z = int(input("Enter a value for z: "))
if (x >= y) and (x >= z): # Check if x is the largest or equal to the largest
print("x is the biggest")
elif (y >= z): # Check if y is larger than or equal to z (x is not the largest)
print("y is the biggest")
else: # If neither x nor y are the largest, then z is the largest
print("z is the biggest")
Example Runs for Program #2:
Input:
Enter a value for x: 5
Enter a value for y: 3
Enter a value for z: 2
Output:
x is the biggest
Input:
Enter a value for x: 2
Enter a value for y: 6
Enter a value for z: 4
Output:
y is the biggest
Input:
Enter a value for x: 3
Enter a value for y: 3
Enter a value for z: 7
Output:
z is the biggest
Key Difference in Logic:
Program #1 uses nested if conditions, which makes the logic a little more verbose. For example, the check (x >= y) is made first, and if true, only then is (x >= z) evaluated. If (x >= y) is false, additional checks are made for y and z separately.
Program #2 simplifies the logic by directly combining the comparisons (if (x >= y) and (x >= z)), which eliminates unnecessary nesting and reads logically as "If x is the largest, do this; otherwise, check y or z."
Final Answer:
More Efficient Program:Program #2 (fewer comparisons and simpler structure)
Outputs: Both programs produce the same output for the same inputs. Examples for both programs are provided.
Here are two optimized versions of the sequence. One uses nested if statements, while the other uses elif to reduce the number of comparisons while maintaining the same functionality.
Program 1: Using Nested if Statements
def porridge_temperature_check():
# Input
temperature = int(input("Enter porridge temperature: "))
MAX_TEMP = 100
MIN_TEMP = 70
# Process and Output using Nested Ifs
if temperature > MAX_TEMP:
print("Porridge too hot")
else:
if temperature < MIN_TEMP:
print("Porridge too cold")
else:
print("Porridge just right - eat it all up.")
How it works:
The first if checks if the temperature is greater than MAX_TEMP. If true, "too hot" is printed, and no further checks are made.
If the first condition is false, the program moves to the else block to decide:
If it's less than MIN_TEMP ("too cold").
If it's within the acceptable range ("just right").
Program 2: Using elif
def porridge_temperature_check():
# Input
temperature = int(input("Enter porridge temperature: "))
MAX_TEMP = 100
MIN_TEMP = 70
# Process and Output using Elif
if temperature > MAX_TEMP:
print("Porridge too hot")
elif temperature < MIN_TEMP:
print("Porridge too cold")
else:
print("Porridge just right - eat it all up.")
How it works:
The conditions are evaluated step by step:
If the temperature is greater than MAX_TEMP, "too hot" is printed, and no further conditions are checked.
If the temperature is less than MIN_TEMP, "too cold" is printed.
If neither of the above is true, it must be in the acceptable range, so "just right" is printed.
Example Run for Both Programs:
Input:
Enter porridge temperature: 105
Output:
Porridge too hot
Input:
Enter porridge temperature: 60
Output:
Porridge too cold
Input:
Enter porridge temperature: 85
Output:
Porridge just right - eat it all up.
Comparison of the Two Approaches:
The nested if program is structured more explicitly so the program checks a condition and only evaluates further based on specific cases. While it's slightly longer, it avoids redundant checks.
The elif program is shorter and linear, with all cases laid out in order of priority but evaluates at most a single condition (top to bottom flow).
Both approaches are efficient and reduce unnecessary comparisons compared to the original!
The given code determines whether the input letter is a consonant (not a vowel) by repeatedly checking if the letter is NOT equal to each of the uppercase vowels (A, E, I, O, U). If the letter is indeed a consonant, it prints the message: <letter> is a consonant.
How it works:
The program starts by taking an uppercase letter as input.
It goes through a series of nested if statements, each checking if the letter is not equal to one of the vowels.
If all the checks pass (i.e., the letter is not a vowel), the program prints that the letter is a consonant.
Rewriting the Code with Logical Operator OR
We can simplify the nested if conditions by using the OR logical operator. With OR, if the letter matches any of the vowels, the condition fails, and no action is taken. Otherwise, the program prints that the input is a consonant.
letter = input("Please enter an uppercase letter: ")
# Combine vowel checks into a single condition using 'or'
if letter != "A" and letter != "E" and letter != "I" and letter != "O" and letter != "U":
print(letter, "is a consonant.")
Even More Simplified Code
Instead of using multiple conditions with !=, we can use the in keyword to check if the letter is in a set of vowels. This simplifies the logic even further.
letter = input("Please enter an uppercase letter: ")
# Check if the letter is NOT a vowel
if letter not in "AEIOU":
print(letter, "is a consonant.")
Examples of Execution:
Case 1: Input is a vowel
Input:
Please enter an uppercase letter: A
Output:
(The program prints nothing in this case since "A" is a vowel.)
Case 2: Input is a consonant
Input:
Please enter an uppercase letter: B
Output:
B is a consonant.
Case 3: Input is invalid (lowercase letter or symbol)
Input:
Please enter an uppercase letter: b
Output:
(The program doesn't check for invalid inputs; it treats lowercase letters the same way as consonants unless additional validation is added.)
Comparison of Original and Simplified Code
Original code uses 5 nested if statements, making it harder to read and maintain.
The rewritten code using OR is more concise and combines the checks into a single statement.
The final version using not in is even more efficient and easier to understand, making it the best solution.
Problem 1: Smallest and Largest of Three Integers
A) Smallest of Three Integers
def find_smallest():
# Input
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
c = int(input("Enter the third integer: "))
# Process: Determine smallest
smallest = a
if b < smallest:
smallest = b
if c < smallest:
smallest = c
# Output
print(f"The smallest integer is: {smallest}")
Example Input/Output:
Input: 8, 3, 6
Output: The smallest integer is: 3
B) Largest of Three Integers
def find_largest():
# Input
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
c = int(input("Enter the third integer: "))
# Process: Determine largest
largest = a
if b > largest:
largest = b
if c > largest:
largest = c
# Output
print(f"The largest integer is: {largest}")
Example Input/Output:
Input: 4, 9, 7
Output: The largest integer is: 9
Problem 2: Place Cards with Titles
def place_card():
# Input
is_doctor = input("Is the person a doctor? (yes/no): ").strip().lower()
if is_doctor == "yes":
name = input("Enter the name: ")
print(f"Place card: Dr. {name}")
else:
gender = input("Is the person male or female? (male/female): ").strip().lower()
name = input("Enter the name: ")
if gender == "male":
print(f"Place card: Mr. {name}")
elif gender == "female":
print(f"Place card: Ms. {name}")
else:
print("Invalid gender!")
Example Input/Output:
Input:
Is the person a doctor? yes
Enter the name: John Smith
Output:
Place card: Dr. John Smith
Input:
Is the person a doctor? no
Is the person male or female? female
Enter the name: Emily Brown
Output:
Place card: Ms. Emily Brown
Problem 3: Discount Rules and Leap Year Check
A) Determine TV Discount Percentage
def tv_discount():
# Input
tv_type = input("Enter TV type (plasma/LCD): ").strip().lower()
selling_price = float(input("Enter the selling price of the TV: "))
# Process
if tv_type == "plasma":
discount = 0.05 * selling_price
elif tv_type == "lcd":
size = int(input("Enter TV size (30 or 42 inches): "))
if size == 30:
discount = 0.08 * selling_price
elif size == 42:
discount = 0.10 * selling_price
else:
print("Invalid size!")
return
else:
print("Invalid TV type!")
return
# Output
print(f"The discount is: ${discount:.2f}")
Example Input/Output:
Input:
Enter TV type (plasma/LCD): LCD
Enter the selling price of the TV: 1000
Enter TV size (30 or 42 inches): 42
Output:
The discount is: $100.00
Input:
Enter TV type (plasma/LCD): plasma
Enter the selling price of the TV: 800
Output:
The discount is: $40.00
B) Determine if a Year is a Leap Year
def is_leap_year():
# Input
year = int(input("Enter a year: "))
# Process: Leap year rules
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Example Input/Output:
Input:
Enter a year: 2024
Output:
2024 is a leap year.
Input:
Enter a year: 1900
Output:
1900 is not a leap year.
Homework Coding Practice 1: Smallest of Three Integers
Function:
def find_smallest(a, b, c):
"""Determine the smallest of three integers."""
smallest = a
if b < smallest:
smallest = b
if c < smallest:
smallest = c
return smallest
Homework Coding Practice 2: Determine if a Year is a Leap Year
Function:
def is_leap_year(year):
"""Determine if a given year is a leap year."""
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True # It's a leap year
else:
return False # It's not a leap year
Test Cases:
# Test Cases
print(is_leap_year(2024)) # Output: True (2024 is a leap year)
print(is_leap_year(1900)) # Output: False (1900 is not a leap year)
print(is_leap_year(2000)) # Output: True (2000 is a leap year)
Homework Coding Practice 3: Place Cards with Titles
Function:
def place_card(is_doctor, gender, name):
"""Determine the title and full card name for a place card."""
if is_doctor:
return f"Dr. {name}"
else:
if gender.lower() == "male":
return f"Mr. {name}"
elif gender.lower() == "female":
return f"Ms. {name}"
else:
return "Invalid gender!"
Test Cases:
# Test Cases
print(place_card(True, "male", "John Smith")) # Output: "Dr. John Smith"
print(place_card(False, "female", "Emily Brown")) # Output: "Ms. Emily Brown"
print(place_card(False, "male", "Lucas Green")) # Output: "Mr. Lucas Green"
Explanation of Test Cases:
find_smallest Test Cases:
Test for typical integers with different values.
Test for mixed positive and negative values.
Test for all integers being the same.
is_leap_year Test Cases:
Test for a leap year divisible by 4 but not 100 (e.g., 2024).
Test for a non-leap year divisible by 100 but not 400 (e.g., 1900).
Test for a leap year divisible by 400 (e.g., 2000).
place_card Test Cases:
Input for a doctor, using a male name.
Input for a non-doctor, using a female name.
Input for a non-doctor, using a male name.
Here are three random programming problems (different from earlier ones), implemented as functions, along with test cases for each.
Problem 1: Check if a Number is Prime
Problem Statement:
Write a function that checks if a number is prime. A prime number is greater than 1 and only divisible by 1 and itself.
Function Implementation:
def is_prime(num):
"""Check if a number is prime."""
if num < 2: # Prime numbers must be greater than 1
return False
for i in range(2, int(num ** 0.5) + 1): # Check divisors up to the square root of the number
if num % i == 0:
return False
return True
Test Cases:
# Test Cases for is_prime
print(is_prime(2)) # Output: True (2 is a prime number)
print(is_prime(15)) # Output: False (15 is not a prime number)
print(is_prime(29)) # Output: True (29 is a prime number)
Problem 2: Reverse a String
Problem Statement:
Write a function to reverse a string.
Function Implementation:
def reverse_string(s):
"""Reverse the given string."""
return s[::-1] # Slice the string in reverse order
Test Cases:
# Test Cases for reverse_string
print(reverse_string("hello")) # Output: "olleh"
print(reverse_string("Python")) # Output: "nohtyP"
print(reverse_string("madam")) # Output: "madam" (Palindrome)
Problem 3: Find Factorial of a Number
Problem Statement:
Write a function that finds the factorial of a number (non-negative integer). The factorial of n is n * (n-1) * (n-2)... * 1. The factorial of 0 is 1.
Function Implementation:
def factorial(n):
"""Find the factorial of a number."""
if n == 0: # Special case: factorial of 0 is 1
return 1
result = 1
for i in range(1, n + 1): # Multiply numbers from 1 to n
result *= i
return result
Test for a non-prime number (15), which is divisible by numbers other than 1 and itself.
Test for a larger prime number (29), which is only divisible by 1 and 29.
reverse_string Test Cases:
Test with a standard string ("hello"), which reverses normally.
Test with a mixed-case string ("Python") to ensure it reverses correctly.
Test with a palindrome ("madam") to verify it reads the same forward and backward.
factorial Test Cases:
Test with 0 (factorial of 0).
Test with a small number (5) to confirm normal functionality.
Test with a larger number (7) to confirm that the function handles big calculations.
Each problem represents a common coding task, often used in beginner or intermediate coding challenges. These test cases cover edge cases and normal functionality!