Quick actions

cmd+k|ctrl+k

Navigation

Languages

Phone battery While Loop example

Snippet info

Language

Python

Visibility

public

Author

tonyngswell

Created

2026-04-30T13:10:03.406139Z

Updated

2026-04-30T13:10:03.406139Z

import time # This helps us slow down the loop so we can read it

battery_level = 20  # Starting at 20 for a quick demo
power_button_pressed = False 

print("--- Phone Powered On ---")

while battery_level >= 0:
    print(f"Battery at: {battery_level}%")
    
    # 1. The 'Warning' logic (similar to your 'x == 4' example)
    if battery_level == 10:
        print("LOW BATTERY WARNING! Switching to Power Save Mode...")
        battery_level -= 1
        time.sleep(1)
        continue # Skip the rest and go back to check the condition
    
    # 2. The 'Manual Break' logic
    if power_button_pressed:
        print("Manual Shutdown initiated...")
        break
    
    # 3. The Natural End
    if battery_level == 0:
        print("Battery empty.")
        break # Exit the loop because we can't run on 0
        
    # Standard battery drain
    battery_level -= 1
    time.sleep(0.5) # Pauses for half a second to simulate time passing

else:
    # This only runs if the loop ends without a 'break'
    # Since we used 'break' for 0%, this line won't actually trigger here!
    print("System Standby")

print("--- Screen Black: Phone is Off ---")
INFO