Python Basics: A Beginner's Guide
github.com/kristofer june 2025, v2
What is Python?
Python is a popular, high-level programming language known for its simplicity and readability. It follows a “batteries included” philosophy and is used for web development, data science, automation, scientific computing, and more.
Basic Program Structure
A basic Python program consists of statements that are executed from top to bottom. Code is organized into functions to promote reuse and clarity, with the main() function often serving as the program’s entry point. Python uses indentation (spaces or tabs) to define code blocks instead of braces or keywords, making code visually clear and easy to follow. For beginners, it’s helpful to start with simple scripts and gradually introduce functions and modules as programs grow in complexity. This means, among other things, that WHITESPACE matters in python (unlike in, say, java).
1# hello_world.py
2def main():
3    print("Hello, World!")
4
5if __name__ == "__main__":
6    main()Or even simpler:
1print("Hello, World!")Data Types
Data types are fundamental in programming because they define what kind of data a variable can hold and what operations can be performed on it. For example, numbers can be added or multiplied, while strings can be concatenated. Data types help the programmer (and the computer) understand how to store, process, and validate information, reducing errors and making code more predictable and efficient. Using the correct data type ensures your program behaves as expected and is easier to read and maintain.
Basic Types
1# Numbers
2i = 42                  # Integer (unlimited precision)
3f = 3.14159             # Float (64-bit)
4c = 3 + 4j              # Complex number
5
6# Other basic types
7s = "Hello"             # String
8b = True                # Boolean (True or False)
9n = None                # None type (similar to null)Collection Types
Python’s built-in types are fundamental data structures that make it easy to represent and manipulate data. Here’s why they’re important:
Core Built-in Types
- int, float, complex: Numbers for arithmetic and scientific calculations.
- str: Strings for text processing.
- bool: Boolean values for logic and control flow.
- NoneType: Represents the absence of a value.
Collection Types
- list: Ordered, mutable sequences.
- tuple: Ordered, immutable sequences.
- dict: Key-value mappings for fast lookups.
- set: Unordered collections of unique elements.
Why They Matter
- Expressiveness: You can represent complex data (like a list of user records or a mapping of names to scores) with simple, readable syntax.
- Less Boilerplate: No need to define custom classes for common data structures.
- Rich Methods: Built-in types come with powerful methods (e.g., list.append(),dict.get()) that reduce the need for manual loops and logic.
- Interoperability: Standard types work seamlessly with Python’s libraries and functions.
- Performance: Built-in types are implemented in C, making them fast and memory-efficient.
Example:
1users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
2names = [user["name"] for user in users if user["age"] > 26]
3# Output: ['Alice']Summary:
Python’s built-in types let you solve problems with less code and complexity by providing ready-to-use, efficient, and expressive data structures.
1# Built-in collections
2my_list = [1, 2, 3]     # List (mutable)
3my_tuple = (1, 2, 3)    # Tuple (immutable)
4my_dict = {"key": 42}   # Dictionary (key-value pairs)
5my_set = {1, 2, 3}      # Set (unique elements)Variables and Constants
Variables are like labeled containers that store data in your program. Unlike some programming languages, Python doesn’t require you to declare what type of data a variable will hold - it figures this out automatically when you assign a value. This makes Python very flexible and beginner-friendly. Variables can be reassigned to different values and even different types throughout your program.
Constants, on the other hand, are values that shouldn’t change during program execution. While Python doesn’t enforce constants like some languages do, programmers use a naming convention (ALL_CAPS) to indicate that a variable should be treated as a constant. This helps other programmers (including your future self) understand that these values are meant to remain unchanged.
1# Variable declaration and assignment
2number = 42             # No type declaration needed
3value = 100
4
5# Constants (by convention)
6PI = 3.14159            # ALL_CAPS indicates constant (convention only)Control Structures
Control structures are the building blocks that allow your program to make decisions and repeat actions. They control the “flow” of your program - determining which code runs when, and how many times. Without control structures, programs would only be able to execute instructions in a straight line from top to bottom, making them very limited. Think of control structures as the decision-making and repetition mechanisms that make programs intelligent and dynamic.
Conditionals
Conditionals allow your program to make decisions based on different conditions. The if statement is like asking a question: “Is this condition true?” If yes, execute this block of code. The elif (else if) allows you to check multiple conditions in sequence, while else provides a fallback for when none of the conditions are met. This mimics how we make decisions in real life - we evaluate conditions and take different actions based on the results.
 1# If statement
 2if condition:
 3    # code
 4elif other_condition:
 5    # code
 6else:
 7    # code
 8
 9# Match statement (Python 3.10+)
10match value:
11    case 1:
12        # code
13    case 2:
14        # code
15    case _:
16        # default codeLoops
Loops are essential for automating repetitive tasks in programming. Instead of writing the same code multiple times, loops allow you to execute a block of code repeatedly. The for loop is ideal when you know how many times you want to repeat something or when you want to process each item in a collection. The while loop continues executing as long as a condition remains true, making it perfect for situations where you don’t know in advance how many iterations you’ll need.
 1# For loop
 2for i in range(5):
 3    # code
 4
 5# While loop
 6while condition:
 7    # code
 8
 9# For loop with collection
10for item in collection:
11    # code
12
13# List comprehension (unique to Python)
14squares = [x**2 for x in range(10)]Collections
Collections are data structures that allow you to store and organize multiple pieces of related data together. Instead of creating separate variables for each piece of data (like student1, student2, student3), collections let you group them logically and work with them efficiently. Python provides several built-in collection types, each optimized for different use cases and patterns of access.
Lists
Lists are Python’s most versatile collection type. They’re ordered (items have a specific position), mutable (you can change them after creation), and can store any type of data. Think of a list as a numbered sequence of items, like a shopping list or a roster of students. You can add items, remove items, change items, and access items by their position (index). Lists are perfect when you need to maintain order and frequently modify your collection.
1# List creation
2numbers = [1, 2, 3, 4, 5]
3empty_list = []
4typed_list = list()
5
6# Accessing elements
7numbers[0] = 42
8first_value = numbers[0]Dictionaries
Dictionaries store data as key-value pairs, like a real dictionary where you look up a word (key) to find its definition (value). They’re incredibly useful when you need to associate pieces of information or when you want fast lookups by a specific identifier. For example, you might use a dictionary to store student information where the student ID is the key and the student’s details are the value. Dictionaries are unordered (in older Python versions) but maintain insertion order in Python 3.7+.
1# Dictionary creation
2person = {"name": "John", "age": 30}
3empty_dict = {}
4typed_dict = dict()
5
6# Accessing elements
7person["name"] = "Jane"
8name = person["name"]
9age = person.get("age", 0)  # Returns 0 if key doesn't existFunctions
Functions are reusable blocks of code that perform specific tasks. They’re like mini-programs within your program that take inputs (parameters), do something with those inputs, and often return a result. Functions help you avoid repeating code, make your programs more organized, and break complex problems into smaller, manageable pieces. Good functions do one thing well and have descriptive names that make your code self-documenting.
Python functions are very flexible - they can have default parameter values, accept variable numbers of arguments, and even accept keyword arguments. This flexibility makes Python functions powerful tools for creating clean, readable code.
 1# Function definition
 2def add(a, b):
 3    return a + b
 4
 5# Function with default parameters
 6def greet(name="World"):
 7    return f"Hello, {name}!"
 8
 9# Function with *args and **kwargs
10def example(*args, **kwargs):
11    print(f"Args: {args}")
12    print(f"Kwargs: {kwargs}")Classes and Objects
Classes and objects form the foundation of object-oriented programming (OOP). A class is like a blueprint or template that defines what data (attributes) and behaviors (methods) objects of that type will have. An object is a specific instance created from that class blueprint. For example, if you have a Car class, it might define that all cars have attributes like color and model, and behaviors like start and stop. Each individual car object (like “my red Toyota” or “your blue Ford”) would be an instance of the Car class.
Object-oriented programming helps organize complex programs by grouping related data and functions together, making code more modular, reusable, and easier to understand and maintain.
Basic Class Structure
 1class Person:
 2    # Class variable
 3    species = "Human"
 4    
 5    # Constructor
 6    def __init__(self, name, age):
 7        # Instance variables
 8        self.name = name
 9        self.age = age
10    
11    # Instance method
12    def get_name(self):
13        return self.name
14    
15    def set_name(self, name):
16        self.name = name
17        
18    # String representation
19    def __str__(self):
20        return f"{self.name}, {self.age} years old"Creating Objects
1person = Person("John", 25)
2name = person.get_name()Exception Handling
Exception handling is how Python deals with errors that occur during program execution. Rather than letting your program crash when something goes wrong, exception handling allows you to anticipate potential problems and handle them gracefully. This makes your programs more robust and user-friendly. For example, if a user enters invalid input or a file doesn’t exist, you can catch these errors and provide helpful feedback instead of a confusing crash.
The try-except structure works like this: “Try to do this code, but if something goes wrong (an exception occurs), execute this alternative code instead.” The finally block contains code that runs regardless of whether an exception occurred, making it perfect for cleanup tasks like closing files or database connections.
 1try:
 2    # Code that might raise an exception
 3    result = 10 / 0
 4except ZeroDivisionError as e:
 5    # Handle specific exception
 6    print(f"Error: {e}")
 7except Exception as e:
 8    # Handle any other exception
 9    print(f"Unexpected error: {e}")
10finally:
11    # Always executed
12    print("Cleanup code")Input and Output
Input and output (I/O) operations allow your programs to interact with users and the outside world. Input operations let you collect information from users, while output operations let you display results, messages, or data back to users. Most interactive programs need both - they ask for information, process it, and then show the results.
Python’s input() function always returns a string, so if you need a number, you’ll need to convert it using functions like int() or float(). The print() function is very flexible and can display multiple values, format strings in various ways, and control output formatting.
1# Console input
2name = input("Enter your name: ")
3number = int(input("Enter a number: "))
4
5# Console output
6print("Hello")          # With newline
7print("Hello", end="")  # Without newline
8print(f"Hello, {name}") # String formattingBest Practices
- Follow Python naming conventions- Classes: PascalCase (MyClass)
- Functions/Variables: snake_case (my_function)
- Constants: ALL_CAPS (PI)
 
- Follow PEP 8 style guidelines
- Use docstrings to document your code
- Handle exceptions appropriately
- Use meaningful variable and function names
- Keep functions small and focused
- Use list comprehensions when appropriate
- Use context managers (withstatements) for resource management
Next Steps
- Explore advanced data structures (collections module)
- Learn about generators and iterators
- Study file I/O operations
- Learn about decorators and context managers
- Explore Python’s standard library
- Practice with small projects
- Explore Python frameworks (Django, Flask, Pandas, NumPy)
Remember: Python is dynamically typed and uses indentation for code blocks. Its syntax is designed to be readable and concise, making it an excellent language for beginners.