Python is one of the most popular programming languages, known for its simplicity and readability. This guide covers all the Python fundamentals you need to get started.
Why Learn Python? #
- Easy to learn - Simple, readable syntax
- Versatile - Web, data science, AI, automation
- Large community - Extensive libraries and support
- High demand - Popular in industry
- Great for beginners - Gentle learning curve
Installing Python #
Download from python.org or use a package manager:
# macOS (Homebrew)
brew install python3
# Ubuntu/Debian
sudo apt-get install python3
# Verify installation
python3 --versionRunning Python #
# Interactive shell
python3
# Run a file
python3 script.py
# Run directly
./script.py # Add #!/usr/bin/env python3 at topVariables and Data Types #
Variables #
# No type declaration needed
name = "Alice"
age = 25
height = 5.7
is_student = True
# Multiple assignment
x, y, z = 1, 2, 3
# Same value
a = b = c = 0Numbers #
# Integer
count = 42
big_number = 1_000_000 # Underscores for readability
# Float
price = 19.99
scientific = 3.14e-10
# Complex
complex_num = 3 + 4j
# Operations
sum_val = 10 + 5 # 15
diff = 10 - 5 # 5
product = 10 * 5 # 50
quotient = 10 / 3 # 3.333...
floor_div = 10 // 3 # 3
remainder = 10 % 3 # 1
power = 2 ** 3 # 8Strings #
# Single or double quotes
name = 'Alice'
message = "Hello World"
# Multi-line
text = """This is
a multi-line
string"""
# String operations
greeting = "Hello" + " " + "World" # Concatenation
repeat = "Ha" * 3 # "HaHaHa"
# String methods
text = "hello world"
print(text.upper()) # "HELLO WORLD"
print(text.capitalize()) # "Hello world"
print(text.title()) # "Hello World"
print(text.replace("world", "Python")) # "hello Python"
print(text.split()) # ['hello', 'world']
print(" spaces ".strip()) # "spaces"
# String indexing and slicing
text = "Python"
print(text[0]) # "P"
print(text[-1]) # "n"
print(text[0:3]) # "Pyt"
print(text[2:]) # "thon"
print(text[:4]) # "Pyth"
# F-strings (formatted strings)
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old")
print(f"Next year I'll be {age + 1}")Booleans #
is_valid = True
is_empty = False
# Boolean operations
print(True and False) # False
print(True or False) # True
print(not True) # False
# Comparison operators
print(5 > 3) # True
print(5 < 3) # False
print(5 == 5) # True
print(5 != 3) # True
print(5 >= 5) # TrueLists #
Ordered, mutable collections:
# Create list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# Access elements
print(fruits[0]) # "apple"
print(fruits[-1]) # "cherry"
# Slicing
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
# Modify
fruits[0] = "orange"
fruits.append("grape")
fruits.insert(1, "mango")
fruits.remove("banana")
popped = fruits.pop() # Remove and return last
# List methods
numbers = [3, 1, 4, 1, 5]
numbers.sort() # [1, 1, 3, 4, 5]
numbers.reverse() # [5, 4, 3, 1, 1]
print(numbers.count(1)) # 2
print(numbers.index(4)) # 2
# List operations
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2 # [1, 2, 3, 4]
repeated = [0] * 3 # [0, 0, 0]
print(3 in [1, 2, 3]) # True
print(len([1, 2, 3])) # 3
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]Tuples #
Ordered, immutable collections:
# Create tuple
point = (3, 4)
person = ("Alice", 25, "Engineer")
# Access elements
print(point[0]) # 3
# Unpacking
x, y = point
name, age, job = person
# Tuple methods
numbers = (1, 2, 3, 2, 1)
print(numbers.count(2)) # 2
print(numbers.index(3)) # 2Dictionaries #
Key-value pairs:
# Create dictionary
user = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Access values
print(user["name"]) # "Alice"
print(user.get("age")) # 25
print(user.get("email", "N/A")) # "N/A" (default)
# Modify
user["age"] = 26
user["email"] = "alice@example.com"
# Delete
del user["city"]
removed = user.pop("email")
# Dictionary methods
print(user.keys()) # dict_keys(['name', 'age'])
print(user.values()) # dict_values(['Alice', 26])
print(user.items()) # dict_items([('name', 'Alice'), ('age', 26)])
# Check existence
print("name" in user) # True
# Dictionary comprehension
squares = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}Sets #
Unordered collections of unique elements:
# Create set
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
# Add and remove
fruits.add("orange")
fruits.remove("banana") # Error if not exists
fruits.discard("grape") # No error if not exists
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # Union: {1, 2, 3, 4, 5}
print(set1 & set2) # Intersection: {3}
print(set1 - set2) # Difference: {1, 2}
print(set1 ^ set2) # Symmetric difference: {1, 2, 4, 5}Control Flow #
If Statements #
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
# Ternary operator
status = "Adult" if age >= 18 else "Minor"For Loops #
# Loop through list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Loop with range
for i in range(5): # 0 to 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
# Loop with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Loop through dictionary
user = {"name": "Alice", "age": 25}
for key, value in user.items():
print(f"{key}: {value}")While Loops #
count = 0
while count < 5:
print(count)
count += 1
# Break and continue
for i in range(10):
if i == 3:
continue # Skip this iteration
if i == 7:
break # Exit loop
print(i)Functions #
# Define function
def greet(name):
return f"Hello, {name}!"
# Call function
message = greet("Alice")
print(message)
# Default parameters
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(5, 3)) # 125
# Multiple return values
def get_coordinates():
return 10, 20
x, y = get_coordinates()
# *args (variable arguments)
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4)) # 10
# **kwargs (keyword arguments)
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="NYC")
# Lambda functions
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda x, y: x + y
print(add(3, 4)) # 7File I/O #
# Write file
with open("file.txt", "w") as f:
f.write("Hello World\n")
f.write("Second line\n")
# Read file
with open("file.txt", "r") as f:
content = f.read()
print(content)
# Read lines
with open("file.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines
with open("file.txt", "r") as f:
lines = f.readlines()
# Append to file
with open("file.txt", "a") as f:
f.write("Appended line\n")Exception Handling #
# 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}")
# Finally block
try:
file = open("file.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found")
finally:
file.close() # Always executes
# Raise exceptions
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / bClasses and Objects #
# Define class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
def is_adult(self):
return self.age >= 18
# Create object
person = Person("Alice", 25)
print(person.name) # "Alice"
print(person.greet()) # "Hello, I'm Alice"
print(person.is_adult()) # True
# Inheritance
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
return f"{self.name} is studying"
student = Student("Bob", 20, "S12345")
print(student.greet()) # Inherited method
print(student.study()) # Own methodModules #
# Import module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
# Import specific items
from math import sqrt, pi
print(sqrt(16))
# Import with alias
import numpy as np
# Import all (not recommended)
from math import *
# Create your own module (mymodule.py)
# def greet(name):
# return f"Hello, {name}"
# Use it
import mymodule
print(mymodule.greet("Alice"))List Comprehensions #
# Basic
squares = [x**2 for x in range(10)]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
# With transformation
words = ["hello", "world"]
upper_words = [word.upper() for word in words]
# Nested
matrix = [[i*j for j in range(3)] for i in range(3)]
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
# Set comprehension
unique_lengths = {len(word) for word in ["hello", "world", "hi"]}Common Built-in Functions #
# Type conversion
int("42") # 42
float("3.14") # 3.14
str(42) # "42"
list("abc") # ['a', 'b', 'c']
# Math functions
abs(-5) # 5
min(1, 2, 3) # 1
max(1, 2, 3) # 3
sum([1, 2, 3]) # 6
round(3.7) # 4
pow(2, 3) # 8
# Sequence functions
len([1, 2, 3]) # 3
sorted([3, 1, 2]) # [1, 2, 3]
reversed([1, 2, 3]) # [3, 2, 1]
enumerate(['a', 'b', 'c']) # [(0, 'a'), (1, 'b'), (2, 'c')]
zip([1, 2], ['a', 'b']) # [(1, 'a'), (2, 'b')]
# Type checking
type(42) # <class 'int'>
isinstance(42, int) # True
# Input
name = input("Enter name: ")Best Practices #
- Follow PEP 8 style guide
- Use meaningful variable names
- Write docstrings for functions
- Use list comprehensions when appropriate
- Handle exceptions properly
- Use with statements for files
- Keep functions small and focused
- Use virtual environments for projects
- Comment complex logic
- Test your code
Python’s simplicity and power make it perfect for beginners and experts alike. Master these fundamentals and you’re ready to build real applications.