Showing posts with label Python Programming. Show all posts
Showing posts with label Python Programming. Show all posts

Python GUI Tutorial for Beginners – Create Simple UIs with Tkinter

← Back to Home

 

๐Ÿ Python UI Programming Series — Part 1: Getting Started with Tkinter


๐Ÿ“˜ Overview

Python is a versatile language with powerful libraries for creating Graphical User Interfaces (GUIs). One of the most beginner-friendly and widely used is Tkinter — it comes bundled with Python and provides all the basic tools to build windows, buttons, input fields, and more.

In this first article, we’ll cover:

  • What is a UI in Python?

  • Introduction to Tkinter

  • Creating your first GUI window

  • Adding widgets: Labels, Buttons, and Entry

  • Handling events with functions


๐Ÿง  What is a UI in Python?

A User Interface (UI) allows users to interact with software through graphical elements like windows, buttons, text fields, etc., instead of typing commands.

Python supports many UI libraries:

  • Tkinter – built-in and beginner-friendly

  • PyQt – feature-rich, better for complex UIs

  • Kivy – used for multitouch apps and mobile support

  • Dear PyGui, PySide, and others...

We’ll start with Tkinter, then explore others in future parts.


๐Ÿงฐ Why Tkinter?

✅ Built-in with Python
✅ Easy to learn
✅ Cross-platform
✅ Great for prototyping and small projects


๐Ÿ–ผ️ Your First GUI with Tkinter

✅ Step 1: Basic Window

import tkinter as tk

# Create a main window
root = tk.Tk()
root.title("My First GUI")
root.geometry("300x200")  # Width x Height

# Start the GUI event loop
root.mainloop()

๐ŸŽฏ This creates a blank window titled "My First GUI".


๐Ÿงฑ Adding Widgets: Labels, Buttons, and Entry

Let’s add some common UI elements:

✅ Step 2: Label + Entry + Button

import tkinter as tk

def greet_user():
    username = entry.get()
    label_result.config(text=f"Hello, {username}!")

root = tk.Tk()
root.title("Greeting App")
root.geometry("300x150")

label_prompt = tk.Label(root, text="Enter your name:")
label_prompt.pack(pady=5)

entry = tk.Entry(root)
entry.pack(pady=5)

button_greet = tk.Button(root, text="Greet", command=greet_user)
button_greet.pack(pady=5)

label_result = tk.Label(root, text="")
label_result.pack(pady=5)

root.mainloop()

๐Ÿง  What’s happening here:

  • Label shows text.

  • Entry allows input.

  • Button triggers a function (greet_user()).

  • config() updates the label text dynamically.


๐Ÿ’ก Recap

In this first part, you've learned:

  • What a Python GUI is

  • Why Tkinter is a good choice

  • How to create a window and basic widgets

  • How to handle user input and events


๐Ÿš€ Coming Up in Part 2:

“Layouts, Frames, and UI Organization”

  • Learn how to organize widgets neatly using pack(), grid(), and place().

  • Nest widgets using frames and build a cleaner layout.


Unit Testing in Python: Get Started with unittest & pytest

← Back to Home


Unit Testing in Python: Getting Started with unittest and pytest


Introduction

Writing code is only half the battle—testing it ensures your program works as expected and helps catch bugs early. Unit testing is a fundamental software development practice that involves testing small parts (units) of your code independently.

Python offers powerful testing frameworks like the built-in unittest module and the popular third-party tool pytest. In this guide, you’ll learn how to write and run unit tests with both, helping you improve code quality and reliability.


What is Unit Testing?

Unit testing focuses on verifying that individual pieces of code (functions, classes, methods) behave correctly in isolation. By writing tests for these units, you create a safety net that alerts you when changes break functionality.


Using Python’s Built-in unittest Module

Python comes with the unittest framework pre-installed.

Writing Your First Test Case

Suppose you have a simple function:

def add(a, b):
    return a + b

Here’s how to test it with unittest:

import unittest
from your_module import add  # Replace with actual module name

class TestAddFunction(unittest.TestCase):
    
    def test_add_positive_numbers(self):
        self.assertEqual(add(2, 3), 5)

    def test_add_negative_numbers(self):
        self.assertEqual(add(-1, -1), -2)

if __name__ == '__main__':
    unittest.main()

Run this test file, and unittest will report if the tests pass or fail.


Introduction to pytest

pytest is a popular third-party testing tool that simplifies writing tests and offers advanced features.

Installing pytest

pip install pytest

Writing Tests with pytest

You don’t need to use classes or inherit from test frameworks. Just write test functions:

from your_module import add

def test_add_positive():
    assert add(2, 3) == 5

def test_add_negative():
    assert add(-1, -1) == -2

Run tests using the command:

pytest

Key Differences Between unittest and pytest

Feature unittest pytest
Test style                 Class-based             Function-based
Setup/teardown                 Methods like setUp, tearDown             Fixtures with decorators
Assertions                 Specific assert methods             Python’s native assert
Plugins                 Limited             Extensive plugin ecosystem
Ease of use                 More boilerplate             Minimal code, more expressive

