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

Data Visualization in Python: Create Stunning Charts with Matplotlib & Seaborn

← Back to Home

๐Ÿ“Š How to Visualize Data in Python Using Matplotlib and Seaborn


Introduction

In the world of data science, visualization is key. It helps turn raw data into meaningful insights that are easy to understand. Python offers several powerful libraries for data visualization, with Matplotlib and Seaborn being the most popular and beginner-friendly.

In this guide, you'll learn how to visualize data using both libraries. We'll cover line plots, bar charts, scatter plots, and heatmaps — all with simple, hands-on examples.


Prerequisites

Make sure you have Python installed. Then install the required libraries:

pip install matplotlib seaborn

You should also have pandas and numpy:

pip install pandas numpy

1. Importing the Libraries

Start by importing the necessary tools:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

2. Creating Sample Data

Let’s create a basic dataset for demonstration:

# Create a simple DataFrame
data = pd.DataFrame({
    'Year': [2020, 2021, 2022, 2023],
    'Sales': [250, 400, 550, 700]
})

3. Line Plot with Matplotlib

plt.plot(data['Year'], data['Sales'], marker='o')
plt.title('Yearly Sales')
plt.xlabel('Year')
plt.ylabel('Sales')
plt.grid(True)
plt.show()

Why it’s useful: Line plots are great for showing trends over time.


4. Bar Plot with Seaborn

sns.barplot(x='Year', y='Sales', data=data)
plt.title('Sales by Year')
plt.show()

Why Seaborn? Seaborn integrates tightly with Pandas and makes beautiful visualizations with less code.


5. Scatter Plot (Comparison)

Let’s create a more detailed dataset:

np.random.seed(0)
df = pd.DataFrame({
    'Hours_Studied': np.random.randint(1, 10, 50),
    'Score': np.random.randint(40, 100, 50)
})

sns.scatterplot(x='Hours_Studied', y='Score', data=df)
plt.title('Study Time vs Exam Score')
plt.show()

Use case: Scatter plots show correlation between two numeric variables.


6. Histogram with Seaborn

sns.histplot(df['Score'], bins=10, kde=True)
plt.title('Distribution of Scores')
plt.show()

Histograms help understand the frequency distribution of values.


7. Heatmap with Correlation

corr = df.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title('Correlation Heatmap')
plt.show()

Tip: Use heatmaps to visualize correlation between features in a dataset.


8. Styling and Themes

Seaborn offers built-in themes:

sns.set_style('darkgrid')

You can choose from 'white', 'dark', 'whitegrid', 'darkgrid', and 'ticks'.


Conclusion

Matplotlib and Seaborn are must-have tools in any Python programmer's toolkit. With just a few lines of code, you can create insightful, professional-looking visualizations that bring your data to life.

Start with simple plots and explore more advanced options as you grow. For best practice, always label your axes, add titles, and make plots readable.

            Note: Try changing data or adding your own visualizations.

Check out our other Python guides to continue learning:


Python List Comprehensions: Complete Guide with Syntax & Examples

← Back to Home

 

Python List Comprehensions Explained: The Ultimate Guide with Examples


Introduction

Python is loved for its clean and concise syntax—and list comprehensions are one of its most powerful features. They allow you to create new lists by transforming or filtering existing iterables with a single line of code.

This guide will walk you through what list comprehensions are, why they’re useful, and how to use them with real-world examples.


What Is a List Comprehension?

A list comprehension is a compact way to generate lists in Python.

Instead of using a loop like this:

squares = []
for x in range(10):
    squares.append(x**2)

You can write:

squares = [x**2 for x in range(10)]

It's shorter, easier to read, and often more efficient.


Basic Syntax

[expression for item in iterable]
  • expression – the value to include in the new list

  • item – the current element in the iteration

  • iterable – the collection you loop over

Example:

evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # Output: [0, 2, 4, 6, 8]

Using Conditions (if)

You can filter items using an if condition:

names = ["John", "Sara", "Paul", "Anna"]
short_names = [name for name in names if len(name) <= 4]

Nested List Comprehensions

You can nest comprehensions to handle nested data, like a 2D matrix:

matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened)  # Output: [1, 2, 3, 4, 5, 6]

With Functions

You can call functions inside list comprehensions:

def square(x):
    return x * x

results = [square(x) for x in range(5)]

Dictionary and Set Comprehensions (Bonus)

List comprehensions have siblings!

Dictionary Comprehension:

