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.
if
Statement: Executes a block of code if the condition is true.elif
Statement: Stands for “else if” and checks another condition if the previousif
condition is false.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:
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:
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.
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 previousif
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:
- Addition (
+
): Adds two numbers. - Subtraction (
-
): Subtracts one number from another. - Multiplication (
*
): Multiplies two numbers. - Division (
/
): Divides one number by another and returns a float. - Integer Division (
//
): Divides one number by another and returns an integer. - Modulus (
%
): Returns the remainder of a division. - Exponentiation (
**
): Raises one number to the power of another.
Example: Basic Math Operations
Let’s see some examples of these operations in action:
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.
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
: 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:
To call this function and execute its code, you use its name followed by parentheses:
When you run this code, it outputs:
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:
To call this function and provide an argument, you do:
When you run this code, it outputs:
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:
To call this function and use the returned value, you do:
When you run this code, it outputs:
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.
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.