Skip to the content.

3.3 Hacks

hacks

Popcorn hack 1

def output(x):
    print(2 * (x + 8) - 1)

output(5)
   
25

Popcorn hack 2

number1 = 3
number2 = 1
number3 = number1 % number2
number4 = number3 * number1 + 50
print(number4)
50

Popcorn Hack 3


numbers = [1, 2, 3, 4, 5]

for num in numbers:
    remainder = num % 2
    if remainder == 0:
        print(num, "is divisible by 2")
    else:
        print("The remainder when", num, "is divided by 2 is", remainder)
The remainder when 1 is divided by 2 is 1
2 is divisible by 2
The remainder when 3 is divided by 2 is 1
4 is divisible by 2
The remainder when 5 is divided by 2 is 1

HW Hack

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n - 1):
        a, b = b, a + b
    return a

term = int(input("Enter the term of the Fibonacci sequence: "))
print(f"The Fibonacci number at position {term} is {fibonacci(term)}.")

def calculate_area():
    shape = input("Enter the shape (circle, square, rectangle): ").lower()

    if shape == "circle":
        radius = float(input("Enter the radius: "))
        area = 3.14 * radius ** 2
    elif shape == "square":
        side = float(input("Enter the side length: "))
        area = side ** 2
    elif shape == "rectangle":
        length = float(input("Enter the length: "))
        width = float(input("Enter the width: "))
        area = length * width
    else:
        return "Invalid shape."

    print(f"The area of the {shape} is: {area}")

calculate_area()

The Fibonacci number at position 5 is 3.
The area of the circle is: 50.24

Challenge

import math

def calculate_volume():
    shape = input("Enter the shape (rectangular prism, sphere, pyramid): ").lower()

    if shape == "rectangular prism":
        length = float(input("Enter the length: "))
        width = float(input("Enter the width: "))
        height = float(input("Enter the height: "))
        volume = length * width * height

    elif shape == "sphere":
        radius = float(input("Enter the radius: "))
        volume = (4/3) * math.pi * radius ** 3

    elif shape == "pyramid":
        base_area = float(input("Enter the base area: "))
        height = float(input("Enter the height: "))
        volume = (1/3) * base_area * height

    else:
        return "Invalid shape."

    print(f"The volume of the {shape} is: {volume:.2f}")

calculate_volume()

The volume of the sphere is: 523.60