Example: Testing a Simple Function

Suppose your function calculates the factorial of a number:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

unittest version

import unittest
from your_module import factorial

class TestFactorial(unittest.TestCase):

    def test_factorial_zero(self):
        self.assertEqual(factorial(0), 1)

    def test_factorial_positive(self):
        self.assertEqual(factorial(5), 120)

if __name__ == '__main__':
    unittest.main()

pytest version

from your_module import factorial

def test_factorial_zero():
    assert factorial(0) == 1

def test_factorial_positive():
    assert factorial(5) == 120

Running Tests and Interpreting Results

  • With unittest, run your test file directly.

  • With pytest, run the pytest command in your terminal.

Both tools will tell you which tests passed or failed and provide helpful output to diagnose issues.


Tips for Effective Testing

  • Write tests for edge cases and normal cases.

  • Use meaningful test names.

  • Test one thing per test function.

  • Use assertions effectively to validate expected results.

  • Consider test coverage tools like coverage.py to measure how much code your tests cover.


Conclusion

Unit testing helps ensure your Python code is reliable, maintainable, and bug-free. Whether you choose Python’s built-in unittest or the powerful pytest, adding tests to your workflow is a valuable skill.

Start small—test your utility functions—and gradually expand coverage to larger components. 

For more Python insights and practical guides, check out our other posts on Python Projects for Beginners and Publishing Python Packages.


What’s Next?

๐Ÿ‘‰ In Next article, we’ll learn Python List Comprehensions


Working with APIs in Python: Beginner’s Guide with Real API Example

← Back to Home

Working with APIs in Python: A Beginner’s Guide (with Real API Example)


Introduction

APIs (Application Programming Interfaces) act as bridges between different software systems, enabling them to communicate and share data. They power many modern web applications, allowing you to retrieve information like weather forecasts, social media feeds, or stock prices — all from external sources.

For Python developers, APIs open a world of possibilities. Whether you want to build apps that consume external data or automate tasks by connecting services, understanding how to work with APIs is crucial.

In this guide, you’ll learn the basics of APIs, how to make requests in Python using the powerful requests library, and work through a practical example using the free JSONPlaceholder API. By the end, you’ll be equipped to start integrating APIs into your own projects.


What You Need Before Starting

  • Python 3.x installed on your computer.

  • The requests library (a user-friendly HTTP library). Install it by running:

pip install requests
  • A text editor or IDE like VS Code, PyCharm, or even a simple Notepad.


What is an API?

An API defines rules and protocols for how software components should interact. For example, a weather service might expose an API that lets you ask for current weather conditions by sending a request to a specific URL.

Understanding API Endpoints

An API endpoint is simply a URL where a specific service is accessible. For instance:

  • https://api.weather.com/current might return current weather data.

  • https://jsonplaceholder.typicode.com/posts returns sample blog posts.


HTTP Methods Explained

APIs typically use HTTP methods to specify the desired action:

Method Purpose Example Use
GET         Retrieve data             Fetch user details or blog posts
POST         Submit new data             Create a new user or post
PUT         Update existing data             Change a post’s content
DELETE         Remove data             Delete a user account

This guide will focus on GET requests to fetch data.


Step 1: Making Your First API Request in Python

Let's start with a simple example of fetching data from JSONPlaceholder, which provides fake API data for testing:

import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

print("Status Code:", response.status_code)  # Should print 200 for success
print("Response Text:", response.text)       # Raw response content

Here, requests.get() sends a GET request to the API endpoint. The response contains status and content.


Step 2: Parsing JSON Data

Most APIs return data in JSON (JavaScript Object Notation) format, which is easy for humans and machines to read.

Use .json() to convert the response to a Python dictionary:

data = response.json()
print(data)
print("Post Title:", data['title'])

This allows you to access specific parts of the response easily, like the post’s title.


Step 3: Fetching Multiple Records

You can also fetch multiple records by targeting the right endpoint:

response = requests.get('https://jsonplaceholder.typicode.com/posts')
posts = response.json()

for post in posts[:5]:  # Show only first 5 posts
    print(f"Post ID {post['id']}: {post['title']}")

This fetches a list of posts and loops through the first five, printing their titles.


Step 4: Handling API Request Errors

Real-world APIs can fail for various reasons — network issues, wrong endpoints, or rate limits.

Handle errors gracefully using try-except blocks:

try:
    response = requests.get('https://jsonplaceholder.typicode.com/posts')
    response.raise_for_status()  # Raises HTTPError for bad status
    data = response.json()
    print("Data fetched successfully!")
except requests.exceptions.HTTPError as http_err:
    print(f"HTTP error occurred: {http_err}")
except requests.exceptions.ConnectionError:
    print("Failed to connect to the API.")
except Exception as err:
    print(f"An error occurred: {err}")

This ensures your program won’t crash and informs the user of problems.


Step 5: Adding Request Parameters

Many APIs support query parameters to filter or customize results.

For example, to get posts by a specific user:

