A curated collection of foundational Python projects demonstrating essential concepts such as control flow, user input handling, looping constructs, error checking, console manipulation, and time delays.
Perfect for beginners looking to understand Python basics or developers needing a reference for basic script templates.
Here is a look at the files included in this repository:
├── hello_world.py # Basic verification script
├── basic_calculator.py # Conditional branch calculator
├── looped_calculator.py # Calculator with continuation logic
├── robust_calculator.py # Menu-driven calculator with robust exception handling
├── countdown_timer.py # Console timer with dynamic screen clearing
└── README.md # Repository documentation (this file)
- Source File:
hello_world.py - Description: A simple entry-point script to verify that your local Python runtime environment is set up correctly.
- Usage:
python hello_world.py
- Source File:
basic_calculator.py - Description: Prompts the user to input two numbers and select an arithmetic operator (
+,-,*,/). It utilizes cleanif-elif-elselogic to calculate and output the results. - Usage:
python basic_calculator.py
- Source File:
looped_calculator.py - Description: Extends the basic calculator by wrapping the operations in a
while Trueloop. This allows users to execute multiple calculations back-to-back without restarting the script, exiting only when the user declines to continue. - Usage:
python looped_calculator.py
- Source File:
robust_calculator.py - Description: A professional menu-driven CLI calculator implementing rigorous input verification and crash protection.
- Key Handling Blocks:
ValueError: Catches invalid non-numeric inputs (e.g. letters) during menu selection or number input.ZeroDivisionError: Safely handles and explains attempts to divide by zero rather than crashing.KeyboardInterrupt: Allows the user to exit cleanly at any time usingCtrl+Cwith a friendly termination message.
- Usage:
python robust_calculator.py
- Source File:
countdown_timer.py - Description: A dynamic console countdown utility that displays remaining time in
MM:SSformat. It imports the nativetimeandosmodules. - Key Features:
- Dynamic Refreshing: Uses
os.system('cls' if os.name == 'nt' else 'clear')to clear the terminal window on each second tick, updating the countdown in place. - Case-Insensitive OS Clears: Supports both Windows (cmd/PowerShell) and POSIX-compliant terminal environments (Linux/macOS).
- Dynamic Refreshing: Uses
- Usage:
python countdown_timer.py
These scripts are structured to help students progress from basic syntax to writing production-like, error-resilient Python CLI applications. Here is an in-depth breakdown of the core programming concepts demonstrated in this repository.
- Console Input (
input()): In Python, theinput()function always reads data from the user as a string (str). - Explicit Type Casting: To perform arithmetic, strings must be explicitly cast to numeric types using
int()(integers) orfloat()(decimal numbers). - The Casting Trap: If a student enters letters (like
"abc") when a script executesfloat(input()), Python will raise aValueErrorand terminate the script immediately.Lesson: Always validate or catch exceptions on inputs that rely on casting (see
robust_calculator.py).
- Conditional Branching (
if-elif-else): Evaluates boolean conditions sequentially from top to bottom. - Mutual Exclusion: Once a condition evaluates to
True, Python executes its corresponding block and skips the remaining conditions. - Fallback Strategy: The
elseblock serves as a catch-all for any user actions that do not match the expected conditions (e.g., inputting an invalid operator).
- Infinite Loops (
while True:): Used to keep a script running until an explicit exit condition is met. - Breaking the Loop (
break): Thebreakkeyword immediately terminates the innermost loop execution, jumping to the first line of code outside the loop block. - Skipping Code (
continue): Thecontinuekeyword bypasses the rest of the code in the current loop iteration and moves execution back to the beginning of the loop (e.g., restarting the menu choice after an invalid input).
In robust_calculator.py, we use a try-except block to intercept runtime errors before they cause the program to crash:
ValueError: Catches cases where non-numeric inputs fail the conversion tointorfloat.ZeroDivisionError: Prevents runtime crashes when dividing a number by zero.KeyboardInterrupt: Triggered when a user forces an exit usingCtrl+C. Intercepting this allows the script to display a clean exit message instead of a messy traceback.- Scoping: Note that the
try-exceptblock is placed inside thewhileloop. This ensures that when an error is caught, the program prints a helpful error message and loops back to let the user try again, rather than shutting down completely.
- Library Imports (
import): Extends Python's capabilities using built-in standard libraries (osandtime). - Dynamic Refreshes:
os.system()runs a system shell command. By executingcls(on Windows) orclear(on Mac/Linux), we clean up old terminal logs to show only the relevant active content. - Thread Sleep:
time.sleep(1)suspends program execution for exactly one second. It is the core function used to create natural real-time timers.
Test your understanding by looking at the code and answering the following questions:
-
Scope of Exception Handlers:
- Question: In
robust_calculator.py, what would happen if the entirewhile True:loop was placed inside a singletryblock, instead of thetry-exceptblock being inside the loop? - Answer: If an exception occurred, the
exceptblock would run and the program would exit immediately, defeating the purpose of the infinite loop which is to keep the calculator running.
- Question: In
-
Zero Division Logic:
- Question: In
basic_calculator.py, what happens if the user inputs0as the second number and selects division (/)? - Answer: The program will crash and display a
ZeroDivisionError: float division by zerotraceback because it lacks exception handling.
- Question: In
-
String Case Normalization:
- Question: Why is
.lower()used inchoice.lower() != "yes"insidelooped_calculator.py? - Answer: It converts the user's input to lowercase, ensuring that inputs like
"YES","Yes", or"yEs"are correctly matched, improving the user experience.
- Question: Why is
-
Formatting Prefixes:
- Question: In
countdown_timer.py, what does the format specifier:02ddo in the statementf"{mins:02d}:{secs:02d}"? - Answer: It formats the integer to be at least 2 digits wide, padding it with a leading zero if it is a single digit (e.g. formatting
5seconds as05instead of5).
- Question: In
-
Clone the Repository:
git clone https://github.com/your-username/python-basics.git cd python-basics -
Verify Python Installation: Ensure you have Python 3.8 or higher installed:
python --version
-
Run any Script: Execute the scripts directly using python command in your terminal:
python robust_calculator.py
This repository is available under the MIT License. Feel free to use, modify, and distribute the code.