Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.3 Python Mathematical Hacks
Student led teaching on Mathematical Expressions. Learn how mathematical expressions involve using arithmetic operators (like addition, subtraction, multiplication, and division) to perform calculations
Operator | Description | Python Example |
---|---|---|
P - Parentheses | Operations inside () |
(3 + 2) * 4 = 20 |
E - Exponents | Powers (using ** operator) |
2 ** 3 = 8 |
M - Multiplication | Multiply two numbers | 3 * 4 = 12 |
D - Division | Divide two numbers | 12 / 3 = 4.0 |
F - Floor Division | Division with integer result | 12 // 5 = 2 |
M - Modulus | Remainder of division | 12 % 5 = 2 |
A - Addition | Sum of numbers | 3 + 5 = 8 |
S - Subtraction | Difference between numbers | 10 - 4 = 6 |
Example Hack #1 (Function for Basic Arithmetic Operations)
def basicOperations(a, b):
sum = a + b
difference = a - b
product = a * b
quotient = a / b
remainder = a % b
print(f"Addition: {a} + {b} = {sum}")
print(f"Subtraction: {a} - {b} = {difference}")
print(f"Multiplication: {a} * {b} = {product}")
print(f"Division: {a} / {b} = {quotient}")
print(f"Modulus: {a} % {b} = {remainder}")
basicOperations(10, 5)
Example Hack #1 (Fibbonaci Sequence)
def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
a = 0
b = 1
for i in range(2, n):
next = a + b
a = b
b = next
return b
n = 7 # Find the 7th Fibonacci number
print(f"The {n}th Fibonacci number is: {fibonacci(n)}")
Popcorn Hacks
- Hack #1
- Define a list of integers
- Compute the sum of all of the integers
- Print the sum
- Hack #2
- Prompt the user to enter the price per bag of popcorn.
- Prompt the user to enter the number of bags they want to buy.
- Calculate the total cost using multiplication.
- Print the total cost.
- Hack #3
- Prompt the user to enter a number n.
- Initialize total_sum to 0.
- Use a loop to iterate from 1 to n.
- Add each number to total_sum.
- Print the total_sum.
Homework Hacks
Now that we have learned about these various math expressions and operations, there are some hacks that you can complete.
- Write a function that has a defined list of integers. The function should:
- Compute the arithmetic mean.
- Compute the median.
- Print both results.
- Make a function that takes one variable a. This function should list the sequence of numbers in the Collatz problem. The Collatz Problem is a math problem where you start with a positive integer and if it is odd you multiply by 3 and add 1, and if it is even you divide by 2. Use conditionals and keep repeating or iterating this process, and eventually you should reach 1 no matter what number is taken as input. Make an array that starts at the variable a, and keeps adding integers until it reaches 1, and print the sequence.