Python Basics - Complete Guide
Comprehensive guide to Python fundamentals including variables, data types, operators, control statements, functions, collections, OOP, exception handling, decorators, and real-world examples with diagrams and best practices.
Python Basics - Complete Guide
Python is one of the most popular and versatile programming languages, known for its simplicity and readability. Created by Guido van Rossum in 1991, Python has become the go-to language for beginners and experts alike.
Why Python?
- Easy to Learn: Simple, readable syntax
- Versatile: Web, data science, AI, automation
- Productive: Write less code, do more
- Large Ecosystem: 300,000+ packages on PyPI
- Strong Community: Extensive documentation and support
- Cross-Platform: Runs on Windows, Mac, Linux
Popular Use Cases
✓ Web Development (Django, Flask, FastAPI)
✓ Data Science & Analytics (Pandas, NumPy)
✓ Machine Learning & AI (TensorFlow, PyTorch)
✓ Automation & Scripting
✓ Cloud Engineering (AWS, Azure, GCP)
✓ DevOps & Infrastructure
✓ Scientific Computing
✓ Game Development
Python vs Other Languages
┌──────────────┬─────────┬─────────┬─────────┐
│ Feature │ Python │ Java │ Go │
├──────────────┼─────────┼─────────┼─────────┤
│ Typing │ Dynamic │ Static │ Static │
│ Syntax │ Simple │ Verbose │ Simple │
│ Speed │ Slow │ Fast │ Fastest │
│ Learning │ Easy │ Medium │ Easy │
│ Use Case │ General │ Enterprise│Backend│
└──────────────┴─────────┴─────────┴─────────┘
Hello World
print("Hello, World!")
Run:
python hello.py
# or
python3 hello.py
Output:
Hello, World!
Interactive Mode:
python
>>> print("Hello, World!")
Hello, World!
>>> exit()
Variables and Data Types
Variable Declaration
Python is dynamically typed - no need to declare types.
# Variables
name = "Venu"
age = 30
salary = 150000.50
is_active = True
# Multiple assignment
x, y, z = 10, 20, 30
# Same value to multiple variables
a = b = c = 100
# Type checking
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(salary)) # <class 'float'>
Basic Data Types
# Integer
age = 30
count = -5
# Float
price = 99.99
temperature = -10.5
# String
name = "Venu"
message = 'Hello World'
multiline = """This is
a multiline
string"""
# Boolean
is_active = True
is_admin = False
# None (null)
result = None
Type Conversion
# String to int
age = int("30")
# Int to string
age_str = str(30)
# String to float
price = float("99.99")
# Int to float
value = float(10)
# Bool to int
num = int(True) # 1
num = int(False) # 0
Operators
Arithmetic Operators
a = 10
b = 3
print(a + b) # 13 - Addition
print(a - b) # 7 - Subtraction
print(a * b) # 30 - Multiplication
print(a / b) # 3.333... - Division
print(a // b) # 3 - Floor division
print(a % b) # 1 - Modulus
print(a ** b) # 1000 - Exponentiation
# Augmented assignment
x = 10
x += 5 # x = x + 5
x -= 3 # x = x - 3
x *= 2 # x = x * 2
x /= 4 # x = x / 4
Comparison Operators
a = 10
b = 20
print(a == b) # False - Equal
print(a != b) # True - Not equal
print(a < b) # True - Less than
print(a > b) # False - Greater than
print(a <= b) # True - Less than or equal
print(a >= b) # False - Greater than or equal
Logical Operators
x = True
y = False
print(x and y) # False - AND
print(x or y) # True - OR
print(not x) # False - NOT
# Short-circuit evaluation
result = (5 > 3) and (10 < 20) # True
Identity and Membership Operators
# Identity operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is c) # True
print(a is b) # False (different objects)
print(a == b) # True (same values)
# Membership operators
nums = [1, 2, 3, 4, 5]
print(3 in nums) # True
print(10 not in nums) # True
Strings
String Operations
# Creation
name = "Venu"
message = 'Hello World'
# Concatenation
full_name = "Venu" + " " + "Gopal"
# Repetition
stars = "*" * 10 # "**********"
# Indexing
first_char = name[0] # "V"
last_char = name[-1] # "u"
# Slicing
text = "Hello World"
print(text[0:5]) # "Hello"
print(text[6:]) # "World"
print(text[:5]) # "Hello"
print(text[::2]) # "HloWrd" (every 2nd char)
print(text[::-1]) # "dlroW olleH" (reverse)
# Length
length = len(name) # 4
String Methods
text = "Hello World"
# Case conversion
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
print(text.capitalize()) # "Hello world"
print(text.title()) # "Hello World"
# Search and replace
print(text.find("World")) # 6
print(text.replace("World", "Python")) # "Hello Python"
print(text.count("l")) # 3
# Split and join
words = text.split() # ["Hello", "World"]
joined = "-".join(words) # "Hello-World"
# Strip whitespace
text = " Hello "
print(text.strip()) # "Hello"
print(text.lstrip()) # "Hello "
print(text.rstrip()) # " Hello"
# Check methods
print("hello".isalpha()) # True
print("123".isdigit()) # True
print("hello123".isalnum()) # True
print("Hello".startswith("H")) # True
print("World".endswith("d")) # True
String Formatting
name = "Venu"
age = 30
# f-strings (Python 3.6+) - Recommended
message = f"My name is {name} and I'm {age} years old"
# format() method
message = "My name is {} and I'm {} years old".format(name, age)
message = "My name is {0} and I'm {1} years old".format(name, age)
message = "My name is {n} and I'm {a} years old".format(n=name, a=age)
# % formatting (old style)
message = "My name is %s and I'm %d years old" % (name, age)
# Expressions in f-strings
print(f"Next year I'll be {age + 1}")
print(f"Uppercase name: {name.upper()}")
Control Statements
If-Elif-Else
age = 20
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
elif age < 65:
print("Adult")
else:
print("Senior")
# Ternary operator
status = "Adult" if age >= 18 else "Minor"
# Multiple conditions
score = 85
if score >= 90 and score <= 100:
print("A grade")
# Truthy and Falsy values
# Falsy: False, None, 0, "", [], {}, ()
# Truthy: Everything else
if []: # Empty list is falsy
print("This won't print")
if [1, 2, 3]: # Non-empty list is truthy
print("This will print")
Loops
For Loop
# Range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Range with start and end
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# Range with step
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Iterate over list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Enumerate (index and value)
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Iterate over string
for char in "Python":
print(char)
# Break and continue
for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i)
# Else clause (executes if loop completes normally)
for i in range(5):
print(i)
else:
print("Loop completed")
While Loop
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# While with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
print(f"You entered: {user_input}")
# While with else
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop completed")
Collections
Lists (Mutable, Ordered)
# Creation
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# Access
print(fruits[0]) # "apple"
print(fruits[-1]) # "cherry" (last item)
# Slicing
print(fruits[0:2]) # ["apple", "banana"]
# Modify
fruits[1] = "blueberry"
# Add elements
fruits.append("date") # Add to end
fruits.insert(1, "avocado") # Insert at index
fruits.extend(["elderberry", "fig"]) # Add multiple
# Remove elements
fruits.remove("apple") # Remove by value
popped = fruits.pop() # Remove and return last
popped = fruits.pop(0) # Remove and return at index
del fruits[0] # Delete by index
fruits.clear() # Remove all
# List operations
numbers = [3, 1, 4, 1, 5, 9, 2]
print(len(numbers)) # 7
print(max(numbers)) # 9
print(min(numbers)) # 1
print(sum(numbers)) # 25
print(numbers.count(1)) # 2
print(numbers.index(4)) # 2
# Sorting
numbers.sort() # Sort in place
numbers.sort(reverse=True) # Sort descending
sorted_nums = sorted(numbers) # Return new sorted list
# Reverse
numbers.reverse() # Reverse in place
reversed_nums = list(reversed(numbers)) # Return new reversed list
# Copy
copy1 = numbers.copy()
copy2 = numbers[:]
copy3 = list(numbers)
List Comprehension
# Basic list comprehension
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# With if-else
numbers = [x if x % 2 == 0 else -x for x in range(10)]
# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# Flatten nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for sublist in nested for item in sublist]
# [1, 2, 3, 4, 5, 6]
Tuples (Immutable, Ordered)
# Creation
point = (10, 20)
person = ("Venu", 30, "Engineer")
single = (42,) # Note the comma
# Access
print(point[0]) # 10
# Unpacking
x, y = point
name, age, job = person
# Tuple methods
numbers = (1, 2, 3, 2, 4, 2)
print(numbers.count(2)) # 3
print(numbers.index(3)) # 2
# Immutable
# point[0] = 15 # TypeError!
# Use cases: Return multiple values, dictionary keys
def get_coordinates():
return (10, 20)
x, y = get_coordinates()
Sets (Mutable, Unordered, Unique)
# Creation
numbers = {1, 2, 3, 4, 5}
fruits = set(["apple", "banana", "cherry"])
# Add and remove
numbers.add(6)
numbers.remove(3) # Raises error if not found
numbers.discard(10) # No error if not found
popped = numbers.pop() # Remove and return arbitrary element
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
print(a ^ b) # Symmetric difference: {1, 2, 5, 6}
# Set methods
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.issubset(b))
print(a.issuperset(b))
# Remove duplicates from list
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers)) # [1, 2, 3, 4]
Dictionaries (Mutable, Key-Value Pairs)
# Creation
person = {
"name": "Venu",
"age": 30,
"city": "Texas"
}
# Access
print(person["name"]) # "Venu"
print(person.get("age")) # 30
print(person.get("email", "N/A")) # "N/A" (default)
# Add/Update
person["email"] = "[email protected]"
person.update({"phone": "123-456-7890", "age": 31})
# Remove
del person["city"]
email = person.pop("email")
person.clear() # Remove all
# Dictionary methods
person = {"name": "Venu", "age": 30, "city": "Texas"}
print(person.keys()) # dict_keys(['name', 'age', 'city'])
print(person.values()) # dict_values(['Venu', 30, 'Texas'])
print(person.items()) # dict_items([('name', 'Venu'), ...])
# Iterate
for key in person:
print(key, person[key])
for key, value in person.items():
print(f"{key}: {value}")
# Dictionary comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Nested dictionaries
users = {
"user1": {"name": "Venu", "age": 30},
"user2": {"name": "John", "age": 25}
}
Functions
Basic Functions
# Simple function
def greet():
print("Hello!")
# Function with parameters
def greet_person(name):
print(f"Hello, {name}!")
# Function with return value
def add(a, b):
return a + b
# Multiple return values
def get_user():
return "Venu", 30, "Engineer"
name, age, job = get_user()
# Default parameters
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # "Hello, Guest!"
greet("Venu") # "Hello, Venu!"
# Keyword arguments
def create_user(name, age, city):
print(f"{name}, {age}, {city}")
create_user(name="Venu", city="Texas", age=30)
# *args (variable positional arguments)
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4, 5)) # 15
# **kwargs (variable keyword arguments)
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Venu", age=30, city="Texas")
Lambda Functions
# Anonymous functions
add = lambda x, y: x + y
print(add(5, 3)) # 8
# With map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]
# With filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]
# With sorted
users = [("Venu", 30), ("John", 25), ("Alice", 35)]
sorted_users = sorted(users, key=lambda x: x[1])
# [('John', 25), ('Venu', 30), ('Alice', 35)]
Decorators
# Simple decorator
def uppercase_decorator(func):
def wrapper():
result = func()
return result.upper()
return wrapper
@uppercase_decorator
def greet():
return "hello world"
print(greet()) # "HELLO WORLD"
# Decorator with arguments
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello() # Prints "Hello!" 3 times
# Built-in decorators
class MyClass:
@staticmethod
def static_method():
print("Static method")
@classmethod
def class_method(cls):
print("Class method")
@property
def my_property(self):
return self._value
Object-Oriented Programming
Classes and Objects
class Person:
# Class variable
species = "Homo sapiens"
# Constructor
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age
# Instance method
def greet(self):
return f"Hello, I'm {self.name}"
# String representation
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
# Create objects
person1 = Person("Venu", 30)
person2 = Person("John", 25)
print(person1.greet()) # "Hello, I'm Venu"
print(person1) # "Person(name=Venu, age=30)"
Inheritance
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
# Derived class
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# Usage
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # "Buddy says Woof!"
print(cat.speak()) # "Whiskers says Meow!"
# Multiple inheritance
class A:
def method_a(self):
print("Method A")
class B:
def method_b(self):
print("Method B")
class C(A, B):
pass
c = C()
c.method_a()
c.method_b()
Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
# print(account.__balance) # AttributeError
Polymorphism
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Polymorphism in action
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(f"Area: {shape.area()}")
Exception Handling
# Basic try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
value = int("abc")
except (ValueError, TypeError) as e:
print(f"Error: {e}")
# Catch all exceptions
try:
# risky code
pass
except Exception as e:
print(f"An error occurred: {e}")
# Try-except-else-finally
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
else:
print("File read successfully")
finally:
file.close() # Always executes
# Raise exceptions
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
# Custom exceptions
class InvalidEmailError(Exception):
pass
def validate_email(email):
if "@" not in email:
raise InvalidEmailError("Invalid email format")
File Handling
# Write to file
with open("data.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python is awesome!")
# Read from file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
# Read all lines
with open("data.txt", "r") as file:
lines = file.readlines()
# Append to file
with open("data.txt", "a") as file:
file.write("\nNew line")
# Binary files
with open("image.jpg", "rb") as file:
data = file.read()
# JSON files
import json
# Write JSON
data = {"name": "Venu", "age": 30}
with open("data.json", "w") as file:
json.dump(data, file, indent=2)
# Read JSON
with open("data.json", "r") as file:
data = json.load(file)
# CSV files
import csv
# Write CSV
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Venu", 30])
# Read CSV
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Modules and Packages
# Import entire module
import math
print(math.sqrt(16))
# Import specific functions
from math import sqrt, pi
print(sqrt(16))
print(pi)
# Import with alias
import numpy as np
import pandas as pd
# Import all (not recommended)
from math import *
# Create your own module
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# main.py
import mymodule
print(mymodule.greet("Venu"))
# Package structure
"""
mypackage/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
"""
# Import from package
from mypackage import module1
from mypackage.subpackage import module3
Real-World Examples
Web Scraper
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# Extract titles
titles = soup.find_all('h2')
for title in titles:
print(title.text.strip())
# Usage
scrape_website('https://example.com')
REST API Client
import requests
class APIClient:
def __init__(self, base_url):
self.base_url = base_url
def get_users(self):
response = requests.get(f"{self.base_url}/users")
return response.json()
def create_user(self, user_data):
response = requests.post(
f"{self.base_url}/users",
json=user_data
)
return response.json()
# Usage
client = APIClient("https://api.example.com")
users = client.get_users()
Data Processing
import pandas as pd
# Read CSV
df = pd.read_csv("data.csv")
# Data analysis
print(df.head())
print(df.describe())
print(df.groupby("category").mean())
# Filter data
filtered = df[df["age"] > 25]
# Add new column
df["full_name"] = df["first_name"] + " " + df["last_name"]
# Save to CSV
df.to_csv("processed_data.csv", index=False)
Best Practices
Code Style (PEP 8)
# ✅ Good: Clear naming
def calculate_total_price(items):
return sum(item.price for item in items)
# ❌ Avoid: Unclear naming
def calc(x):
return sum(i.p for i in x)
# ✅ Good: Proper indentation (4 spaces)
if condition:
do_something()
do_another_thing()
# ✅ Good: Line length < 79 characters
# ✅ Good: Two blank lines between functions
# ✅ Good: One blank line between methods
Error Handling
# ✅ Good: Specific exceptions
try:
value = int(user_input)
except ValueError:
print("Invalid number")
# ❌ Avoid: Bare except
try:
risky_operation()
except:
pass
Documentation
def calculate_area(radius):
"""
Calculate the area of a circle.
Args:
radius (float): The radius of the circle
Returns:
float: The area of the circle
Raises:
ValueError: If radius is negative
"""
if radius < 0:
raise ValueError("Radius cannot be negative")
return 3.14 * radius ** 2
Summary
Python is a powerful, versatile language perfect for beginners and experts:
✅ Simple Syntax - Easy to read and write ✅ Dynamic Typing - Flexible and productive ✅ Rich Standard Library - Batteries included ✅ Large Ecosystem - 300,000+ packages ✅ Multiple Paradigms - OOP, functional, procedural ✅ Great Community - Extensive support
Key Concepts Mastered
- Variables and data types
- Control flow and loops
- Functions and lambda expressions
- Collections (lists, tuples, sets, dicts)
- Object-oriented programming
- Exception handling
- File I/O
- Modules and packages
Next Steps
- Learn web frameworks (Django, Flask, FastAPI)
- Explore data science (Pandas, NumPy, Matplotlib)
- Study machine learning (scikit-learn, TensorFlow)
- Master async programming (asyncio)
- Build real projects
- Contribute to open source
Remember: Python's philosophy is "There should be one-- and preferably only one --obvious way to do it." Write clean, readable, Pythonic code! 🐍