params = {'userId': 1}
response = requests.get('https://jsonplaceholder.typicode.com/posts', params=params)
posts = response.json()

print(f"Posts by user 1:")
for post in posts:
    print(post['title'])

The params dictionary is automatically encoded into the URL.


Step 6: Practical Project Idea

Try building a simple command-line app that lets users enter a user ID and fetch their posts.

def get_user_posts(user_id):
    url = 'https://jsonplaceholder.typicode.com/posts'
    params = {'userId': user_id}
    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        posts = response.json()
        for post in posts:
            print(f"{post['id']}: {post['title']}")
    except requests.exceptions.RequestException as e:
        print("Error:", e)

if __name__ == "__main__":
    user_input = input("Enter User ID to fetch posts: ")
    if user_input.isdigit():
        get_user_posts(int(user_input))
    else:
        print("Please enter a valid number.")

Bonus Tips

  • Rate Limits: Some APIs limit how many requests you can make in a given time. Check API docs and respect limits.

  • Authentication: Many APIs require API keys or tokens for access. This guide covers public APIs, but you’ll want to learn how to handle auth for private ones.

  • API Documentation: Always refer to the API’s official docs for endpoints, params, and usage.


Conclusion

Working with APIs in Python unlocks endless possibilities for your projects. This guide showed you how to send requests, parse JSON data, handle errors, and customize queries using a real example API.

You can keep practicing with other APIs — like Twitter, GitHub, or OpenWeather — to deepen your skills.

If you want to explore more Python projects and packaging, check out these posts:


What’s Next?

๐Ÿ‘‰ In Next article, we’ll learn Unit Testing in Python


Top 10 Python Projects for Beginners (With Source Code and GitHub Links)

← Back to Home

 

๐Ÿ Top 10 Python Projects for Beginners (With Source Code and Diagrams)

Are you just starting out with Python and wondering what projects to build? Working on hands-on projects is one of the most effective ways to solidify your programming skills. In this blog post, we’ll explore 10 beginner-friendly Python projects, each with a diagram and source code to get you coding right away!


✅ 1. Number Guessing Game

๐Ÿ’ก Concept Diagram:

[Start] → [Generate Random Number] → [User Guesses] → [Check Guess]
   → [Too High/Low?] → [Try Again] → [Correct?] → [End]

๐Ÿง  What You'll Learn:

  • Loops

  • Conditional statements

  • Random module

๐Ÿงพ Source Code:

import random

number = random.randint(1, 100)
guess = None

while guess != number:
    guess = int(input("Guess a number between 1 and 100: "))
    if guess < number:
        print("Too low!")
    elif guess > number:
        print("Too high!")
    else:
        print("Congratulations! You guessed it.")

✅ 2. Simple Calculator

๐Ÿ’ก Concept Diagram:

[Input Num1] + [Input Operator] + [Input Num2] → [Perform Operation] → [Display Result]

๐Ÿง  What You'll Learn:

  • Functions

  • Basic arithmetic

  • Input handling

๐Ÿงพ Source Code:

def calculator():
    num1 = float(input("Enter first number: "))
    operator = input("Enter operator (+, -, *, /): ")
    num2 = float(input("Enter second number: "))

    if operator == '+':
        print(num1 + num2)
    elif operator == '-':
        print(num1 - num2)
    elif operator == '*':
        print(num1 * num2)
    elif operator == '/':
        print(num1 / num2)
    else:
        print("Invalid operator")

calculator()

✅ 3. To-Do List (Console-Based)

๐Ÿ’ก Concept Diagram:

[Menu] → [Add Task / View Tasks / Delete Task] → [List Updated]

๐Ÿง  What You'll Learn:

  • Lists

  • Menu-driven programs

๐Ÿงพ Source Code:

tasks = []

def show_menu():
    print("\n1. Add Task\n2. View Tasks\n3. Delete Task\n4. Exit")

while True:
    show_menu()
    choice = input("Enter choice: ")

    if choice == '1':
        task = input("Enter task: ")
        tasks.append(task)
    elif choice == '2':
        for i, task in enumerate(tasks):
            print(f"{i+1}. {task}")
    elif choice == '3':
        index = int(input("Enter task number to delete: ")) - 1
        if 0 <= index < len(tasks):
            tasks.pop(index)
        else:
            print("Invalid task number.")
    elif choice == '4':
        break
    else:
        print("Invalid choice.")

✅ 4. Dice Roller Simulator

๐Ÿ’ก Concept Diagram:

[Press Enter] → [Generate Random Number (1-6)] → [Display Dice Face]

๐Ÿง  What You'll Learn:

  • Random numbers

  • Loop control

๐Ÿงพ Source Code:

import random

while input("Roll the dice? (y/n): ").lower() == 'y':
    print(f"You rolled a {random.randint(1, 6)}")

✅ 5. Countdown Timer

๐Ÿ’ก Concept Diagram:

