Om Pandey
Python Programming

Python 0 to Hero

Master Python programming from absolute scratch. A complete guide covering everything from basics to advanced concepts with hands-on examples.

Beginner Friendly Hands-on Examples Learn by Doing
📚

What You'll Learn

Hello, World!

Variables and Types

Lists

Basic Operators

String Formatting

String Operations

Conditions

Loops

Functions

Dictionaries

Input and Output

Printing on Screen

1

Introduction to Python

Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum in 1991, Python has become one of the most popular languages in the world for web development, data science, AI, automation, and more!

💡 Why Python?

Python's simple syntax makes it perfect for beginners, yet powerful enough for experts. It's used by Google, Netflix, Instagram, and NASA!

2

Learn the Basics

Hello, World!

Every programming journey starts with "Hello, World!" - Let's print our first message!

hello.py
# Your first Python program!
print("Hello, World!")

# Print multiple lines
print("Welcome to Python!")
print("Let's start coding! 🚀")
Output
Hello, World! Welcome to Python! Let's start coding! 🚀

Variables and Types

Variables store data. Python automatically detects the type - no need to declare it!

variables.py
# String - text data
name = "Om Pandey"

# Integer - whole numbers
age = 21

# Float - decimal numbers
height = 5.9

# Boolean - True or False
is_developer = True

# Check types
print(type(name))      # <class 'str'>
print(type(age))       # <class 'int'>
print(type(height))    # <class 'float'>
print(type(is_developer)) # <class 'bool'>

# Print variables
print(f"Hi, I'm {name} and I'm {age} years old!")
Output
<class 'str'> <class 'int'> <class 'float'> <class 'bool'> Hi, I'm Om Pandey and I'm 21 years old!

Lists

Lists store multiple items in a single variable. They are ordered, changeable, and allow duplicates.

lists.py
# Creating a list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]

# Access items (index starts at 0)
print(fruits[0])      # apple
print(fruits[-1])     # cherry (last item)

# Add items
fruits.append("orange")
print(fruits)         # ['apple', 'banana', 'cherry', 'orange']

# Remove items
fruits.remove("banana")
print(fruits)         # ['apple', 'cherry', 'orange']

# List length
print(len(fruits))    # 3

# List slicing
print(numbers[1:4])   # [2, 3, 4]

Basic Operators

Python supports arithmetic, comparison, and logical operators for calculations and comparisons.

operators.py
# Arithmetic Operators
a = 10
b = 3

