Showing posts with label Beginner Python Projects. Show all posts
Showing posts with label Beginner Python Projects. 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.


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


How to Create Your First Python Package and Publish on PyPI: A Complete Beginner’s Guide

← Back to Home

 

How to Create Your First Python Package and Publish on PyPI (Expanded Guide)


Introduction

Publishing your own Python package can be a rewarding experience. It lets you share your code with the global community, showcase your skills, and even simplify your own projects by reusing code easily. In this guide, I’ll take you through the full process—from creating your package structure to uploading it on PyPI—with practical tips and common pitfalls to avoid.


What Is a Python Package and Why Publish One?

A Python package is a collection of modules organized in directories that allow others to reuse your code by simply installing it via pip. Publishing on PyPI (Python Package Index) is like putting your package in the official Python library store, making it easy for anyone to find and install it.

Why publish?

  • Share useful tools with the world

  • Build your portfolio and credibility

  • Encourage collaboration and contributions

  • Manage your own code efficiently across projects


Step 1: Set Up Your Package Structure

Organize your files clearly. Here’s a recommended folder structure:

my_package/
├── my_package/
│   └── __init__.py
├── tests/
│   └── test_basic.py
├── setup.py
├── README.md
└── LICENSE

What these files do:

  • my_package/ — This is where your package code lives.

  • __init__.py — This file can be empty or include package initialization code.

  • tests/ — Always good to include some tests to ensure your package works.

  • setup.py — Contains metadata and instructions for packaging.

  • README.md — Explains what your package does.

  • LICENSE — Open-source licenses define how others can use your code (MIT, Apache, etc.).

Tip: Adding tests makes your package more professional and reliable.


Step 2: Write Your Package Code

Create a simple function to start. For example, in my_package/__init__.py:

def greet(name):
    """Return a friendly greeting."""
    return f"Hello, {name}! Welcome to my package."

Tip: Write clear docstrings and comments to help users understand your code.


Step 3: Prepare setup.py for Packaging

This script tells Python how to build and install your package.

Example:

from setuptools import setup, find_packages

setup(
    name='my_package',  # Choose a unique package name on PyPI
    version='0.1.0',
    author='Your Name',
    author_email='your.email@example.com',
    description='A simple greeting package',
    long_description=open('README.md').read(),
    long_description_content_type='text/markdown',
    url='https://github.com/yourusername/my_package',
    packages=find_packages(),
    classifiers=[
        'Programming Language :: Python :: 3',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
    ],
    python_requires='>=3.6',
)

Pro tip: Use find_packages() to automatically discover subpackages.


Step 4: Write a Helpful README.md

Your README is often the first thing users see.

Include:

  • What your package does

  • Installation instructions

  • Basic usage examples

  • Links to documentation or source code

Here’s a mini template you can adapt:

# my_package

A simple Python package that greets users.

## Installation

```bash
pip install my_package

Usage

from my_package import greet

print(greet("Alice"))

---

## Step 5: Choose a License

Open source licenses tell users what they can do with your code. Popular licenses include:

- **MIT License:** Very permissive, allows almost anything.
- **Apache 2.0:** Includes patent protections.
- **GPL:** Requires derivatives to be open source too.

Choose a license and add a `LICENSE` file in your project.

---

## Step 6: Build Your Package

Before publishing, install the latest build tools:

```bash
pip install --upgrade setuptools wheel

Then run:

python setup.py sdist bdist_wheel

This creates .tar.gz and .whl files in the dist/ folder.


Step 7: Test Locally (Optional but Recommended)

Install your package locally to test before uploading:

pip install dist/my_package-0.1.0-py3-none-any.whl

Then run:

from my_package import greet
print(greet("Test User"))

Step 8: Upload Your Package to PyPI

Install Twine:

pip install --upgrade twine

Create an account on PyPI if you haven’t already.

Upload your package:

twine upload dist/*

Enter your credentials when prompted.


Step 9: Celebrate and Share!

Your package is now live! You can install it via:

pip install my_package

Share your package on social media, forums, or developer communities to get feedback and contributions.


Common Pitfalls to Avoid

  • Package name conflicts: Check PyPI to ensure your package name is unique.

  • Forgetting __init__.py: Without this file, Python won't recognize your folder as a package.

  • Ignoring dependencies: List dependencies in setup.py if your package requires other packages.

  • Skipping tests: Always test your package thoroughly before publishing.



Conclusion

Publishing your first Python package might feel complex at first, but with this guide, you’re well-equipped to share your work with the Python community. Keep refining your package, writing tests, and engaging with users to make it even better!


← Back to Home

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!


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!


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