squares = {x: x*x for x in range(5)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Set Comprehension:

unique_lengths = {len(word) for word in ["apple", "banana", "cherry"]}
# Output: {5, 6}

Common Use Cases

  • Filtering even/odd numbers

  • Removing duplicates from a list

  • Flattening nested lists

  • Mapping transformations (e.g. converting strings to lowercase)

  • Reading and processing file lines


List Comprehensions vs Loops

Feature For Loop List Comprehension
Verbosity             More lines of code         One-liner
Readability             Clearer for complex logic         Clearer for simple operations
Performance             Slightly slower in some cases         Often faster

Rule of thumb:
Use comprehensions when the logic is simple and readable. For complex logic or side-effects (like print/log), stick with loops.


Common Mistakes to Avoid

  • Trying to do too much in one line → hurts readability

  • Forgetting to include if condition at the right place

  • Using nested comprehensions without understanding them


Practice Problems

Try writing list comprehensions for the following:

  1. Get all numbers divisible by 3 from 0 to 50

  2. Convert all strings in a list to uppercase

  3. Extract first letters of each word in a sentence


Conclusion

List comprehensions are an elegant and Pythonic way to write clean, concise code. Once you get used to them, you’ll find they make many common tasks simpler and more readable.

Explore them in your projects, and when in doubt—test both list comprehension and the regular loop to see what’s clearer.

For more Python tutorials, check out our posts on:


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 Libraries You Must Know in 2025 — Complete Guide for Beginners & Experts

← Back to Home

Top 10 Python Libraries You Must Know in 2025 (With Use Cases)


Introduction

Python’s rich ecosystem of libraries is one reason why it’s loved by developers worldwide. Whether you’re a beginner eager to learn or an expert looking to stay updated, knowing the right libraries can boost your productivity and open doors to new possibilities.

In this post, I’ll introduce you to the top 10 Python libraries you must know in 2025, along with their core use cases, installation tips, and mini code examples to get you started quickly.


1. NumPy

Use case: Numerical computing and powerful array operations.
NumPy is the foundation for scientific computing in Python. It allows fast operations on large multi-dimensional arrays and matrices.

Mini Example:

import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)  # Output: [2 4 6]

Install:

pip install numpy

2. Pandas

Use case: Data manipulation and analysis.
Pandas offers data structures like DataFrames that simplify working with structured data, making data cleaning and analysis intuitive.

Mini Example:

import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)

Install:

pip install pandas

3. Requests

Use case: HTTP requests made simple.
Requests makes it easy to send HTTP/1.1 requests without the hassle of manual connection handling, perfect for web scraping or API consumption.

Mini Example:

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

Install:

pip install requests

4. Matplotlib

Use case: Data visualization.
Create static, animated, and interactive plots in Python. Matplotlib is versatile and widely used for plotting graphs.

Mini Example:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

Install:

pip install matplotlib

5. FastAPI

Use case: Modern, fast web APIs.
FastAPI is a high-performance framework for building APIs quickly with Python 3.7+ based on standard Python type hints.

Mini Example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

Install:

pip install fastapi uvicorn

6. Pydantic

Use case: Data validation and settings management.
Pydantic uses Python type annotations to validate data, ideal for ensuring your APIs or configs are robust and error-free.

Mini Example:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str

user = User(id=1, name="Alice")
print(user)

Install:

pip install pydantic

7. Selenium

Use case: Browser automation and testing.
Automate browsers for testing web applications or scraping dynamic web pages.

Mini Example:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.python.org')
print(driver.title)
driver.quit()

Install:

pip install selenium

8. BeautifulSoup

Use case: Web scraping.
Parse HTML and XML documents to extract data easily.

Mini Example:

from bs4 import BeautifulSoup

html = "<html><head><title>Test</title></head><body><p>Hello</p></body></html>"
soup = BeautifulSoup(html, 'html.parser')
print(soup.title.string)

Install:

pip install beautifulsoup4

9. TensorFlow

Use case: Machine learning and deep learning.
TensorFlow is a powerful library for building and training ML models, widely used in AI applications.

Mini Example:

import tensorflow as tf

hello = tf.constant('Hello, TensorFlow!')
tf.print(hello)

Install:

pip install tensorflow

10. Plotly

Use case: Interactive data visualization.
Plotly helps you create beautiful interactive charts and dashboards for data analysis.

Mini Example:

import plotly.express as px

fig = px.bar(x=["a", "b", "c"], y=[1, 3, 2])
fig.show()

