Python Basics

Learn Python programming fundamentals

Python Basics

Python is a high-level, interpreted programming language known for its readability and simplicity. This guide covers the fundamentals you need to get started with Python programming.

Variables

Python variables are dynamically typed - no type declaration needed:

# Variable assignment
name = "Python"
age = 30
price = 19.99
is_active = True
value = None  # Python's null

# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0

# Variable naming
user_name = "developer"  # snake_case (Python convention)
MAX_SIZE = 100           # UPPERCASE for constants

Data Types

Python has several built-in data types:

# Strings
name = "Python"
greeting = 'Hello, World!'
multiline = """This is a
multiline string"""
formatted = f"Hello, {name}!"  # f-strings (Python 3.6+)

# Numbers
integer = 42
float_num = 3.14
complex_num = 3 + 4j

# Booleans
is_active = True
is_complete = False

# None (Python's null)
value = None

Lists

Lists are ordered, mutable collections:

# Creating lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# Accessing elements
fruits[0]        # "apple" (first element)
fruits[-1]       # "orange" (last element)
fruits[1:3]      # ["banana", "orange"] (slicing)

# Adding elements
fruits.append("grape")        # Add to end
fruits.insert(0, "kiwi")     # Insert at index
fruits.extend(["mango", "pear"])  # Add multiple

# Removing elements
fruits.remove("banana")       # Remove by value
fruits.pop()                  # Remove last
fruits.pop(0)                 # Remove at index
del fruits[0]                 # Delete at index

# List methods
len(fruits)                   # Get length
fruits.count("apple")         # Count occurrences
fruits.index("orange")        # Find index
fruits.sort()                 # Sort in place
sorted(fruits)                # Return sorted copy

Dictionaries

Dictionaries are key-value pairs:

# Creating dictionaries
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Or with dict()
person2 = dict(name="Jane", age=25)

# Accessing values
person["name"]                # "John"
person.get("name")            # "John" (safe, returns None if missing)
person.get("email", "N/A")   # "N/A" (default value)

# Adding/updating
person["email"] = "john@example.com"
person["age"] = 31

# Dictionary methods
person.keys()                 # dict_keys(['name', 'age', 'city'])
person.values()               # dict_values(['John', 30, 'New York'])
person.items()                # dict_items([('name', 'John'), ...])
"name" in person              # True
len(person)                   # 3

Tuples

Tuples are immutable ordered collections:

# Creating tuples
coordinates = (10, 20)
point = 3, 4  # Parentheses optional
single = (42,)  # Comma required for single element

# Accessing elements
coordinates[0]  # 10
coordinates[1]  # 20

# Unpacking
x, y = coordinates  # x=10, y=20

Sets

Sets are unordered collections of unique elements:

# Creating sets
unique_numbers = {1, 2, 3, 4, 5}
fruits = set(["apple", "banana", "apple"])  # {"apple", "banana"}

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.union(set2)        # {1, 2, 3, 4, 5}
set1.intersection(set2)  # {3}
set1.difference(set2)    # {1, 2}

Loops

Python offers several iteration methods:

# For loop (most common)
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# For loop with index
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# For loop with range
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

for i in range(1, 6):
    print(i)  # 1, 2, 3, 4, 5

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

# Loop control
for fruit in fruits:
    if fruit == "banana":
        continue  # Skip to next iteration
    if fruit == "orange":
        break     # Exit loop
    print(fruit)

# List comprehension
squared = [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]

Conditionals

Control flow with if/else statements:

# If/else
age = 20
if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

# Ternary operator
status = "Adult" if age >= 18 else "Minor"

# Logical operators
if age >= 18 and has_license:
    print("Can drive")

if is_weekend or is_holiday:
    print("Day off")

if not is_complete:
    print("Not done yet")

# Membership operators
if "apple" in fruits:
    print("Found apple")

if "grape" not in fruits:
    print("No grape")

Functions

Functions are defined with def:

# Simple function
def greet(name):
    return f"Hello, {name}!"

print(greet("Python"))  # "Hello, Python!"

# Function with default parameters
def greet(name="World"):
    return f"Hello, {name}!"

# Function with multiple parameters
def calculate_total(price, tax=0.1):
    return price * (1 + tax)

# Function returning multiple values
def get_name_and_age():
    return "John", 30

name, age = get_name_and_age()

# Lambda functions (anonymous)
square = lambda x: x ** 2
print(square(5))  # 25

# *args and **kwargs
def print_all(*args, **kwargs):
    for arg in args:
        print(arg)
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_all(1, 2, 3, name="John", age=30)

Classes

Python supports object-oriented programming:

# Defining a class
class Person:
    # Class variable
    species = "Homo sapiens"
    
    # Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # Instance method
    def introduce(self):
        return f"Hi, I'm {self.name} and I'm {self.age} years old"
    
    # String representation
    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

# Creating objects
person = Person("John", 30)
print(person.introduce())
print(person.name)  # "John"
person.age = 31

Common Patterns

# Map (list comprehension preferred)
numbers = [1, 2, 3, 4]
squared = [x**2 for x in numbers]  # [1, 4, 9, 16]

# Filter
evens = [x for x in numbers if x % 2 == 0]  # [2, 4]

# Reduce (from functools)
from functools import reduce
sum = reduce(lambda acc, n: acc + n, numbers, 0)  # 10

# Zip (combine lists)
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age}")