print(a + b)   # Addition: 13
print(a - b)   # Subtraction: 7
print(a * b)   # Multiplication: 30
print(a / b)   # Division: 3.333...
print(a // b)  # Floor Division: 3
print(a % b)   # Modulus: 1
print(a ** b)  # Exponent: 1000

# Comparison Operators
print(a > b)   # True
print(a == b)  # False
print(a != b)  # True

# Logical Operators
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

String Formatting

Format strings to include variables and expressions dynamically.

string_format.py
name = "Om"
age = 21

# f-strings (Recommended - Python 3.6+)
print(f"Hello, my name is {name} and I'm {age}")

# .format() method
print("Hello, my name is {} and I'm {}".format(name, age))

# % operator (old style)
print("Hello, my name is %s and I'm %d" % (name, age))

# Format numbers
price = 49.99
print(f"Price: ${price:.2f}")  # Price: $49.99

# Padding
print(f"{name:>10}")  # Right align, pad to 10
print(f"{name:<10}")  # Left align, pad to 10

Basic String Operations

Strings have many built-in methods for manipulation.

strings.py
text = "Hello, Python World!"

# Length
print(len(text))         # 20

# Case conversion
print(text.upper())       # HELLO, PYTHON WORLD!
print(text.lower())       # hello, python world!
print(text.title())       # Hello, Python World!

# Find and replace
print(text.find("Python"))     # 7 (index)
print(text.replace("World", "Universe"))

# Split and join
words = text.split(" ")
print(words)              # ['Hello,', 'Python', 'World!']
print("-".join(words))    # Hello,-Python-World!

# Strip whitespace
messy = "  hello  "
print(messy.strip())      # "hello"

# Check content
print(text.startswith("Hello"))  # True
print("Python" in text)         # True

Conditions

Control the flow of your program with if, elif, and else statements.

conditions.py
age = 18

# Simple if-else
if age >= 18:
    print("You are an adult!")
else:
    print("You are a minor!")

# Multiple conditions with elif
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Your grade: {grade}")

# Ternary operator (one-liner)
status = "adult" if age >= 18 else "minor"
print(status)

Loops

Loops let you repeat code. Python has for loops and while loops.

loops.py
# For loop with range
for i in range(5):
    print(f"Count: {i}")

# For loop with list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I love {fruit}!")

# While loop
count = 0
while count < 3:
    print(f"Count is {count}")
    count += 1

# Break and Continue
for i in range(10):
    if i == 3:
        continue  # Skip 3
    if i == 7:
        break     # Stop at 7
    print(i)

# List comprehension
squares = [x**2 for x in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

Functions

Functions are reusable blocks of code that perform specific tasks.

functions.py
# Basic function
def greet():
    print("Hello, World!")

greet()  # Call the function

# Function with parameters
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Om")

# Function with return value
def add(a, b):
    return a + b

result = add(5, 3)
print(f"Sum: {result}")  # Sum: 8

# Default parameters
def power(base, exp=2):
    return base ** exp

print(power(3))      # 9 (3^2)
print(power(3, 3))   # 27 (3^3)

# Lambda functions (one-liners)
square = lambda x: x ** 2
print(square(5))  # 25
3

Dictionaries

Dictionaries store data in key-value pairs. They are unordered, changeable, and don't allow duplicate keys.

dictionaries.py
# Creating a dictionary
person = {
    "name": "Om Pandey",
    "age": 21,
    "city": "Kathmandu",
    "is_developer": True
}

# Access values
print(person["name"])      # Om Pandey
print(person.get("age"))   # 21

# Add or update
person["email"] = "[email protected]"
person["age"] = 22

# Remove items
del person["city"]

# Loop through dictionary
for key, value in person.items():
    print(f"{key}: {value}")

# Dictionary methods
print(person.keys())    # All keys
print(person.values())  # All values
print(len(person))       # Number of items
4

Input and Output

Interact with users by getting input and displaying output.

input_output.py
# Getting user input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Input is always a string - convert for numbers
age = int(input("Enter your age: "))
print(f"Next year you'll be {age + 1}")

# Multiple outputs
print("Hello", "World", sep="-")  # Hello-World
print("Line 1", end=" | ")
print("Line 2")  # Line 1 | Line 2

# File I/O
# Writing to file
with open("test.txt", "w") as file:
    file.write("Hello, File!")

# Reading from file
with open("test.txt", "r") as file:
    content = file.read()
    print(content)
5

Printing on Screen

Master different ways to display output beautifully.

printing.py
# Basic print
print("Hello, World!")

# Print with variables
name = "Om"
print("Name:", name)

# Formatted output
score = 95.5678
print(f"Score: {score:.2f}")  # Score: 95.57

# Table-like output
print(f"{'Name':<15}{'Age':>5}")
print(f"{'Om Pandey':<15}{21:>5}")
print(f"{'John Doe':<15}{25:>5}")

# Special characters
print("Line 1\nLine 2")       # New line
print("Col1\tCol2\tCol3")     # Tab
print("He said \"Hello!\"")   # Escape quotes

# Colorful output (using ANSI codes)
print("\033[92m✓ Success!\033[0m")   # Green
print("\033[91m✗ Error!\033[0m")     # Red
print("\033[93m⚠ Warning!\033[0m")   # Yellow

# ASCII Art Fun!
print("""
   🐍 PYTHON 🐍
 ╔═══════════╗
 ║  Hello!   ║
 ╚═══════════╝
""")
Output
Name Age Om Pandey 21 John Doe 25 🐍 PYTHON 🐍 ╔═══════════╗ ║ Hello! ║ ╚═══════════╝

🎉 Congratulations!

You've learned the Python basics! Ready to build real projects with frameworks?

Continue with Framework