Install:

pip install plotly

Why Learn These Libraries?

  • Beginners: They provide a strong foundation in Python’s most practical applications — data science, web development, automation, and AI. Learning these tools opens doors to exciting projects and job opportunities.

  • Experts: Staying current with the latest tools and frameworks helps maintain efficiency, write cleaner code, and leverage improvements in performance and usability.


Conclusion

Mastering these libraries will supercharge your Python journey in 2025, whether you’re just starting out or refining advanced skills. Don’t just read about them — try building small projects or scripts using these libraries to gain hands-on experience. The Python ecosystem is vast and powerful, and these libraries are your gateway to making the most of it.


← 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!


Python Lists Explained with Examples – A Beginner to Pro Guide

← Back to Home

๐Ÿ Python Lists Made Easy: A Beginner to Pro Guide

Python is known for its simplicity and powerful built-in data structures. One of the most important and widely used structures in Python is the list.

Whether you're a student just starting out or a professional working on a project, understanding Python lists can help you write cleaner, faster, and more efficient code.


✅ What is a List in Python?

A list in Python is a collection of items that are ordered, changeable (mutable), and allow duplicate values.

You can store:

  • Numbers

  • Strings

  • Other lists

  • Even a mix of different data types!


๐Ÿ“ฆ Creating a List

# Creating different types of lists
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [10, "hello", 3.14, True]

๐Ÿ“Œ Basic List Operations

1. Accessing Items

Lists use indexing starting from 0.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # Output: apple
print(fruits[-1])  # Output: cherry (last item)

2. Changing Items

fruits[1] = "blueberry"
print(fruits)  # ['apple', 'blueberry', 'cherry']

3. Adding Items

fruits.append("orange")         # Add at end
fruits.insert(1, "mango")       # Add at specific position

4. Removing Items

fruits.remove("apple")          # Remove by value
fruits.pop()                    # Remove last item
del fruits[0]                   # Remove by index

5. List Length

print(len(fruits))  # Number of items

๐Ÿ”„ Looping Through a List

for fruit in fruits:
    print(fruit)

๐Ÿงช Useful List Methods

Method Description
append() Adds an item to the end
insert() Inserts item at a specific index
remove() Removes the first occurrence
pop() Removes item at index or last
sort() Sorts the list (in place)
reverse() Reverses the order of items
clear() Removes all items
index() Returns index of first occurrence
count() Counts number of occurrences

Example:

scores = [45, 87, 45, 92, 60]
print(scores.count(45))    # Output: 2
print(scores.index(92))    # Output: 3

๐Ÿง  Advanced List Tricks (Useful for Professionals)

1. List Comprehension

A concise way to create lists.

squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

2. Slicing

Extract parts of a list.

nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])    # [1, 2, 3]
print(nums[:3])     # [0, 1, 2]
print(nums[-2:])    # [4, 5]

3. Nested Lists

Lists inside lists (like a matrix).

matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
]
print(matrix[1][1])  # Output: 4

๐ŸŽฏ When to Use Lists?

  • Storing ordered data like names, numbers, tasks

  • Looping through a group of values

  • Performing bulk operations (filter, sort, etc.)

  • Building custom data structures like stacks/queues


๐Ÿ“ Quick Summary

  • Lists are ordered, mutable collections.

  • You can add, remove, change, or access items easily.

  • Great for storing groups of related data.

  • Widely used in Python for data manipulation, web development, automation, and more.


๐Ÿ’ก Practice Challenge

Try this:

# Create a list of 5 favorite movies
# Print only the 2nd and 4th movie from the list

movies = ["The Matrix", "Interstellar", "Inception", "The Dark Knight", "Tenet"]
print(movies[1])
print(movies[3])

๐ŸŽ“ Conclusion

Python lists are a core part of the language that you'll use in almost every project. They're simple enough for beginners and powerful enough for professionals.

Whether you're building a to-do app or crunching big data, knowing how to use lists efficiently is a skill every Python developer needs.




This above video describes python lists in a very easy and smooth manner for the viewers who want to learn it .Watch it with examples and hands on exercises.
Learn the concept of lists in python and get answers of the following questions:

What is a python list ?
How to create lists in python?
Populating list with items.
How to access items from a list in python?
Slicing in python.
Concatenation of two lists in python.


Featured Post

Extra Challenge: Using References Between Documents

  ๐ŸŽฏ ๐Ÿ’ก Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mode...

Popular Posts