[Input Time] → [Countdown Loop] → [Time's Up]

๐Ÿง  What You'll Learn:

  • Time module

  • Loops

๐Ÿงพ Source Code:

import time

t = int(input("Enter time in seconds: "))

while t:
    mins, secs = divmod(t, 60)
    print(f'{mins:02d}:{secs:02d}', end='\r')
    time.sleep(1)
    t -= 1

print("Time's up!")

✅ 6. Basic Contact Book

๐Ÿ’ก Concept Diagram:

[Menu] → [Add/View/Delete Contact] → [Dictionary Update]

๐Ÿง  What You'll Learn:

  • Dictionaries

  • Functions

  • File handling (Optional)

๐Ÿงพ Source Code:

contacts = {}

def add_contact():
    name = input("Name: ")
    phone = input("Phone: ")
    contacts[name] = phone

def view_contacts():
    for name, phone in contacts.items():
        print(f"{name}: {phone}")

while True:
    print("\n1. Add\n2. View\n3. Exit")
    choice = input("Choice: ")
    if choice == '1':
        add_contact()
    elif choice == '2':
        view_contacts()
    elif choice == '3':
        break

✅ 7. Password Generator

๐Ÿ’ก Concept Diagram:

[Input Length] → [Randomly Select Characters] → [Display Password]

๐Ÿง  What You'll Learn:

  • random and string modules

  • String manipulation

๐Ÿงพ Source Code:

import random
import string

length = int(input("Enter password length: "))
chars = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(chars) for _ in range(length))
print("Generated password:", password)

✅ 8. QR Code Generator

๐Ÿ’ก Concept Diagram:

[Input Text/URL] → [Generate QR Image] → [Save File]

๐Ÿง  What You'll Learn:

  • External libraries (qrcode)

๐Ÿงพ Source Code:

pip install qrcode
import qrcode

data = input("Enter data to encode: ")
img = qrcode.make(data)
img.save("qrcode.png")
print("QR code saved as qrcode.png")

✅ 9. Weather App (Using API)

๐Ÿ’ก Concept Diagram:

[Input City] → [Fetch from OpenWeatherMap API] → [Display Weather]

๐Ÿง  What You'll Learn:

  • APIs

  • JSON parsing

  • requests module

๐Ÿงพ Source Code:

pip install requests
import requests

API_KEY = "your_api_key_here"
city = input("Enter city: ")
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"

response = requests.get(url)
data = response.json()

if data.get('main'):
    print(f"Temperature: {data['main']['temp']}°C")
else:
    print("City not found.")

✅ 10. Tic-Tac-Toe (2 Player Game)

๐Ÿ’ก Concept Diagram:

[Player 1 & 2 Turn] → [Update Board] → [Check Winner/Draw] → [Repeat]

๐Ÿง  What You'll Learn:

  • Lists

  • Game logic

  • Conditions

๐Ÿงพ Source Code:

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 5)

def check_winner(board):
    for row in board:
        if row.count(row[0]) == 3 and row[0] != ' ':
            return row[0]
    for col in range(3):
        if board[0][col] == board[1][col] == board[2][col] != ' ':
            return board[0][col]
    if board[0][0] == board[1][1] == board[2][2] != ' ':
        return board[0][0]
    if board[0][2] == board[1][1] == board[2][0] != ' ':
        return board[0][2]
    return None

board = [[" "]*3 for _ in range(3)]
turn = "X"

for _ in range(9):
    print_board(board)
    row = int(input(f"{turn}'s turn. Enter row (0-2): "))
    col = int(input(f"{turn}'s turn. Enter col (0-2): "))
    if board[row][col] == " ":
        board[row][col] = turn
        winner = check_winner(board)
        if winner:
            print_board(board)
            print(f"{winner} wins!")
            break
        turn = "O" if turn == "X" else "X"
    else:
        print("Cell already taken.")
else:
    print("It's a draw!")

๐Ÿ”š Final Thoughts

Each of these projects helps you practice essential Python concepts while having fun. Start with one, tweak it, break it, fix it — and watch your Python skills grow!

๐Ÿง  Click Next:  to explore the list of 100 python projects for beginners, intermediate and Expert level!


Python Modules Made Easy: A Beginner to Pro Guide with Examples

← Back to Home

 

๐Ÿ Python Modules: A Simple Guide for Beginners and Professionals

In Python, modules help you organize code, reuse functionality, and keep things clean and manageable. Whether you're a student just starting out or a developer building real-world applications, understanding modules is essential.


๐Ÿ“ฆ What is a Python Module?

A module is a file containing Python code — it can include functions, variables, and classes. By importing modules, you can access their functionality in your own programs.

Think of a module as a toolbox: instead of building tools from scratch every time, you just bring the right toolbox and use what’s inside.


๐Ÿ”— Built-in Modules

Python comes with many built-in modules like math, random, and datetime.

✏️ Example: Using the math module

import math

print(math.sqrt(16))     # 4.0
print(math.pi)           # 3.141592653589793

๐Ÿ“ Creating Your Own Module

You can create your own module by saving Python code in a .py file.

✏️ Step 1: Create a File mytools.py

