Python function exercises with solution

Introduction

Functions are used to organize code into blocks that we can reuse later. It makes the code more readable and modular. Moreover, it saves time when designing and running the code since it helps to keep code clean and unrepeated. We just need to call a function whenever a similar task needs to be executed. To explore more on function click here.

Question 1: Suggest Footwear

Write a program that will give suggested footwear based on the weather.
Ask the user for the weather outside with three options (sunny, rainy, or snowy) and give the correct footwear suggestion (sneaker, gumboot, or boots). Each option should be written as its own function that prints a message based on the input. Expected output:

Source code:

def sunny():
    print("It is sunny day, good to wear sneaker!")

def rainy():
    print("Oops! its raining, better wear gumbot")

def snowy():
    print("Wow! its snowing, better wear boot")

weather_today = input("Whats the weather today:")
if weather_today == "sunny":
    sunny()
elif weather_today == "rainy":
    rainy()
elif weather_today == "snowy":
    snowy()
else:
    print(f"No footwear avaibale for {weather_today}")

Output:

//sample output 1
Whats the weather today:sunny
It is sunny day, good to wear sneaker!

//sample output 2
Whats the weather today:rainy
Oops! its raining, better wear gumbot

//sample output 3
Whats the weather today:snowy
Wow! its snowing, better wear boot

//sample output 4
Whats the weather today:cloudy
No footwear avaibale for cloudy
Question 2: Simple Calculator using function

Write a program that asks the user for two numbers. Then ask them if they would like to add, subtract, divide, or multiply these numbers. Perform the chosen operation on the values, showing the operation being performed. Write four functions, one for each mathematical operation.
Example: add(), subtract(), Multiply(), and Divide()

Source code:

num1 = float(input("Enter number 1:"))
num2 = float(input("Enter number 2:"))

def to_add():
    tot = num1 + num2
    print(f"{num1} + {num2} = {tot}")

def to_sub():
    sub = num1 - num2
    print(f"{num1} - {num2} = {sub}")

def to_mul():
    mul = num1 * num2
    print(f"{num1} x {num2} = {mul}")

def to_div():
    div = num1 / num2
    print(f"{num1} / {num2} = {div}")

operation = input("Choose an operation(+,-,*, /):")
if operation == "+":
    to_add()
elif operation == "-":
    to_sub()
elif operation == "*":
    to_mul()
elif operation == "/":
    to_div()
else:
    print(f"No operation for {operation} for now! sorry!")

Output:

//sample output 1
Enter number 1:5
Enter number 2:2
Choose an operation(+,-,*, /):*
5.0 x 2.0 = 10.0

//sample output 2
Enter number 1:9
Enter number 2:100
Choose an operation(+,-,*, /):-
9.0 - 100.0 = -91.0

Question 3: My Favorite Book

Write a function called favorite_book() that accepts two parameter, title and author. The function should print a message, such as The History of Bhutan by Karma Phuntsho. Call the function, make sure to include a book title and author as an argument in the function call.

Source code:

def favorite_book(title, author):
    print(f"{title} was written by {author}")
favorite_book("The History of Bhutan", "Karma Phuntsho")

Output:

The History of Bhutan was written by Karma Phuntsho
Question 4: Sum of numbers

Write a function that takes two arguments and returns their sum.

Source code:

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

num1 = float(input("Enter number 1:"))
num2 = float(input("Enter number 2:"))
tot = sum_of_number(num1, num2)
print(f"{num1} + {num2} = {tot}")

Output:

Enter number 1:5
Enter number 2:90
5.0 + 90.0 = 95.0
Coding challenge: Leap year

Write a function called is_leap() that accepts one parameter i.e. year. The function should check whether the year is a leap year or not. 

Hint: 

In the Gregorian calendar, two conditions are used to identify leap years:

  • The year that can be evenly divided by 4 but not by 100, is a leap year.
  • The year is also a leap year if it is evenly divisible by 400.

Source code:

def is_leap(year):
    if year % 4 == 0 and year % 100 != 0:
        print(f"{year} is a leap year.")
    elif year % 400 == 0:
        print(f"{year} is a leap year.")
    elif year % 100 == 0:
        print(f"{year} is not a leap year.")
    else:
        print(f"{year} is not a leap year.")
year = int(input("Enter a year:"))
is_leap(year)

Output:

//sample output 1
Enter a year:2004
2004 is a leap year.

//sample output 2
Enter a year:2003
2003 is not a leap year.