Skip to content

Conditionals, Math Operations, and Functions

3.1 Conditionals

Conditionals allow you to execute different code based on certain conditions. They are fundamental in controlling the flow of a program. Let’s explore how to use conditionals in Python with examples from everyday scenarios and build up to using them in an interactive calculator.

3.1.1 Understanding Conditionals

In Python, conditionals use if, elif, and else statements to make decisions.

  1. if Statement: Executes a block of code if the condition is true.
  2. elif Statement: Stands for “else if” and checks another condition if the previous if condition is false.
  3. else Statement: Executes a block of code if all preceding conditions are false.

Syntax of Conditionals

The syntax of conditionals in Python is straightforward. Here’s a basic example:

if condition1:
# Block of code to execute if condition1 is true
elif condition2:
# Block of code to execute if condition1 is false and condition2 is true
else:
# Block of code to execute if both condition1 and condition2 are false

Example: Checking User Age

Let’s consider an example where we check the age of a user and print different messages based on their age:

age = int(input("Enter your age: "))
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")

In this example:

  • If the age is less than 13, the program prints “You are a child.”
  • If the age is between 13 and 17 inclusive, the program prints “You are a teenager.”
  • If the age is 18 or above, the program prints “You are an adult.”

Using Conditionals in an Interactive Calculator

Let’s use conditionals to decide which mathematical operation to perform based on user input.

operation = input("Enter the operation (+, -, *, /): ")
if operation == "+":
print("You chose addition.")
elif operation == "-":
print("You chose subtraction.")
elif operation == "*":
print("You chose multiplication.")
elif operation == "/":
print("You chose division.")
else:
print("Invalid operation.")

In this example:

  • The program asks the user to input an operation.
  • Depending on the input, it prints a message indicating which operation was chosen or if the input was invalid.

Summary of Conditionals

  • if Statement: Executes a block of code if the condition is true.
  • elif Statement: Checks another condition if the previous if condition is false.
  • else Statement: Executes a block of code if all preceding conditions are false.

By mastering conditionals, you can control the flow of your programs and make them respond dynamically to different inputs and conditions.

Level 1 Exercises

Write a Python program that asks the user for their grade percentage and prints a message based on the grade:

  • “You failed.” if the grade is below 50.
  • “You passed.” if the grade is between 50 and 75 inclusive.
  • “You did great!” if the grade is between 76 and 89 inclusive.
  • “You did excellent!” if the grade is 90 or above.

Write a Python program that calculates the Body Mass Index (BMI) and prints a message based on the BMI value:

  • “Underweight” if BMI is less than 18.5.
  • “Normal weight” if BMI is between 18.5 and 24.9 inclusive.
  • “Overweight” if BMI is between 25 and 29.9 inclusive.
  • “Obese” if BMI is 30 or above.

Write a Python program that asks the user for a number and prints whether the number is even or odd.

Write a Python program that asks the user for a number and prints whether the number is positive, negative, or zero.

Level 2 Exercises

Write a Python program that asks the user for the total amount of their shopping and their membership status (member or non-member). Apply the following discount rules and print the final amount:

  • If the user is a member:
  • 20% discount if the amount is more than $100.
  • 10% discount if the amount is $100 or less.
  • If the user is not a member:
    • 5% discount if the amount is more than $100.
    • No discount if the amount is $100 or less.

Write a Python program that asks the user for a year and prints whether it is a leap year. A year is a leap year if it is divisible by 4, but not divisible by 100, unless it is also divisible by 400.

3.2 Math Operations

Math operations allow you to perform calculations in your programs. Python supports various arithmetic operations, such as addition, subtraction, multiplication, division, and more. Understanding these operations is fundamental for performing calculations, data analysis, and algorithm development. Let’s delve into each basic math operation supported by Python and incorporate them into our interactive calculator.

3.3.1 Basic Math Operations

