A comprehensive handbook for Python beginners
Python is an easy-to-learn, versatile, and popular programming language. It is used in various fields such as web development, data analysis, AI, automation, and more.
Python's readability and simplicity make it perfect for beginners. Its "batteries included" philosophy means you can accomplish a lot with minimal code, allowing you to focus on solving problems rather than wrestling with syntax.
python --version
.Python has two major versions still in use: Python 2 and Python 3. Always use Python 3 for new projects as Python 2 is no longer supported. Most modern code examples and libraries are written for Python 3.
Variables store data. Python is dynamically typed, meaning you don't need to declare variable types explicitly.
Type | Description | Example |
---|---|---|
Integer | Whole numbers | 42 |
Float | Decimal numbers | 3.14 |
String | Text | 'Hello' |
Boolean | Truth values | True , False |
List | Ordered collection | [1, 2, 3] |
Dictionary | Key-value pairs | {'name': 'Alice'} |
Use descriptive names for variables. Python convention is to use lowercase with underscores for variable names (snake_case), like user_name
or total_score
.
input()
- Gets user input from the consoleprint()
- Displays information to the consoleEven if the user enters a number, input()
returns it as a string.
Convert the input to the appropriate type: age = int(input("Enter age: "))
Trying to use a variable that hasn't been defined yet will cause an error.
Always initialize variables before using them.
if
, elif
, else
)Conditional statements allow your program to make decisions based on conditions.
You can combine conditions using logical operators: and
, or
, and not
.
Example: if age >= 18 and has_id == True:
Loops allow you to repeat code multiple times.
for
loop:Used to iterate over a sequence (like a list, tuple, or string).
while
loop:Repeats as long as a condition is true.
A while loop will run forever if its condition never becomes False.
Always ensure there's a way for the loop condition to become False. Include a counter or break statement if necessary.
Python uses indentation to define code blocks. Inconsistent indentation causes errors.
Use consistent indentation (4 spaces per level is the Python standard).
Functions are reusable blocks of code that perform specific tasks.
Always include docstrings in your functions to explain what they do. This helps other developers (and future you) understand your code. You can access a function's docstring using help(function_name)
.
Small anonymous functions defined with the lambda
keyword.
If you don't include a return statement, the function returns None by default.
Always include a return statement if your function needs to produce a value.
Using mutable objects (like lists or dictionaries) as default arguments can lead to unexpected behavior.
Use None as the default and create the mutable object inside the function.
Ordered, mutable collections of items.
Collections of key-value pairs, allowing fast lookup by key.
Ordered, immutable collections of items.
Unordered collections of unique items.
This can lead to unexpected behavior or errors.
Create a copy of the list to iterate over, or use list comprehension to create a new filtered list.
Trying to access a non-existent key with square brackets raises a KeyError.
Use the .get() method with a default value: dict.get('key', default_value)
Lists and dictionaries are mutable (can be changed), while strings, tuples, and numbers are immutable.
Be aware of which data types are mutable and which are immutable. When you need an unchangeable collection, use a tuple instead of a list.
Classes are blueprints for creating objects. Objects are instances of classes.
Inheritance allows a class to inherit attributes and methods from another class.
Python classes can implement special methods (also called "dunder" methods) that allow instances to work with built-in functions and operators.
All instance methods need self as their first parameter.
Always include self as the first parameter in instance methods.
Class attributes are shared by all instances, while instance attributes are unique to each instance.
Define instance attributes in __init__ with self.attribute_name, and class attributes directly in the class body.
Reading from and writing to files is a common task in programming.
Always use the with
statement when working with files. It automatically handles closing the file, even if an exception occurs.
Handling errors gracefully to prevent program crashes.
Organizing code into reusable modules and packages.
Concise ways to create lists and generate sequences of values.
Use generators when working with large sequences to save memory. Generators produce values on-demand rather than storing the entire sequence in memory.
Functions that modify the behavior of other functions.
Python uses indentation to define code blocks. Mixing tabs and spaces or using inconsistent indentation causes errors.
Use consistent indentation (4 spaces per level is the Python standard). Configure your editor to convert tabs to spaces.
Variables defined inside a function are not accessible outside that function.
Return values from functions if you need to use them outside. Use global variables sparingly and with caution.
This can lead to unexpected behavior and hard-to-find bugs.
Use the global keyword if you must modify a global variable, but it's better to pass variables as arguments and return modified values.
Default arguments are evaluated only once when the function is defined, not each time the function is called.
Use None as the default and create the mutable object inside the function.
When you assign a mutable object (like a list) to a new variable, both variables reference the same object.
Use appropriate copy methods: .copy(), list(), slicing [:], or copy.deepcopy() for nested structures.
Using + to concatenate many strings in a loop is inefficient.
Use join() for concatenating multiple strings, or f-strings/format() for formatting.