def greet(name):
    return f"Hello, {name}!"

def square(x):
    return x * x

✏️ Step 2: Import and Use It

import mytools

print(mytools.greet("Alice"))   # Hello, Alice!
print(mytools.square(5))        # 25

✅ Now you're using your own module like a pro!


๐Ÿ“š Importing Modules in Different Ways

๐Ÿ”น import module

import math
print(math.ceil(2.3))

๐Ÿ”น from module import function

from math import sqrt
print(sqrt(16))

๐Ÿ”น import module as alias

import random as r
print(r.randint(1, 10))

๐Ÿ“ฆ Using External Modules (Installing with pip)

Python has thousands of third-party modules you can install using pip.

✏️ Example: Using requests (HTTP library)

pip install requests
import requests

response = requests.get("https://api.github.com")
print(response.status_code)

๐Ÿง  Why Use Modules?

  • ๐Ÿงฉ Organize code into logical files

  • ๐Ÿ” Reuse code in multiple programs

  • ๐Ÿ‘จ‍๐Ÿ‘ฉ‍๐Ÿ‘ง Collaborate in teams more easily

  • ๐Ÿ“ฆ Use powerful libraries from the community


⚠️ Best Practices

Do ✅ Don’t ❌
Use clear module names Avoid overly generic names
Group related functions Don’t mix unrelated code
Document your module Don’t leave magic code unexplained
Keep modules small & focused Avoid massive all-in-one files

๐Ÿงพ Summary

Feature Description
Module Definition         A file with Python code (.py)
Built-in Modules      math, random, datetime, etc.
Custom Modules         Your own reusable .py files
External Modules         Installed via pip (e.g. requests)
Import Syntax Options     import, from, as

๐ŸŽฏ Final Thoughts

Python modules are the building blocks of maintainable and scalable code. As you advance in Python, using and creating modules will become second nature — and a major boost to your coding productivity.


← Back to Home

Top 3 Python Script Mode Projects for Beginners – Calculator, Quiz Game & Number Checker

← Back to Home

 

๐Ÿ Python Script Mode Projects for Students – Simple & Fun Assignments

If you're just starting out with Python, learning through small projects is a great way to build your skills and confidence. Below are three beginner-level Python projects you can write and run using Script Mode.

These projects are ideal for:

  • Practice

  • School/college assignments

  • Building confidence with Python programming


๐Ÿ“ What You’ll Learn:

  • How to write a Python script in Script Mode

  • How to save, run, and test .py files

  • Real examples with download links for .py files


๐Ÿงฎ 1. Simple Calculator in Python

This script allows users to perform basic operations like addition, subtraction, multiplication, and division.

๐Ÿ’ก Features:

  • Menu-based interface

  • Input from user

  • Error handling for division by zero

✅ Sample Code:

# calculator.py

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Cannot divide by zero"
    return x / y

print("Select operation:")
print("1. Add\n2. Subtract\n3. Multiply\n4. Divide")

choice = input("Enter choice (1/2/3/4): ")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
    print("Result:", add(num1, num2))
elif choice == '2':
    print("Result:", subtract(num1, num2))
elif choice == '3':
    print("Result:", multiply(num1, num2))
elif choice == '4':
    print("Result:", divide(num1, num2))
else:
    print("Invalid input")

๐Ÿง  2. Quiz Game in Python

A fun multiple-choice quiz with score tracking.

✅ Sample Code:

# quiz_game.py

score = 0

print("Welcome to the Python Quiz!\n")

answer1 = input("Q1: What is the keyword to define a function in Python? \n(a) def\n(b) function\n(c) fun\nAnswer: ")
if answer1.lower() == "a" or answer1.lower() == "def":
    score += 1

answer2 = input("Q2: What data type is used to store True or False? \n(a) int\n(b) bool\n(c) str\nAnswer: ")
if answer2.lower() == "b" or answer2.lower() == "bool":
    score += 1

answer3 = input("Q3: What symbol is used for comments in Python? \n(a) //\n(b) <!-- -->\n(c) #\nAnswer: ")
if answer3.lower() == "c" or answer3.lower() == "#":
    score += 1

print(f"\nYour final score is {score}/3")

๐Ÿ” 3. Even or Odd Number Checker

A very basic utility to check if a number is even or odd.

✅ Sample Code:

# number_checker.py

number = int(input("Enter a number: "))

if number % 2 == 0:
    print("The number is EVEN.")
else:
    print("The number is ODD.")


๐Ÿ“š How to Use These Scripts (Script Mode Guide)

  1. create and SAVE the scripts the files.

  2. Open any file (e.g., calculator.py) in a text editor or Python IDE.

  3. Save it if you make changes.

  4. Run the script:

    • Using Terminal:

      python calculator.py
      
    • Using IDLE:
      F5 to run.


๐ŸŽ“ Final Tip for Students

These small Python projects help you:

  • Practice Script Mode usage

  • Understand input/output

  • Write if-else logic

  • Build confidence in Python basics

