Mastering Python: While Loops and Format Specifiers for Cleaner Code

🚀 I Learned Two Python Concepts Today That Instantly Made My Code Better Today I practiced two important Python concepts: • While Loops • Format Specifiers (Python f-string formatting) Both are heavily used in real programs for input validation and clean output formatting. 🔁 1. While Loop — Repeating Code Until a Condition Changes A while loop repeatedly executes code as long as a condition is true. age = int(input("Enter your age: ")) while age < 0: print("Age cannot be negative") age = int(input("Enter your age: ")) print(f"You are {age} years old") 📌 What Happens 1️⃣ User enters age. 2️⃣ If the value is negative, an error appears. 3️⃣ The program asks again until a valid value is entered. 🌍 Real‑world uses • Input validation • Login retry systems • Game loops • Menu programs For example, an ATM keeps asking for a PIN until it is correct. 🔄 2. Infinite Loop + Break (Common Pattern) while True: principal = float(input("Enter principal amount: ")) if principal < 0: print("Principal cannot be negative") else: break 🧠 Logic • while True creates a continuous loop • Invalid input → error message • Valid input → break stops the loop This pattern is widely used for reliable user input handling. 🎯 3. Format Specifiers — Clean Output Formatting Python f-strings allow precise formatting of numbers. General syntax {value:flags} Example value price = 3000.1459 🔢 Round to specific decimals print(f"{price:.2f}") Output 3000.15 .2f → round to 2 decimal places (very common in finance). 0️⃣ Zero padding / fixed width print(f"{price:010}") Example 0003000.1459 Useful for IDs, invoices, or structured tables. 📊 Number alignment Left {value:<10} Right {value:>10} Center {value:^10} Helpful when printing tables or reports. 💰 Sign and comma formatting print(f"{price:+,.2f}") Output +3,000.15 Meaning: • + show sign • , thousands separator • .2f two decimals Common in financial dashboards and reports. 🧮 Example: Compound Interest total = principal * pow((1 + rate/100), time) print(f"Balance after {time} years: ${total:.2f}") This demonstrates: • while-loop validation • calculation logic • formatted output 📚 What I Practiced Today • While loops • Infinite loop pattern • Input validation • Python format specifiers • Clean numeric output Programming is about controlling logic and handling real data correctly. 🔗 Code Repository GitHub: https://lnkd.in/dFtwyqEw #python #pythonlearning #codingjourney #programming #softwaredeveloper #learnpython #developers #100daysofcode #computerscience

  • graphical user interface

To view or add a comment, sign in

Explore content categories