Here are the basic math operations in Python:

  1. Addition (+): Adds two numbers.
  2. Subtraction (-): Subtracts one number from another.
  3. Multiplication (*): Multiplies two numbers.
  4. Division (/): Divides one number by another and returns a float.
  5. Integer Division (//): Divides one number by another and returns an integer.
  6. Modulus (%): Returns the remainder of a division.
  7. Exponentiation (**): Raises one number to the power of another.

Example: Basic Math Operations

Let’s see some examples of these operations in action:

a = 10
b = 5
print("Addition:", a + b) # 15
print("Subtraction:", a - b) # 5
print("Multiplication:", a * b) # 50
print("Division:", a / b) # 3.0
print("Integer Division:", a // b) # 2
print("Modulus:", a % b) # 0
print("Exponentiation:", a ** b) # 100000

Using Math Operations in an Interactive Calculator

Now, let’s use these operations in our calculator. We will ask the user to input two numbers and perform the chosen operation.

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Enter the operation (+, -, *, /): ")
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
if num2 != 0:
result = num1 / num2
else:
result = "Error! Division by zero."
else:
result = "Invalid operation."
print("The result is:", result)

In this example:

  • The program asks the user for two numbers and an operation.
  • It then performs the specified operation and prints the result.
  • If the user chooses division and the second number is zero, it prints an error message.

Summary of Math Operations

  • Addition (+): Adds two numbers.
  • Subtraction (-): Subtracts one number from another.
  • Multiplication (*): Multiplies two numbers.
  • Division (/): Divides one number by another and returns a float.

By mastering these basic math operations, you can perform a wide range of calculations in your programs.

Level 2 Exercises

Write a Python program that asks the user for the length and width of a rectangle and calculates:

  • The area (length * width).
  • The perimeter (2 * (length + width)).

Write a Python program that asks the user for a base and an exponent and calculates the result of raising the base to the power of the exponent.

Write a Python program that asks the user for an amount in US dollars and converts it to Euros. Assume the exchange rate is 1 USD = 0.85 EUR.

Write a Python program that calculates the simple interest. The program should ask the user for the principal amount, the rate of interest per year, and the time in years.

Level 3 Exercises

Write a Python program that calculates the compound interest. The program should ask the user for the principal amount, the rate of interest per year, the number of times interest is compounded per year, and the time in years.

3.3 Functions

Functions allow you to group code into reusable blocks. This makes your code more organized, modular, and easier to maintain. Functions can take inputs, perform specific tasks, and return outputs. They are a fundamental concept in programming and essential for writing efficient and scalable code.

3.3.1 Defining and Calling Functions

To define a function in Python, you use the def keyword, followed by the function name and parentheses. You can also include parameters inside the parentheses if the function needs input values. The function body contains the code to be executed, and it must be indented.

Syntax of a Function Definition

def function_name(parameters):
# Code to be executed
return result
  • def: Keyword to define a function.
  • function_name: The name you give to the function.
  • parameters: Optional inputs the function takes (can be zero or more).
  • return: Optional keyword to return a value from the function.

Example: Simple Function

Let’s define a simple function that prints a greeting message:

def greet():
print("Hello, welcome to the program!")

To call this function and execute its code, you use its name followed by parentheses:

greet()

When you run this code, it outputs:

Hello, welcome to the program!

3.3.2 Functions with Parameters

Functions can take parameters (also known as arguments) that allow you to pass values into them. Parameters make functions more flexible and reusable because you can provide different inputs each time you call the function.

Example: Function with Parameters

Here’s a function that takes a name as a parameter and prints a personalized greeting message:

def greet(name):
print(f"Hello, {name}! Welcome to the program!")

To call this function and provide an argument, you do:

greet("Alice")
greet("Bob")

When you run this code, it outputs:

Hello, Alice! Welcome to the program!
Hello, Bob! Welcome to the program!

3.3.3 Functions with Return Values

Functions can also return values using the return statement. Returning values allows the function to output results that can be used elsewhere in the program.

Example: Function with Return Value

Here’s a function that takes two numbers, adds them, and returns the result:

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

To call this function and use the returned value, you do:

result = add(10, 5)
print("Result:", result)

When you run this code, it outputs:

Result: 15

Using Functions in an Interactive Calculator

Let’s make our calculator more modular by using functions. We will define functions for each operation and call them based on user input.

def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Error! Division by zero."
def calculator():
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Enter the operation (+, -, *, /): ")
if operation == "+":
result = add(num1, num2)
elif operation == "-":
result = subtract(num1, num2)
elif operation == "*":
result = multiply(num1, num2)
elif operation == "/":
result = divide(num1, num2)
else:
result = "Invalid operation."
print("The result is:", result)
calculator()

In this example:

  • We defined functions for addition, subtraction, multiplication, and division.
  • The calculator function handles user input and calls the appropriate function based on the chosen operation.
  • This modular approach makes the code more organized and easier to maintain.

Summary of Functions

  • Defining Functions: Use the def keyword followed by the function name and parentheses.
  • Calling Functions: Use the function name followed by parentheses.
  • Parameters: Functions can take input values (parameters) to perform operations.
  • Return Values: Functions can return values using the return statement.

By mastering functions, you can write modular, reusable, and efficient code. Functions are a cornerstone of programming and are used extensively in all types of software development. Practice writing and using functions to become proficient in creating organized and scalable programs.

Level 1 Exercises

Define a function named greet that takes no parameters and prints a greeting message. Call the function to display the message.

Define a function named greet that takes a name as a parameter and prints a personalized greeting message. Call the function with different names.

Define a function named square that takes a number as a parameter and returns its square. Call the function with different numbers and print the results.

Level 2 Exercises

Define a function named fahrenheit_to_celsius that takes a temperature in Fahrenheit and returns the temperature in Celsius. Call the function and print the result.

Define a function named circle_area that takes the radius as a parameter and returns the area of the circle. Call the function with different radii and print the results.

Level 3 Exercises

Combine the functions you have created into a single formula calculator program. The program should ask the user to choose a formula and call the appropriate function to solve the formula with proper parameters.