# Tactiverge Academy — companion code for "Decisions, loops, functions and a first simulation"
# Lesson: https://tactiverge.win/academy/computational-engineering/python-fundamentals/control-flow-functions-simulation/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
temperature = 31.5   # °C

if temperature > 30:
    print("Warning: too hot")
elif temperature < 10:
    print("Warning: too cold")
else:
    print("Temperature OK")


# ── Example 2 ────────────────────────────────────────
readings = [12.1, 12.3, 55.0, 12.2, 12.4]

for r in readings:
    print(r)


# ── Example 3 ────────────────────────────────────────
for i, r in enumerate(readings):
    if r > 50:
        print(f"Reading {i} looks wrong: {r}")


# ── Example 4 ────────────────────────────────────────
height = 100.0   # cm
bounces = 0

while height > 1.0:
    height = height * 0.6
    bounces += 1      # same as bounces = bounces + 1

print(f"{bounces} bounces, last height {height:.3f} cm")


# ── Example 5 ────────────────────────────────────────
def current_ma(voltage, resistance):
    """Return the current in milliamps through a resistor (Ohm's law)."""
    return voltage / resistance * 1000

print(current_ma(9.0, 450.0))           # 20.0
print(f"{current_ma(5.0, 220.0):.1f}")  # 22.7


# ── Example 6 ────────────────────────────────────────
def average(values):
    return sum(values) / len(values)

def keep_in_range(values, low, high):
    kept = []
    for v in values:
        if low <= v <= high:
            kept.append(v)
    return kept

readings = [12.1, 12.3, 55.0, 12.2, 12.4]
clean = keep_in_range(readings, 0, 50)

print(f"All readings: {average(readings):.2f}")   # 20.80
print(f"In range:     {average(clean):.2f}")      # 12.25


# ── Example 7 ────────────────────────────────────────
temperature = 90.0   # °C, starting temperature
room = 20.0          # °C
k = 0.1              # cooling constant, per minute (an assumed value)
dt = 1.0             # time step, minutes

for minute in range(1, 11):
    temperature = temperature - k * (temperature - room) * dt
    print(f"t = {minute:2d} min   T = {temperature:5.1f} °C")


# ── Example 8 ────────────────────────────────────────
def minutes_to_cool(start, room, k, target, dt):
    t = 0.0
    temp = start
    while temp > target:
        temp = temp - k * (temp - room) * dt
        t += dt
    return t

print(round(minutes_to_cool(90.0, 20.0, 0.1, 60.0, dt=1.0), 2))   # 6.0
print(round(minutes_to_cool(90.0, 20.0, 0.1, 60.0, dt=0.1), 2))   # 5.6
