Introduction to Python
Basic Data Types and Variables
Control Flow
Data Structures
Functions and Modules
File Handling
Error Handling and Exceptions
Object-Oriented Programming (OOP)
Working with External Libraries
Practical Projects and Next Steps
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. Created by Guido van Rossum and first released in 1991, Python has become one of the most popular programming languages in the world, used in web development, data science, automation, artificial intelligence, robotics, and more.
Key Features:
Python is ideal for both beginners and experienced developers because:
Open a terminal (Command Prompt, PowerShell, or Terminal) and type:
python --version
or
python3 --version
If you see a version number (e.g., Python 3.11.0
), Python is installed.
You can start the Python interactive shell (REPL) by typing:
python
or
python3
You’ll see a prompt like:
>>>
You can type Python code here and see the results immediately.
Example:
>>> print("Hello, world!")
Hello, world!
Save your code in a file with a .py
extension, for example hello.py
:
print("Hello, world!")
Run the script from the terminal:
python hello.py
You can write Python code in any text editor, but some popular choices include:
Choose the one that best fits your workflow.
Now that you have Python installed and know how to run code, you’re ready to dive into Python’s basic data types and variables in Chapter 2.
Summary:
This chapter introduced Python’s history, features, setup, and how to run Python code interactively and via scripts. You also learned about different editors to write Python code. In the next chapter, we’ll explore the core building blocks of Python: data types and variables.
Every programming language has ways to store and manipulate data. In Python, data is represented using various built-in data types. Understanding these types and how to use variables is essential for building any Python program.
age = 30
temperature = -5
price = 19.99
pi = 3.14159
'...'
) or double ("..."
) quotes.name = "Alice"
greeting = 'Hello, world!'
True
or False
.is_sunny = True
is_raining = False
=
operator.Examples:
x = 5
user_name = "Bob"
has_access = False
Naming Conventions:
snake_case
).You can convert between data types using built-in functions:
age = "30"
age = int(age) # Converts string to integer
price = 10
price_str = str(price) # Converts integer to string
is_valid = bool("non-empty") # Converts to True
print()
print("Welcome to Python!")
print("The answer is", 42)
input()
name = input("Enter your name: ")
print("Hello,", name)
Note:
input()
always returns a string. Convert it to another type if needed.
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
Use the type()
function to check a variable’s data type:
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("hello")) # <class 'str'>
print(type(True)) # <class 'bool'>
print()
for output and input()
for user input.In the next chapter, we’ll see how to use these values in decision-making and loops with control flow statements.
Control flow statements determine the order in which code is executed in a Python program. In this chapter, you’ll learn how to make decisions with conditional statements and how to repeat actions using loops.
Conditional statements let you execute code blocks only if certain conditions are met.
if
Statementx = 10
if x > 5:
print("x is greater than 5")
if-else
Statementage = 17
if age >= 18:
print("You can vote.")
else:
print("You cannot vote.")
if-elif-else
Statementscore = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D or F")
==
: equal to!=
: not equal to<
: less than>
: greater than<=
: less than or equal to>=
: greater than or equal toand
: True if both conditions are Trueor
: True if at least one condition is Truenot
: True if the condition is FalseExample:
temperature = 22
is_sunny = True
if temperature > 20 and is_sunny:
print("Great day for a walk!")
Python uses indentation (spaces or tabs) to define code blocks. Consistent indentation is crucial.
if True:
print("This is indented and part of the if block.")
print("This is outside the if block.")
Loops let you repeat actions multiple times.
while
LoopRepeats as long as a condition is True.
count = 0
while count < 3:
print("Counting:", count)
count += 1
for
LoopIterates over a sequence (list, string, range, etc.).
for letter in "cat":
print(letter)
range()
for i in range(5):
print(i) # Prints 0 to 4
break
: Exit the loop immediately.continue
: Skip to the next iteration.Example:
for i in range(10):
if i == 5:
break # Stops the loop when i is 5
if i % 2 == 0:
continue # Skips even numbers
print(i)
pass
Statementpass
is a placeholder that does nothing; useful when a statement is required syntactically.
if False:
pass # Code not yet implemented
You can nest if
statements and loops inside each other.
for i in range(3):
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")
if
, elif
, and else
for decision-making.for
and while
loops for repetition.break
, continue
, and pass
.In the next chapter, we’ll explore Python’s core data structures: lists, tuples, sets, and dictionaries.
Data structures help you organize, store, and manipulate data efficiently. Python provides several built-in data structures, each suited to different types of tasks. This chapter covers lists, tuples, sets, and dictionaries.
A list is an ordered, mutable collection of items.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
print(fruits[0]) # "apple"
print(fruits[-1]) # "cherry"
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[::2]) # [1, 3, 5]
fruits[1] = "blueberry"
fruits.append("date")
fruits.insert(1, "banana")
print(fruits)
fruits.remove("banana") # Removes first occurrence
popped = fruits.pop() # Removes and returns last item
del fruits[0] # Deletes item at index 0
append(item)
: Add item to endinsert(index, item)
: Insert at indexremove(item)
: Remove first occurrencepop(index)
: Remove and return item at index (default last)sort()
, reverse()
, count(item)
, index(item)
A tuple is an ordered, immutable collection.
coordinates = (4, 5)
person = ("Alice", 30)
single = (42,) # Note the comma
print(coordinates[1]) # 5
A set is an unordered collection of unique items.
colors = {"red", "green", "blue"}
numbers = set([1, 2, 2, 3])
print(numbers) # {1, 2, 3}
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Union: {1, 2, 3, 4, 5}
print(a & b) # Intersection: {3}
print(a - b) # Difference: {1, 2}
add(item)
, remove(item)
, discard(item)
, clear()
A dictionary is an unordered collection of key-value pairs.
person = {"name": "Bob", "age": 25}
empty = dict()
print(person["name"]) # "Bob"
person["age"] = 26
person["city"] = "London"
del person["city"]
removed = person.pop("age")
for key in person:
print(key, person[key])
for value in person.values():
print(value)
for key, value in person.items():
print(key, "->", value)
You can combine data structures:
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25}
]
matrix = [[1, 2], [3, 4]]
These structures are core to organizing data in Python. Next, we’ll see how to write reusable code using functions and modules.
Functions and modules are essential for writing organized, reusable, and maintainable code. Functions let you group code into blocks that can be executed repeatedly, while modules allow you to organize code into separate files and use Python’s vast ecosystem of libraries.
A function is a block of code that performs a specific task and can be called by name.
def greet():
print("Hello!")
greet() # Outputs: Hello!
Functions can take inputs (parameters):
def greet(name):
print("Hello,", name)
greet("Alice") # Outputs: Hello, Alice
You can have multiple parameters:
def add(a, b):
return a + b
result = add(3, 4) # result is 7
Functions can return values using the return
statement.
def square(x):
return x * x
result = square(5) # result is 25
If no return
is specified, the function returns None
.
You can provide default values for parameters:
def greet(name="World"):
print("Hello,", name)
greet() # Outputs: Hello, World
greet("Bob") # Outputs: Hello, Bob
Keyword arguments allow you to specify parameters by name:
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9
print(power(3, exponent=3)) # 27
x = 10 # Global
def foo():
y = 5 # Local
print(x, y)
foo()
# print(y) # Error: y is not defined outside foo()
To modify a global variable inside a function, use the global
keyword.
You can add documentation to functions using docstrings:
def add(a, b):
"""
Returns the sum of a and b.
"""
return a + b
print(add.__doc__)
A module is a file containing Python definitions and code. You can use modules to organize your code and to use external libraries.
import math
print(math.sqrt(16)) # 4.0
You can import specific functions:
from math import sqrt
print(sqrt(25)) # 5.0
You can also give an imported module an alias:
import numpy as np
Any .py
file is a module. For example, if you have mymodule.py
:
# mymodule.py
def hello():
print("Hello from mymodule!")
You can import and use it in another file:
import mymodule
mymodule.hello()
Python comes with many useful modules, such as:
math
— mathematical functionsrandom
— random number generationdatetime
— date and time manipulationos
— operating system utilitiessys
— system-specific parameters and functionsExplore the Python Standard Library documentation for more.
In the next chapter, you’ll learn how to handle files for reading and writing data.
File handling is crucial for reading from and writing to files, allowing your Python programs to interact with data stored on disk. This chapter covers opening, reading, writing, and closing files, as well as best practices for working with files.
Use the built-in open()
function to work with files. The basic syntax is:
file_object = open("filename.txt", "mode")
Common modes:
"r"
: Read (default). Error if file does not exist."w"
: Write. Creates file if it doesn’t exist, truncates if it does."a"
: Append. Creates file if it doesn’t exist."b"
: Binary mode (e.g., "rb"
, "wb"
).Example:
file = open("example.txt", "r")
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()
file = open("output.txt", "w")
file.write("Hello, world!\n")
file.write("This is a new file.\n")
file.close()
file = open("output.txt", "a")
file.write("Adding another line.\n")
file.close()
Always close files to free up system resources.
file = open("data.txt")
# ... work with file ...
file.close()
with
Statements (Context Managers)A safer and more concise way to handle files is with the with
statement, which automatically closes the file:
with open("example.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here
os
and pathlib
modules for cross-platform file paths.Example:
import os
print(os.getcwd()) # Get current working directory
from pathlib import Path
p = Path("folder") / "file.txt"
with open(p, "r") as file:
print(file.read())
Use try-except
blocks to handle errors like missing files:
try:
with open("missing.txt") as file:
data = file.read()
except FileNotFoundError:
print("File not found!")
For binary files, add "b"
to the mode:
with open("image.png", "rb") as file:
data = file.read()
For reading and writing CSV, JSON, and other formats, use modules like csv
and json
:
import json
with open("data.json") as f:
data = json.load(f)
open()
to access files, specifying the appropriate mode.with
statements for automatic closing.csv
and json
for structured file formats.Next, you’ll learn how to handle errors and exceptions in Python programs.
Errors are inevitable in programming. Python provides a robust system for handling errors and exceptions, allowing you to write more reliable and user-friendly programs. In this chapter, you’ll learn how to anticipate, catch, and respond to exceptions.
An exception is an error detected during execution. When an exception occurs, normal program flow is interrupted. If not handled, the program will terminate and display a traceback.
Example:
print(10 / 0) # Raises ZeroDivisionError
numbers = [1, 2, 3]
print(numbers[5]) # Raises IndexError
Use try-except
blocks to handle exceptions gracefully.
Syntax:
try:
# Code that might raise an exception
risky_code()
except SomeException:
# Code to handle the exception
handle_the_problem()
Example:
try:
x = int(input("Enter a number: "))
print(100 / x)
except ValueError:
print("Please enter a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
You can catch any exception by omitting the exception type, but use this sparingly.
try:
# risky code
except:
print("Something went wrong.")
It’s better to catch specific exceptions when possible.
else
runs if no exception occurs.finally
always runs, whether or not there was an exception (useful for cleanup).try:
file = open("data.txt")
except FileNotFoundError:
print("File not found.")
else:
data = file.read()
file.close()
finally:
print("Attempted to open file.")
You can raise exceptions intentionally using the raise
statement.
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
print("Age set to:", age)
set_age(-5) # Raises ValueError
Define your own exception classes by inheriting from Exception
.
class NegativeNumberError(Exception):
pass
def check_positive(number):
if number < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
try:
check_positive(-2)
except NegativeNumberError as e:
print(e)
ValueError
: Wrong value type (e.g., int("abc")
)TypeError
: Wrong data type usedIndexError
: Out-of-range list indexKeyError
: Missing dictionary keyZeroDivisionError
: Division by zeroFileNotFoundError
: File does not existImportError
: Import failsfinally
to close files or release resources.except:
unless you have a very good reason.try-except
blocks for graceful error handling.else
for code that only runs if no exception occurs, and finally
for cleanup.raise
and create custom exceptions as needed.Next, you’ll learn about object-oriented programming and how to use classes and objects in Python.
Object-Oriented Programming (OOP) is a paradigm that organizes code using objects and classes. OOP makes it easier to manage complex programs by grouping data and behavior together, encouraging code reuse and modularity.
A class is a blueprint for creating objects, which are instances of that class.
class Dog:
pass
my_dog = Dog()
print(type(my_dog)) # <class '__main__.Dog'>
Attributes are variables that belong to an object. Methods are functions defined within a class.
__init__
MethodThe __init__
method initializes the object’s attributes.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
my_dog = Dog("Buddy", 5)
print(my_dog.name) # Buddy
Instance methods operate on the object’s data.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, "says woof!")
my_dog = Dog("Fido")
my_dog.bark() # Fido says woof!
class Cat:
species = "Felis catus" # Class attribute
def __init__(self, name):
self.name = name # Instance attribute
cat1 = Cat("Whiskers")
cat2 = Cat("Luna")
print(cat1.species, cat2.species) # Felis catus Felis catus
Inheritance lets you create a new class based on an existing one.
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
d = Dog()
d.speak() # Woof!
Dog
class inherits from Animal
and overrides the speak
method.super()
FunctionUse super()
to call methods from the parent class.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
_
) to indicate “protected” (by convention).__
) for name mangling (makes it harder to access from outside).class Person:
def __init__(self, name):
self._name = name # Protected
self.__secret = "hidden" # Private
p = Person("Alice")
print(p._name) # Allowed, but discouraged
# print(p.__secret) # AttributeError
Polymorphism allows different classes to provide different implementations of the same method.
class Bird:
def speak(self):
print("Chirp")
class Duck(Bird):
def speak(self):
print("Quack")
animals = [Bird(), Duck()]
for a in animals:
a.speak() # Output: Chirp Quack
Special methods (dunder methods) define behavior for built-in operations.
__str__
: String representation__len__
: Length__eq__
: Equalityclass Book:
def __init__(self, title):
self.title = title
def __str__(self):
return f"Book: {self.title}"
b = Book("1984")
print(b) # Book: 1984
In the next chapter, you’ll learn how to work with external libraries and manage dependencies in Python.
Python’s true power comes from its vast ecosystem of external libraries (also called packages or modules). These libraries expand Python’s capabilities for web development, data science, networking, automation, and much more. This chapter shows you how to find, install, and use external libraries, as well as manage dependencies with virtual environments.
requests
for HTTP, numpy
for numerical computing, pandas
for data analysis, matplotlib
for plotting.pip
pip
is Python’s standard package manager.pip install package_name
pip install --upgrade package_name
pip uninstall package_name
Example:
pip install requests
After installation, import the library in your Python code:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())
Many libraries have their own documentation and usage guides online. Refer to the official docs for best practices.
As your projects grow, you’ll likely need multiple libraries. It’s important to manage dependencies carefully to avoid version conflicts and ensure reproducibility.
pip list
Save a list of installed packages for your project:
pip freeze > requirements.txt
Install all dependencies in another environment:
pip install -r requirements.txt
Virtual environments isolate your project’s dependencies from your system Python and other projects.
python -m venv venv
venv
containing a separate Python environment.Windows:
venv\Scripts\activate
macOS/Linux:
source venv/bin/activate
When active, installed packages go only into this environment.
deactivate
Install and use numpy
:
pip install numpy
import numpy as np
a = np.array([1, 2, 3])
print(a * 2) # [2 4 6]
requirements.txt
to share and reproduce dependencies.pip
to install, upgrade, or remove packages.In the next chapter, you’ll apply what you’ve learned by building small projects and get tips for further learning.
Now that you’ve refreshed your Python skills, it’s time to put your knowledge into practice. In this chapter, you’ll find ideas for small projects, learn basic testing and debugging techniques, and get resources for further learning.
Try building simple projects to reinforce what you’ve learned:
random
library.requests
and beautifulsoup4
libraries to fetch and parse information from a website.pandas
and matplotlib
.Use Python’s built-in unittest
or pytest
frameworks to test your code.
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
test_add()
print("All tests passed!")
import pdb; pdb.set_trace()
git init
.Congratulations on completing your Python refresher! Keep coding and exploring.