Once you're comfortable, try adding:

  • More math operations to the calculator

  • Timer or difficulty levels to the quiz

  • Prime number or palindrome checkers in the number tool

๐Ÿง  Click Next:  to explore the list of 100 python projects for beginners, intermediate and Expert level!


Python Iterators: Understanding Iterables and Iterators in Python

← Back to Home

๐Ÿ” Python Iterators (Made Simple) 

Iterators are a way to go through all the elements in a collection (like a list or tuple), one item at a time. Python has built-in support for iterators, making it easy to loop through data.

If you've ever used a for loop in Python, you've already worked with iterators—even if you didn’t realize it!


✅ What Is an Iterator?

An iterator is an object that can be looped through (iterated over). It must follow two main rules:

  1. It must have a method called __iter__() → returns the iterator object itself.

  2. It must have a method called __next__() → returns the next item from the sequence.


๐Ÿ“˜ Example 1: Using an Iterator

my_list = [1, 2, 3]

# Get an iterator
my_iter = iter(my_list)

print(next(my_iter))  # Output: 1
print(next(my_iter))  # Output: 2
print(next(my_iter))  # Output: 3

๐Ÿ” Output:

1
2
3

If you call next() again after the list is finished, it will raise a StopIteration error.


๐Ÿ›  Behind the Scenes of a For Loop

When we use a for loop like this:

for item in [1, 2, 3]:
    print(item)

Python automatically:

  • Calls iter() to get an iterator.

  • Calls next() repeatedly until StopIteration is raised.


๐Ÿงฑ Building a Custom Iterator

Let’s create our own iterator to return numbers from 1 to 5.

๐Ÿ“˜ Example 2: Custom Iterator

class MyNumbers:
    def __iter__(self):
        self.num = 1
        return self

    def __next__(self):
        if self.num <= 5:
            x = self.num
            self.num += 1
            return x
        else:
            raise StopIteration

# Create object
nums = MyNumbers()
my_iter = iter(nums)

for number in my_iter:
    print(number)

๐Ÿ” Output:

1
2
3
4
5

๐Ÿ’ก Important Notes

  • iter() creates an iterator from an iterable (like a list or string).

  • next() returns the next value.

  • When there are no more items, StopIteration is raised to end the loop.

  • You can create custom iterators by defining __iter__() and __next__().


๐Ÿ“˜ Example 3: Iterating Over a String

Strings are also iterable!

my_str = "Hi"
my_iter = iter(my_str)

print(next(my_iter))  # Output: H
print(next(my_iter))  # Output: i

๐Ÿ” Output:

H
i

๐ŸŽฏ Conclusion

Iterators are a powerful tool in Python that let you go through items one at a time. Whether you’re working with lists, strings, or building custom sequences, understanding iterators helps us write clean and efficient code.


Python File Handling

← Back to Home


๐Ÿ”น File Handling in Python – Beginner-Friendly 

In Python, file handling allows us to create, read, write, and delete files. This is useful when you want to store data permanently, such as saving user info, logs, reports, etc.


๐Ÿ”ธ Why is File Handling Important?

Without file handling, data disappears when the program ends. With files, we can store and retrieve data even after the program stops.


๐Ÿ”ธ Opening a File

Python uses the built-in open() function to open a file.

Syntax:

file = open("filename", "mode")

Mode Description
'r' Read (default)
'w' Write (creates new or overwrites file)
'a' Append (adds to end of file)
'x' Create (fails if file exists)
'b' Binary mode (e.g., 'rb', 'wb')

๐Ÿ”ธ Example 1: Writing to a File


file = open("example.txt", "w")  # Open in write mode
file.write("Hello, this is a test.\n")
file.write("Writing to a file in Python.\n")
file.close()  # Always close the file!

๐Ÿ“ This creates a file named example.txt and writes two lines to it.


๐Ÿ”ธ Example 2: Reading from a File

file = open("example.txt", "r")  # Open in read mode
content = file.read()
print(content)
file.close()

๐Ÿ“ This reads and prints the contents of example.txt.


๐Ÿ”ธ Example 3: Appending to a File

file = open("example.txt", "a")  # Open in append mode
file.write("Adding a new line.\n")
file.close()

๐Ÿ“ This adds a new line at the end of the file without deleting the old content.


๐Ÿ”ธ Reading Line by Line

file = open("example.txt", "r")
for line in file:
    print(line.strip())      # Here, strip() removes newline characters
file.close()

๐Ÿ”ธ Using with Statement (Recommended)

Python provides a cleaner way to handle files using the with statement. It automatically closes the file.

Example:

with open("example.txt", "r") as file:
    data = file.read()
    print(data)

Using this way, you don’t need to call file.close().


๐Ÿ”ธ Deleting a File

You can delete a file using the os module.

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
    print("File deleted.")
else:
    print("File does not exist.")

๐Ÿ”š Summary

  • Use open() to work with files.

  • Modes: 'r' (read), 'w' (write), 'a' (append), 'x' (create).

  • Always close the file after use (or use with).

  • Use the os module for file operations like deleting or checking existence.


✅ Quick Tip:

Use with open(...) as f: whenever possible—it’s safer and cleaner.

Python Exception Handling

← Back to Home

๐Ÿ›ก️ Exception Handling in Python: Advanced Guide for Beginners

In programming, exceptions are errors that happen when the program is running. Exceptions are runtime errors that disrupt normal flow. 

If we don’t handle these errors, our program might crash. Python gives us a way to catch and handle exceptions, which  helps catch these errors so the program can continue to run gracefully or show a friendly message to the user.


๐Ÿค” Why Use Exception Handling?

Consider a program that divides two user-input numbers. If a user inputs 0 as the divisor, a division by zero error (ZeroDivisionError) occurs. Without handling, your program crashes. With exception handling, you can:

  • Rescue the program from crashing

  • Display helpful error messages

  • Prevent invalid data from breaking your logic


๐Ÿงฉ Core Syntax

try:
    # code that may raise an exception
except SpecificError as e:
    # handle the error
else:
    # optional: runs when no exception was raised
finally:
    # optional: runs regardless, commonly used for clean-up


  • try: Wrap potentially risky operations

  • except: Catch and handle one or more specific exceptions

  • else: Execute only if no exceptions occur

  • finally: Always execute (e.g., closing files or releasing resources)


Let’s understand this with an example.

 

๐Ÿ”ธ Example 1: Division Program



๐Ÿ’ก Output Scenarios:

1.    Normal input:

                       


    2. Division by zero:

                



    3. Invalid Input:




๐Ÿงช Example: User Input & Division (Code block)

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
except ValueError:
    print("Error: Please enter a valid integer.")
else:
    print(f"Result: {result}")
finally:
    print("Operation complete.")

How this works:

  • ZeroDivisionError: Caught when divisor is zero

  • ValueError: Non-integer input

  • else: Displays result if no error

  • finally: Runs every time


๐Ÿ“š Common Built-in Exceptions

  • ZeroDivisionError – division by zero

  • ValueError – conversion errors

  • TypeError – unsupported operations

  • FileNotFoundError – file operations fail


๐Ÿง  Best Practices

  1. Catch only specific exceptions (e.g., ZeroDivisionError, not a general Exception)

  2. Avoid bare except:, which hides unexpected errors.

  3. Keep try blocks minimal – include only code that might fail

  4. Use finally for cleanup – close files or release resources.

  5. Log or print exception details using except Exception as e: for debugging purposes


๐Ÿ”ง Advanced Patterns: Raising and Chaining Exceptions

You can also raise custom exceptions or re-raise caught ones:

def divide(x, y):
    try:
        return x / y
    except ZeroDivisionError as e:
        raise ValueError("Invalid division") from e

This approach wraps an internal error in a clearer, higher-level exception—while preserving original context.


๐Ÿ“Œ Summary

  • Use try to wrap code that might cause an error.

  • Use Except to Handle specific exceptions to maintain clarity

  • Use else for code that runs only if there's no error and success paths.

  •  Use finally for code that should run no matter what (like essential cleanup).

  • Apply best practices to write robust, maintainable code.


Exception handling makes your program more reliable and user-friendly

Mastering exception handling transforms your scripts from fragile to resilient—making them suitable for real-world applications!


Creating a simple Function in python || python code for creating function

← Back to Home

๐Ÿ”น Functions in Python

A function is a block of code which only runs when it is called.

we can pass data, known as parameters, into a function.

A function can return data as a result.


# In Python a function is defined using the def keyword:

๐Ÿ”ธ Example : Creating a Function

def my_function():
  print("Hello function" )



๐Ÿ”ธ  Calling a Function

To call a function, we use the function name followed by parenthesis

 Example :


def my_function():
  print("Hello from function")

my_function()    # Here is Function call by its name


Python Functions Explained: A Beginner’s Guide with Code Examples

← Back to Home

๐Ÿ” Understanding Python Functions – A Beginner’s Guide

Functions are one of the most powerful and useful features in Python. They allow you to group code into reusable blocks, making your programs more organized, readable, and efficient.

Functions are the heart of clean, efficient Python programming. If you're a beginner, think of functions as named blocks of code that do something specific — like a recipe in a cookbook.


๐Ÿง  What is a Function?

A function is a reusable block of code that  that performs a specific task and runs only when called.  You define it once and call it whenever needed. 

You can pass data into it using parameters, and get a result back using the return keyword.

๐Ÿ“Œ Key Points:

  • A function is a block of code which only runs when it is called.
  • You can pass data, known as parameters, into a function.
  • A function can return data as a result.
  • In Python, a function is defined using the def keyword:

See example below:

def my_function():
  print("Hello from a function")

๐Ÿ”ง Basic Anatomy of a Function

def function_name(parameters):
    # code block
    return result

๐Ÿ‘️ Code Diagram

+---------------------------+
| def greet(name):         | <- Function Definition
|     print("Hello", name) | <- Function Body
+---------------------------+

        ⬇ Function Call

+--------------------+
| greet("Alice")     | <- Output: Hello Alice
+--------------------+

✅ Why Use Functions?

Functions help you:

๐Ÿงฉ Break complex tasks into manageable chunks
๐Ÿ” Reuse code instead of repeating
๐Ÿ“š Improve readability of your code
๐Ÿ› ️ Debug and maintain programs easily


✍️ Creating Your First Function

Let’s write a simple function:

def my_function():
    print("Hello from a function")

✍️ Defining and Calling a Function

Let’s write a above simple function again:

def my_function():
    print("Hello from a function!")

# Call the function
my_function()

๐Ÿ–ฅ️ Output:

Hello from a function!


๐Ÿงพ Function with Parameters

def greet(name):
    print(f"Hello, {name}!")
    
greet("Alice")

๐Ÿ–ฅ️ Output:

Hello, Alice!

๐Ÿ“Œ You can pass any data—strings, numbers, lists, etc.—as parameters.



๐Ÿ” Reusability at Work:

Want to greet different users? Use parameters.

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

๐Ÿ–จ️ Output:

Hello, Alice!
Hello, Bob!

๐Ÿ”„ Returning Values from Functions

Some functions return a result:

def add(a, b):
    return a + b

sum = add(4, 6)
print(sum)

๐Ÿ–จ️ Output:

10


๐Ÿ”„ Function with Conditional Logic

def is_even(num):
    if num % 2 == 0:
        return True
    else:
        return False

print(is_even(4))  # True
print(is_even(5))  # False

๐Ÿ“Œ You can use functions to implement logic and decision-making.


๐Ÿงญ Flowchart: How a Function Works

[Start]
   ↓
Define Function → [Call Function?] — No → [End]
                          ↓ Yes
                    Execute Code Block
                          ↓
                     Return (Optional)
                          ↓
                        [End]

See the flowchart in picture below:




๐ŸŽฅ Watch and Learn

Want to see it in action?
๐Ÿ‘‰ Check out the video below: “What is a Function in Python” – ideal for visual learners!



๐ŸŽฏ Final Tip

Functions help you write clean, modular, and testable code. The more you use them, the better your Python skills will become!


๐Ÿš€ Your Turn

Now that you know the basics of Python functions, try creating your own! Whether it’s a calculator or a greeting app, functions will help you build smarter and cleaner code.


Dictionaries in Python

← Back to Home

Python Dictionaries:



Dictionaries are python data structures which store the data in key-value pairs. These are like Maps in other similar programming languages.

Dictionaries are not ordered unlike strings, Lists and Tuples.

Keys uniquely define the items in a python dictionary. So duplicate keys are not allowed.

Keys are unique but values are not.

Keys must be of immutable types like strings, numbers and tuples.

Dictionary can contain any type of values.



Creating a Dictionary :

Each key is separated from its value by a colon(:)

The items are separated by commas

All the above paired items are enclosed in curly braces.


watch video below to demonstrate python dictionaries: 





Empty Dictionary:
       An empty dictionary without any item is created with just two curly braces.{}

Example:

              

Dictionary containing items: (create and display)




Accessing values from Dictionary:

Values can be accessed  using square brackets along with the key to obtain its value.

Example:



Both the print commands produces the corresponding values with keys "Name" and "Age".

If we attempt to access the data item which is not present in dictionary, we'll get error as





Updating Dictionary :

Dictionary can be updated by adding a new entry or a Key-Value pair, modifying an existing entry or deleting an existing entry :
Example:

In the above code the key 'Age' has the updated value from 25 to 16.
Also, there is a new entry where key is 'Department' with the value 'Finance'.(see Highlighted)


Deleting Dictionary Element

You can delete either an individual item or entire content of a dictionary.

Entire dictionary can also be deleted in a single operation.

Example 1:


If we now want to print the items, An exception is raised because after the command del dict, dictionary does not  exist.

Example 2:




 Properties of Dictionary Keys:

1. More than one entry per key is not allowed i.e duplicate keys are not allowed. When duplicate keys are assigned, only the last assigned (latest) key exists.

2. Keys must be immutable. i.e you can use strings, numbers and Tuples as dictionary keys . others are not allowed.



Built-in Dictionary functions:

1.  cmp : compares elements of both dict.

             cmp ( dict1 , dict2)

2.   len: Gives total length or the total number of elements in the dictionary.

             len(dict)

3.   str: produces a printable string representation of a dictionary.

            str(dict)

4.  type (variable) - returns the type of passed variable . If passed variable is dictionary, then it returns dictionary type.



Dictionary Methods:

Python uses following dictionary methods:

1.    dict.clear( )

2.    dict.copy( )

3.    dict.fromkeys( )

4.    dict.get(key, default = None)

5.    dict.has_key(key)

6.    dict.items( )

7.    dict.keys()

8.    dict.setdefault(key, default=None)

9.    dict.update(dict2)

10.  dict.values()


Featured Post

Solution MongoDB document Modelling Assignment

 Here's the complete solution to your MongoDB document modeling assignment, including: ✅ Sample documents for students and courses ...

Popular Posts