189k views
0 votes
A half-life is the amount of time it takes for a substance or entity to fall to half its original value. Caffeine has a half-life of about 6 hours in humans. Given caffeine amount (in mg) as input, output the caffeine level after 6, 12, and 24 hours. Use a string formatting expression with conversion specifiers to output the caffeine amount as floating-point numbers.

Output each floating-point value with two digits after the decimal point, which can be achieved as follows: print(f'{your_value:.2f}')
Ex: If the input is: 100 the output is: After 6 hours: 50.00mg After 12 hours: 25.00mg After 24 hours: 6.25mg Note: A cup of coffee has about 100mg. A soda has about 40mg. An "energy" drink (a misnomer) has between 100mg and 200mg.

1 Answer

3 votes

# Constants

CAFFEINE_HALF_LIFE = 6 # hours

def main():

# Get initial caffeine amount

initial_amount = float(input("Enter the initial caffeine amount (in mg): "))

# Calculate and print caffeine remaining after 6, 12, 24 hours

print_caffeine_remaining(initial_amount, 6)

print_caffeine_remaining(initial_amount, 12)

print_caffeine_remaining(initial_amount, 24)

def print_caffeine_remaining(initial_amount, hours_passed):

"""Prints the caffeine remaining after the given hours, rounded to 2 decimals"""

amount_remaining = calculate_remaining(initial_amount, hours_passed)

print(f"After {hours_passed} hours: {amount_remaining:.2f}mg")

def calculate_remaining(initial_amount, hours_passed):

"""Calculates the caffeine remaining based on half-life formula"""

return initial_amount * (0.5)**(hours_passed / CAFFEINE_HALF_LIFE)

if __name__ == "__main__":

main()

A half-life is the amount of time it takes for a substance or entity to fall to half-example-1
User Althor
by
7.9k points

No related questions found