Skip to content

maddyinthematrix/python-basics-tasks

Repository files navigation

Python Basics: Calculators & Countdown Timer

Python Version License: MIT

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.


📂 Project Structure

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)

🚀 Projects Detailed Breakdown

1. Hello World

  • 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

2. Basic Calculator

  • Source File: basic_calculator.py
  • Description: Prompts the user to input two numbers and select an arithmetic operator (+, -, *, /). It utilizes clean if-elif-else logic to calculate and output the results.
  • Usage:
    python basic_calculator.py

3. Looped Calculator

  • Source File: looped_calculator.py
  • Description: Extends the basic calculator by wrapping the operations in a while True loop. 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

4. Robust Calculator (with Exception Handling)

  • 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 using Ctrl+C with a friendly termination message.
  • Usage:
    python robust_calculator.py

5. Dynamic Countdown Timer

  • Source File: countdown_timer.py
  • Description: A dynamic console countdown utility that displays remaining time in MM:SS format. It imports the native time and os modules.
  • 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).
  • Usage:
    python countdown_timer.py

🧠 Key Python Concepts & Student Learning Guide

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.


1. Data Input, Validation, and Type Casting

  • Console Input (input()): In Python, the input() 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) or float() (decimal numbers).
  • The Casting Trap: If a student enters letters (like "abc") when a script executes float(input()), Python will raise a ValueError and terminate the script immediately.

    Lesson: Always validate or catch exceptions on inputs that rely on casting (see robust_calculator.py).


2. Decision Making & Logic Structures

  • 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 else block serves as a catch-all for any user actions that do not match the expected conditions (e.g., inputting an invalid operator).

3. Iteration and Loop Control Flow

  • Infinite Loops (while True:): Used to keep a script running until an explicit exit condition is met.
  • Breaking the Loop (break): The break keyword immediately terminates the innermost loop execution, jumping to the first line of code outside the loop block.
  • Skipping Code (continue): The continue keyword 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).

4. Exception Handling & Error Boundaries

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 to int or float.
  • ZeroDivisionError: Prevents runtime crashes when dividing a number by zero.
  • KeyboardInterrupt: Triggered when a user forces an exit using Ctrl+C. Intercepting this allows the script to display a clean exit message instead of a messy traceback.
  • Scoping: Note that the try-except block is placed inside the while loop. 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.

5. Operating System Controls & External Libraries

  • Library Imports (import): Extends Python's capabilities using built-in standard libraries (os and time).
  • Dynamic Refreshes: os.system() runs a system shell command. By executing cls (on Windows) or clear (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.

❓ Student Review & Self-Assessment Questions

Test your understanding by looking at the code and answering the following questions:

  1. Scope of Exception Handlers:

    • Question: In robust_calculator.py, what would happen if the entire while True: loop was placed inside a single try block, instead of the try-except block being inside the loop?
    • Answer: If an exception occurred, the except block would run and the program would exit immediately, defeating the purpose of the infinite loop which is to keep the calculator running.
  2. Zero Division Logic:

    • Question: In basic_calculator.py, what happens if the user inputs 0 as the second number and selects division (/)?
    • Answer: The program will crash and display a ZeroDivisionError: float division by zero traceback because it lacks exception handling.
  3. String Case Normalization:

    • Question: Why is .lower() used in choice.lower() != "yes" inside looped_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.
  4. Formatting Prefixes:

    • Question: In countdown_timer.py, what does the format specifier :02d do in the statement f"{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 5 seconds as 05 instead of 5).

🛠️ How to Get Started Locally

  1. Clone the Repository:

    git clone https://github.com/your-username/python-basics.git
    cd python-basics
  2. Verify Python Installation: Ensure you have Python 3.8 or higher installed:

    python --version
  3. Run any Script: Execute the scripts directly using python command in your terminal:

    python robust_calculator.py

📄 License

This repository is available under the MIT License. Feel free to use, modify, and distribute the code.

About

A collection of beginner-friendly Python CLI programs featuring basic and looped calculators, robust error boundaries (try-except), and a dynamic countdown timer.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages