Welcome to CodingGear’s Python Cheatsheet, your ultimate quick reference guide to mastering the Python programming language! Whether you’re a student, a professional developer, or just someone curious about Python, this Python cheat sheet is your go-to resource for all things Python.
In this cheat sheet, we’ve distilled the essential Python concepts, syntax, and best practices; from variables and data types to control flow, functions, and libraries, we’ve got you covered. Whether you need to quickly review a specific topic or learn something new, this Python cheat sheet is your trusty companion on your Python journey. You can bookmark this page or download the PDF version of 22 pages.
Enter Your Email & Name To Download the Free Python Cheatsheet
Here’s more to know about the cheat sheet:
- It is inspired by the bestselling Python Crash Course book by Eric Matthes and is based on a part of its curriculum. However, the explanations are based on my own understanding of Python and so are the code snippets. I might earn a small commission if you purchase this book through the link I just provided.
- I do not include the output or results of the code snippets when run to make this page just a little shorter, so I recommend you to copy and paste the code snippets and run them in a code editor.
And another thing, don’t hesitate to let us know what you think about the Python Cheatsheet. If there are any mistakes you came across or even content you wish to be added, just put them down there in the comments section. We’re here for you.
PART 1: SUMMARY OF THE VERY BASICS
1. Variables and Strings
Hello world:
The basic “Hello, World!” program to introduce Python.
print("Hello, World!")
Hello world with a variable: Printing a greeting using a variable.
greeting = "Hello, World!"
print(greeting)
Concatenation (combining strings): Combining strings using the + operator and f-strings.
first_name = "John"
last_name = "Doe"
#using + operator
full_name = first_name + " " + last_name
#using f-strings
greeting = f'Hello world, my name is {first_name} and my surname is {last_name}'
print(full_name)
print(greeting)
2. Lists
Make a list:
Creating a list of items.
fruits = ["apple", "banana", "cherry"]
Get the first item in a list: Accessing the first item of a list.
first_fruit = fruits[0]
Get the last item in a list: Accessing the last item of a list.
last_fruit = fruits[-1]
Looping through a list: Iterating through a list using a for loop.
for fruit in fruits:
print(fruit)
Adding items to a list: Appending items to an existing list.
fruits.append("grape")
Making numerical lists: Creating numerical lists using range.
numbers = list(range(1, 6)) # Creates [1, 2, 3, 4, 5]
List comprehensions: A concise way to create lists.
squares = [x ** 2 for x in range(1, 6)] # Creates [1, 4, 9, 16, 25]
Slicing a list: Extracting specific portions of a list.
selected_fruits = fruits[1:3] # Retrieves ['banana', 'cherry']
**Copying a list: Creating a copy of a list.
copied_fruits = fruits.copy()
3. Tuples
Making a tuple: Creating an immutable sequence of values.
dimensions = (200, 50)
4. If Statements
Conditional tests: Evaluating conditions using if statements.
age = 18
if age >= 18:
print("You can vote!")
Conditional test with lists: Checking if an item is in a list.
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
print("We have apples!")
Assigning boolean values: Storing boolean results in variables.
is_adult = age >= 18
A simple if test: Using the if statement.
if condition:
# Do something
if-elif-else statements: Handling multiple conditions.
age = 18
if age < 18:
print("You're too young")
elif age == 18:
print("You're just old enough")
else:
print("You're an adult")
5. Dictionaries
A simple dictionary: Creating a key-value pair data structure.
person = {"first_name": "John", "last_name": "Doe"}
Accessing a value: Retrieving a value from a dictionary using its key.
first_name = person["first_name"]
Adding a new key-value pair: Expanding a dictionary with a new entry.
person["age"] = 30
Looping through all key-value pairs: Iterating through the items in a dictionary.
for key, value in person.items():
print(key + ": " + str(value))
Looping through all keys: Iterating through the keys in a dictionary.
for key in person.keys():
print(key)
Looping through all the values: Iterating through the values in a dictionary.
for value in person.values():
print(value)
6. User Input
Prompting for a value: Asking the user for input.
name = input("What's your name? ")
Prompting for numerical input: Getting numerical input and converting it.
age = int(input("How old are you? "))
7. While Loops
A simple while loop: Creating a basic loop that repeats until a condition is met.
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
Letting the user choose when to quit: Using a loop to keep a program running until the user decides to exit.
while True:
response = input("Enter 'quit' to exit: ")
if response == 'quit':
break
8. Functions
A simple function: Defining and calling a basic function.
def greet(name):
print("Hello, " + name + "!")
Passing an argument: Passing data to a function.
greet("Alice")
Default values for parameters: Providing default values for function parameters.
def greet(name="Guest"):
print("Hello, " + name + "!")
Returning a value: Getting a result from a function.
def add(a, b):
return a + b
9. Classes
Creating a class: Defining a class to create objects.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
Inheritance: Creating a subclass to inherit properties and methods.
class Beagle(Dog):
pass
Method Overriding: Redefining methods in a subclass.
class Beagle(Dog):
def speak(self):
return "Woof!"
Encapsulation: Restricting access to certain attributes.
class Dog:
def __init__(self, name):
self.__name = name
Polymorphism: Using objects of different classes interchangeably.
def make_sound(animal):
print(animal.speak())
10. Working with Files
Reading a file and storing its lines: Opening a file, reading its contents, and storing them.
with open('filename.txt') as file_object:
lines = file_object.readlines()
Writing to a file: Creating a new file or overwriting an existing one.
with open('filename.txt', 'w') as file_object:
file_object.write("Hello, World!")
Appending to a file: Adding content to an existing file.
with open('filename.txt', 'a') as file_object:
file_object.write("Appending new content.")
11. Exceptions
Catching an exception: Handling errors gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero.")
End of Part 1
Enter Your Email & Name To Download the Free Python Cheatsheet
PART 2: GETTING INTO THE DETAILS OF THE VERY BASICS
1. LISTS
Defining Lists
Making a List
A list is an ordered collection of items, enclosed in square brackets []. Lists can contain elements of different data types.
my_list = [1, 2, 3, 4, 5]
Accessing Elements
Getting the First Element
You can access individual elements in a list by their index. In Python, indexing starts at 0, so the first element is at index 0.
first_element = my_list[0] # Gets the first element (1)
Getting the Second Element
Similarly, you can access the second element at index 1:
second_element = my_list[1] # Gets the second element (2)
Getting the Last Element
To access the last element, you can use negative indexing, where -1 represents the last item, -2 represents the second-to-last, and so on.
last_element = my_list[-1] # Gets the last element (5)
Modifying Individual Items
Changing an Element
You can modify the value of an element in a list by assigning a new value to it using its index.
my_list[2] = 10 # Changes the third element to 10
Adding Elements
Adding an Element to the End of the List
You can append elements to the end of a list using the append() method.
my_list.append(6) # Adds 6 to the end of the list
Starting with an Empty List
To create a list dynamically, start with an empty list and add elements as needed.
empty_list = []
empty_list.append(1)
empty_list.append(2)
Inserting Elements at a Particular Position
Use the insert() method to add an element at a specific index, shifting existing elements to accommodate the new one.
my_list.insert(2, 7) # Inserts 7 at index 2, shifting elements
Removing Elements
Deleting an Element by Its Position
You can remove an element from a list by specifying its index using the del statement.
del my_list[3] # Deletes the element at index 3 (4)
Removing an Item by Its Value
If you know the value you want to remove and don’t know its position, you can use the remove() method.
my_list.remove(5) # Removes the first occurrence of value 5
Popping Elements
Pop the Last Item from a List
The pop() method removes and returns the last item in a list.
last_item = my_list.pop() # Removes and returns the last item (6)
Pop the First Item in a List
To remove and return the first item, specify its index (0).
first_item = my_list.pop(0) # Removes and returns the first item (1)
List Length
Find the Length of a List
The len() function returns the number of items in a list.
length = len(my_list) # Gets the length of the list (4)
Sorting a List
Sorting a List Permanently
You can sort a list in ascending order using the sort() method.
my_list.sort() # Sorts the list in ascending order
Sorting a List Permanently in Reverse Alphabetical Order
To sort a list in descending order, use the sort() method with the reverse parameter set to True.
my_list.sort(reverse=True) # Sorts the list in descending order
Sorting a List Temporarily
The sorted() function creates a sorted copy of a list without modifying the original.
sorted_list = sorted(my_list) # Creates a sorted copy of the list
Reversing the Order of a List
The reverse() method reverses the order of elements in a list.
my_list.reverse() # Reverses the order of the list
Looping Through a List
Printing All Items in a List
You can use a for loop to iterate through all items in a list and perform operations on each element.
for item in my_list:
print(item)
Printing a Message for Each Item, and a Separate Message Afterwards
You can also perform specific actions for each item in a list and additional actions after the loop.
for item in my_list:
print(f"Item: {item}")
print("All items have been printed.")
The range() Function
Printing the Numbers 0 to 1000
The range() function generates a sequence of numbers, and you can use a for loop to print them.
for num in range(1001):
print(num)
Printing the Numbers 1 to 1000
To print numbers from 1 to 1000, specify the starting value (1) in the range() function.
for num in range(1, 1001):
print(num)
Making a List of Numbers from 1 to a Million
You can create a list of numbers from 1 to a million using the list() function with range().
million_nums = list(range(1, 1000001))
Simple Statistics
Finding the Minimum Value in a List
You can find the minimum value in a list using the min() function.
min_value = min(my_list)
Finding the Maximum Value
The max() function helps you find the maximum value in a list.
max_value = max(my_list)
Finding the Sum of All Values
To calculate the sum of all values in a list, use the sum() function.
total_sum = sum(my_list)
Slicing a List
Getting the First Three Items
Slicing allows you to extract a portion of a list. To get the first three items, use slicing with [:3].
first_three = my_list[:3] # Gets the first three items [1, 2, 7]
Getting the Middle Three Items
You can extract a middle portion of a list using slicing with a specified range.
middle_three = my_list[1:4] # Gets the middle three items [2, 7, 10]
Getting the Last Three Items
To obtain the last three items, use negative indexing and slicing.
last_three = my_list[-3:] # Gets the last three items [7, 10, 6]
Copying a List
Making a Copy of a List
Creating a copy of a list ensures that changes made to the copy won’t affect the original list. You can use slicing to achieve this.
new_list = my_list[:] # Creates a copy of my_list
List Comprehensions
Using a Loop to Generate a List of Square Numbers
A loop can be used to generate a list of square numbers.
squares = []
for num in range(1, 6):
squares.append(num ** 2)
Using a Comprehension to Generate a List of Square Numbers
List comprehensions offer a concise way to create lists, especially for simple transformations.
squares = [num ** 2 for num in range(1, 6)]
Using a Loop to Convert a List of Names to Upper Case
You can loop through a list of names and convert them to uppercase.
names = ["alice", "bob", "carol"]
upper_names = []
for name in names:
upper_names.append(name.upper())
Using a Comprehension to Convert a List of Names to Upper Case
List comprehensions can also be used to perform operations on each element of a list.
names = ["alice", "bob", "carol"]
upper_names = [name.upper() for name in names]
Tuples
Defining a Tuple
A tuple is similar to a list but is enclosed in parentheses () and is immutable, meaning its elements cannot be changed once defined.
my_tuple = (1, 2, 3)
Looping Through a Tuple
You can iterate through the elements of a tuple in the same way as a list.
for item in my_tuple:
print(item)
2. DICTIONARIES
Defining a Dictionary
A dictionary is a collection of key-value pairs. In real-life scenarios, dictionaries are often used to represent data where each item has attributes.
Making a Dictionary
# Creating a dictionary representing a person
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
Accessing Values
Getting the Value Associated with a Key
To access a value in a dictionary, use the key as an index. This is similar to looking up information in a real-life dictionary.
# Accessing the person's name
name = person['name'] # 'Alice'
Getting the Value with get()
Using get() is safer because it handles missing keys gracefully by returning a default value if the key doesn’t exist.
# Accessing age with get()
age = person.get('age', 0) # If 'age' key doesn't exist, returns 0
Adding New Key-Value Pairs
Adding a Key-Value Pair
You can add new information to a dictionary by specifying a new key and its associated value.
# Adding the person's gender
person['gender'] = 'Female'
Adding to an Empty Dictionary
In real-life scenarios, you might start with an empty dictionary and populate it as you gather more information.
# Creating an empty dictionary and adding data
empty_dict = {}
empty_dict['name'] = 'Bob'
empty_dict['age'] = 25
Modifying Values
Modifying Values in a Dictionary
Dictionaries are mutable, so you can easily update values associated with existing keys.
# Modifying the person's age
person['age'] = 31
Removing Key-Value Pairs
Deleting a Key-Value Pair
In real-life applications, you may need to remove data from a dictionary when it’s no longer relevant.
# Removing the 'city' key-value pair
del person['city']
Looping Through a Dictionary
Looping Through All Key-Value Pairs
Iterating through a dictionary is useful for processing data or displaying information.
# Looping through and printing all key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Looping Through All the Keys
Sometimes you might need to work with just the keys in a dictionary.
# Looping through and printing all keys
for key in person.keys():
print(key)
Looping Through All the Values
Looping through values can be useful when you need to perform actions on data.
# Looping through and printing all values
for value in person.values():
print(value)
Looping Through All the Keys in Order
In some situations, you might want to work with keys in a specific order, such as sorting them alphabetically.
# Looping through keys in sorted order
for key in sorted(person.keys()):
print(key)
Dictionary Length
Finding a Dictionary’s Length
You can determine the size of a dictionary using the len() function, which is useful for managing and analyzing data.
# Finding the length of the dictionary
length = len(person) # 2 (after removing 'city' key)
Nesting – A List of Dictionaries
Storing Dictionaries in a List
In real-life applications, you might have a list of items, each represented as a dictionary.
# Creating a list of dictionaries for items
items = [
{'name': 'item1', 'price': 10},
{'name': 'item2', 'price': 20}
]
Defining a List of Dictionaries Directly
You can directly define a list of dictionaries, especially when the data structure is known in advance.
# Creating a list of dictionaries directly
items = [
{'name': 'item1', 'price': 10},
{'name': 'item2', 'price': 20}
]
Nesting – Lists in a Dictionary
Storing Lists in a Dictionary
In real-life scenarios, you might use a dictionary to represent a person’s profile, including a list of hobbies or interests.
# Creating a dictionary with a list of hobbies
person = {
'name': 'Alice',
'hobbies': ['reading', 'painting', 'swimming']
}
Nesting – A Dictionary of Dictionaries
Storing Dictionaries in a Dictionary
Complex data structures can be represented by dictionaries of dictionaries, such as storing information about students in a class.
# Creating a dictionary of dictionaries for students
students = {
'student1': {'name': 'Alice', 'age': 20},
'student2': {'name': 'Bob', 'age': 22}
}
Using an OrderedDict
Preserving the Order of Keys and Values
In some applications where the order of data is important, you can use OrderedDict to maintain the order of key-value pairs.
from collections import OrderedDict
# Creating an ordered dictionary
ordered_dict = OrderedDict()
ordered_dict['b'] = 2
ordered_dict['a'] = 1
Generating a Million Dictionaries
Creating a large number of dictionaries can be useful for simulating data or handling a massive dataset.
# Generating a list of a million empty dictionaries (aliens)
aliens = [{} for _ in range(1000000)]
Disclaimer
While nesting can be a powerful tool for organizing data, it’s essential to strike a balance. Excessive nesting can make code complex and harder to maintain. Always consider the readability and maintainability of your code when deciding on data structures. In some cases, using classes or alternative data structures may provide a simpler solution.
3. IF STATEMENTS
What are If Statements
If statements allow you to make decisions in your code based on conditions. They control the flow of your program.
Conditional Control Flow
age = 18
if age >= 18:
print("You are an adult.")
Conditional Tests
Checking for Equality
You can use == to check if two values are equal.
color = 'blue'
if color == 'blue':
print("The color is blue.")
Ignoring Case When Making a Comparison
You can use .lower() or .upper() to make case-insensitive comparisons.
user_input = 'Yes'
if user_input.lower() == 'yes':
print("User answered 'yes'.")
Checking for Inequality
Use != to check if two values are not equal.
status = 'active'
if status != 'inactive':
print("The status is not inactive.")
Numerical Comparisons
Testing Equality and Inequality
Numerical values can be compared using == and !=.
age = 18
if age == 18:
print("You are 18 years old.")
Comparison Operators
You can use comparison operators such as <, >, <=, and >= for numerical comparisons.
value = 42
if value > 50:
print("Value is greater than 50.")
Checking Multiple Conditions
Using and to Check Multiple Conditions
To check if multiple conditions are true, use and.
age = 25
income = 50000
if age >= 18 and income > 30000:
print("You are an adult with a good income.")
Using or to Check Multiple Conditions
To check if at least one condition is true, use or.
age = 16
score = 75
if age < 18 or score >= 70:
print("You are either under 18 or have a good score.")
Boolean Values
Simple Boolean Values
Boolean values, True and False, are used in conditional statements.
is_sunny = True
if is_sunny:
print("It's a sunny day.")
If Statements
Simple if Statement
A simple if statement tests a single condition.
temperature = 25
if temperature > 30:
print("It's hot outside.")
if-else Statements
An if-else statement allows you to specify what happens when the condition is not met.
age = 15
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
The if-elif-else Chain
You can use multiple conditions with if-elif-else to handle different scenarios.
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
else:
print("C")
Conditional Tests with Lists
Testing if a Value is in a List
You can check if an item is in a list using in.
fruits = ['apple', 'banana', 'cherry']
if 'banana' in fruits:
print("Banana is in the list.")
Testing if a Value is Not in a List
To check if an item is not in a list, use not in.
if 'orange' not in fruits:
print("Orange is not in the list.")
Checking if a List is Empty
You can use the if statement to check if a list is empty.
empty_list = []
if not empty_list:
print("The list is empty.")
Accepting Input
Simple Input
You can use input() to accept user input.
name = input("Enter your name: ")
print(f"Hello, {name}!")
Accepting Numerical Input
To accept numerical input, you can convert the input to the desired data type.
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
If statements are fundamental for controlling the logic of your Python programs, allowing you to make decisions based on conditions and respond accordingly. They are crucial for creating dynamic and interactive applications.
4. WHILE LOOPS
What are While Loops
While loops are used to repeat a code block as long as a condition is true, making them useful for tasks that require repetitive execution.
Creating a While Loop
Counting to 5
A simple while loop can be used to count from 1 to 5.
# Counting to 5 with a while loop
count = 1
while count <= 5:
print(count)
count += 1
Letting the User Choose When to Quit
While loops are often used to create interactive programs that continue until the user decides to exit.
# Letting the user choose when to quit
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
Using a Flag
A flag variable can control when a while loop should continue or stop.
# Using a flag to control a while loop
flag = True
while flag:
user_input = input("Continue? (yes/no): ")
if user_input.lower() == 'no':
flag = False
Using break to Exit a Loop
The break statement allows you to exit a loop prematurely when a certain condition is met.
# Using break to exit a loop
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
Using continue in a Loop
The continue statement allows you to skip the rest of the loop iteration and move to the next one.
# Using continue in a loop to skip even numbers
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
print(number)
Avoiding Infinite Loops
An Infinite Loop
An infinite loop runs indefinitely because the condition never becomes False.
Removing All Instances of a Value from a List
# An infinite loop
while True:
print("This loop runs forever!")
Removing All Instances
While loops can be used to remove all occurrences of a specific value from a list.
# Removing all instances of a value from a list
numbers = [1, 2, 3, 4, 2, 5, 2]
value_to_remove = 2
while value_to_remove in numbers:
numbers.remove(value_to_remove)
While loops provide a powerful mechanism for creating iterative processes in Python. They are essential for tasks that require repetitive actions or interactive user input. However, it’s crucial to be cautious with while loops to avoid infinite loops that can freeze your program.
5. FUNCTIONS
What are Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code and make it more manageable.
Reusable Code Blocks
# A simple function that greets the user
def greet_user():
print("Hello!")
# Calling the function
greet_user()
Defining a Function
Making a Function
To create a function, use the def keyword followed by the function name and parentheses.
# Defining a function that adds two numbers
def add(a, b):
result = a + b
return result
Passing Information to a Function
Passing a Single Argument
Functions can accept one or more arguments, allowing you to provide data to the function.
# Function that displays a message with a name
def greet(name):
print(f"Hello, {name}!")
Positional and Keyword Arguments
Using Positional Arguments
Positional arguments are passed in the order defined by the function.
# Function with positional arguments
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
Using Keyword Arguments
Keyword arguments are passed with the parameter name, allowing for more clarity.
# Function with keyword arguments
def describe_person(name, age):
print(f"Name: {name}, Age: {age}")
Default Values
Using a Default Value
Default values are assigned to parameters, making them optional when calling the function.
# Function with a default value
def greet_user(name="User"):
print(f"Hello, {name}!")
Using None to Make an Argument Optional
You can use None as a default value to make an argument truly optional.
# Function with None to make an argument optional
def describe_pet(pet_name, animal_type=None):
if animal_type:
print(f"I have a {animal_type} named {pet_name}.")
else:
print(f"I have a pet named {pet_name}.")
Return Values
Returning a Single Value
Functions can return values using the return statement.
# Function that returns the square of a number
def square(x):
return x ** 2
Returning a Dictionary
Functions can return dictionaries to provide structured data.
# Function that returns a dictionary
def create_person(name, age):
person = {'name': name, 'age': age}
return person
Returning a Dictionary with Optional Values
You can include optional values in the dictionary returned by a function.
# Function that returns a dictionary with optional values
def create_car(make, model, year=None):
car = {'make': make, 'model': model}
if year:
car['year'] = year
return car
Passing a List to a Function
Passing a List as an Argument
Functions can accept lists as arguments for processing.
# Function that prints items from a list
def print_items(my_list):
for item in my_list:
print(item)
Allowing a Function to Modify a List
A function can modify a list passed as an argument.
# Function that modifies a list
def add_element(my_list, element):
my_list.append(element)
Preventing a Function from Modifying a List
To avoid modifying the original list, you can pass a copy.
# Function that receives a copy of a list
def modify_list(my_list_copy):
my_list_copy.append(42)
Passing an Arbitrary Number of Arguments
Collecting an Arbitrary Number of Arguments
You can use *args to collect an arbitrary number of positional arguments.
# Function with arbitrary positional arguments
def print_args(*args):
for arg in args:
print(arg)
Collecting an Arbitrary Number of Keyword Arguments
You can use **kwargs to collect an arbitrary number of keyword arguments.
# Function with arbitrary keyword arguments
def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
The Best Way to Structure a Function
Well-Structured Functions
Functions should have clear purposes, descriptive names, and appropriate documentation.
# A well-structured function
def calculate_average(numbers):
"""Calculate the average of a list of numbers."""
total = sum(numbers)
count = len(numbers)
return total / count
Modules
Storing a Function in a Module
Functions can be stored in separate Python modules for organization.
# Function stored in a module named 'my_module.py'
# my_module.py:
def greet(name):
print(f"Hello, {name}!")
Importing an Entire Module
You can import an entire module to use its functions.
# Importing an entire module
import my_module
my_module.greet("Alice")
Importing a Specific Function
You can import a specific function from a module.
# Importing a specific function from a module
from my_module import greet
greet("Bob")
Giving a Module an Alias
Modules can be given aliases to simplify their usage.
# Giving a module an alias
import my_module as mm
mm.greet("Carol")
Giving a Function an Alias
Functions can also be given aliases to make code more readable.
# Giving a function an alias
from my_module import greet as say_hello
say_hello("David")
Importing All Functions from a Module
You can import all functions from a module using *.
# Importing all functions from a module
from my_module import *
greet("Eve")
Functions are a fundamental concept in Python, allowing you to encapsulate logic, make code reusable, and create organized and maintainable programs. Understanding how to define, call, and structure functions is crucial for effective programming.
6. CLASSES
What are Classes
Classes are blueprints that define the structure and behavior of objects in Python. They encapsulate data and functions that operate on that data.
Creating and Using a Class
The Dog Class
A class is defined using the class keyword, followed by the class name.
# Defining a Dog class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
Creating an Object from a Class
Objects are instances of a class and are created using the class constructor.
# Creating a Dog object
my_dog = Dog("Buddy", 3)
Accessing Attribute Values
Attributes are accessed using dot notation.
# Accessing attribute values
print(my_dog.name) # Output: Buddy
Calling Methods
Methods are functions defined within a class and can be called on objects.
# Defining a method in the Dog class
def sit(self):
print(f"{self.name} is sitting.")
# Calling a method
my_dog.sit() # Output: Buddy is sitting.
Creating Multiple Objects
Multiple objects can be created from the same class, each with its own set of attributes and behavior.
# Creating multiple Dog objects
dog1 = Dog("Rex", 5)
dog2 = Dog("Molly", 2)
Modifying Attributes
Modifying an Attribute Directly
Attributes can be modified directly.
# Modifying an attribute directly
my_dog.age = 4
Writing a Method to Update an Attribute’s Value
Methods can be used to update attribute values with more control.
# Writing a method to update an attribute's value
def update_age(self, new_age):
self.age = new_age
my_dog.update_age(5)
Writing a Method to Increment an Attribute’s Value
Methods can be used to perform specific actions on attributes, like incrementing.
# Writing a method to increment an attribute's value
def increment_age(self, years):
self.age += years
my_dog.increment_age(2)
Naming Conventions
Class Naming Convention
Class names should use CamelCase convention (each word capitalized).
class CarModel:
# ...
Class Inheritance
The __init__() Method for a Child Class
Child classes can inherit from parent classes and extend them.
# Defining a child class
class Bulldog(Dog):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
Adding New Methods to the Child Class
Child classes can have their own methods in addition to inherited ones.
# Adding a new method to the child class
def guard(self):
print(f"{self.name} is guarding the house.")
Using Child Methods and Parent Methods
Objects of child classes can use methods from both child and parent classes.
# Using child methods and parent methods
my_bulldog = Bulldog("Spike", 4, "Bulldog")
my_bulldog.sit() # Inherited from Dog class
my_bulldog.guard() # From the Bulldog class
Overriding Parent Methods
Child classes can override parent class methods to customize behavior.
# Overriding a parent method
def sit(self):
print(f"{self.name} sits differently.")
my_bulldog.sit() # Output: Spike sits differently.
Instances as Attributes
A Battery Class
Instances of one class can be used as attributes in another class.
# A Battery class
class Battery:
def __init__(self, capacity):
self.capacity = capacity
def describe_battery(self):
print(f"Battery capacity: {self.capacity} kWh")
Using an Instance as an Attribute
Instances of the Battery class can be used as attributes in an ElectricCar class.
# Using an instance as an attribute
class ElectricCar:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.battery = Battery(75) # Using Battery instance
Using the Instance
You can call methods on the instance used as an attribute.
# Using the instance
my_electric_car = ElectricCar("Tesla", "Model 3", 2023)
my_electric_car.battery.describe_battery()
Importing Classes
Storing Classes in a File
Classes can be stored in separate Python files.
# Car.py (class stored in a file)
class Car:
# ...
Importing Individual Classes from a Module
You can import specific classes from a module.
# Importing an individual class from a module
from Car import Car
Importing an Entire Module
You can import an entire module containing classes.
# Importing an entire module
import Car
my_car = Car.Car()
Importing All Classes from a Module
You can import all classes from a module.
# Importing all classes from a module
from Car import *
my_car = Car()
Storing Objects in a List
A Fleet of Rental Cars
Objects of the same class can be stored in a list for easy management.
# Storing objects in a list
fleet = []
fleet.append(Car())
fleet.append(ElectricCar("Tesla", "Model S", 2023))
Classes and objects are fundamental to object-oriented programming in Python. They allow you to model real-world entities and create reusable and organized code. Understanding how to create, inherit from, and use classes is essential for building complex and modular applications.
7. FILES
What are Files
Files are used for storing data on a computer’s file system. They are essential for reading and writing information in Python.
Reading from a File
Reading an Entire File at Once
You can read the entire contents of a file into a string.
# Reading an entire file at once
with open('filename.txt') as file:
contents = file.read()
Reading Line by Line
Reading a file line by line is useful for large files or when processing data incrementally.
# Reading a file line by line
with open('filename.txt') as file:
for line in file:
print(line.rstrip())
Storing the Lines in a List
You can read the lines of a file into a list for easy access.
# Storing the lines in a list
with open('filename.txt') as file:
lines = file.readlines()
Writing to a File
Writing to an Empty File
You can create a new file or overwrite an existing one to write data to it.
# Writing to an empty file
with open('new_file.txt', 'w') as file:
file.write("Hello, world!")
Writing Multiple Lines to an Empty File
Multiple lines can be written to a file using a loop or list.
# Writing multiple lines to an empty file
lines = ['Line 1', 'Line 2', 'Line 3']
with open('new_file.txt', 'w') as file:
for line in lines:
file.write(line + '\n')
Appending to a File
Appending data to an existing file keeps the original content and adds new data.
# Appending to a file
with open('existing_file.txt', 'a') as file:
file.write("This line is appended.")
File Paths
Opening a File from a Subfolder
You can specify a file’s path relative to the current working directory.
# Opening a file from a subfolder
with open('subfolder/filename.txt') as file:
contents = file.read()
Opening a File Using an Absolute Path
An absolute path specifies the file’s location from the root directory.
# Opening a file using an absolute path
file_path = '/home/user/documents/myfile.txt'
with open(file_path) as file:
contents = file.read()
Opening a File on Windows
Windows uses backslashes in file paths, which need to be escaped.
# Opening a file on Windows
file_path = 'C:\\Users\\User\\Documents\\myfile.txt'
with open(file_path) as file:
contents = file.read()
Storing Data with JSON
Using json.dump() to Store Data
The json.dump() function allows you to store data in JSON format.
import json
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as file:
json.dump(data, file)
Using json.load() to Read Data
The json.load() function reads JSON data from a file.
import json
with open('data.json') as file:
loaded_data = json.load(file)
Making Sure the Stored Data Exists
You can check if the JSON file exists before attempting to read it.
import json
import os
if os.path.exists('data.json'):
with open('data.json') as file:
loaded_data = json.load(file)
else:
print("File 'data.json' does not exist.")
Working with files is essential for managing data in Python. You can read and write files, specify file paths, and store data in various formats like JSON to interact with external resources and persist information between program runs.
8. EXCEPTIONS
The try-except Block
Exception handling in Python allows you to gracefully handle errors, preventing your program from crashing when unexpected situations arise. Use try, except, and else blocks to manage exceptions effectively and make your code more robust.
Handling the ZeroDivisionError Exception
Use a try-except block to handle exceptions, like ZeroDivisionError.
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
Handling the FileNotFoundError Exception
Catch exceptions like FileNotFoundError when working with files.
try:
with open('nonexistent.txt') as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
Knowing Which Exception to Handle
Specific Exception Handling
Handle specific exceptions for precise error handling.
try:
# Code that may raise an exception
except SpecificException:
# Handle SpecificException
except AnotherException:
# Handle AnotherException
The else Block
Using an else Block
The else block executes when no exceptions occur in the try block.
try:
result = 10 / 2
except ZeroDivisionError:
print("Division by zero is not allowed.")
else:
print("Result:", result)
Preventing Crashes from User Input
Use else to handle exceptions and prevent crashes from user input.
try:
number = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print(f"Square of {number}: {number**2}")
Failing Silently
Using the pass Statement in an else Block
You can use the pass statement in an else block to do nothing when an exception occurs.
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
else:
pass
Avoid Bare except Blocks
Don’t Use Bare except Blocks
Avoid using bare except blocks as they catch all exceptions, making debugging difficult.
try:
# Code that may raise exceptions
except:
# Avoid bare except blocks
Use Exception Instead
Use except Exception to catch all exceptions explicitly.
try:
# Code that may raise exceptions
except Exception:
# Handle all exceptions
Printing the Exception
You can print the exception message for debugging.
try:
result = 10 / 0
except Exception as e:
print(f"An exception occurred: {e}")
The End; Happy Coding