Python: Learning Python
A comprehensive Python guide
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Python cloud solution that provides a host of benefits, including:
- Deploy your application in seconds with a simple
git push.- Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
- Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
- Get optimal performance and robust security thanks to a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Python cloud hosting solution!
This guide provides an overview of essential Python concepts and syntax. It serves as a quick refresher for experienced developers and a friendly introduction for beginners. Covering everything from basic data types to advanced features, this cheatsheet includes topics such as control flow, functions, classes, objects, and common modules. Keep it handy as a quick reference while working on Python projects. Keep in mind that Python has a vast ecosystem of libraries and frameworks, so exploring additional resources and documentation will help you dive deeper into specialized topics.
Happy coding!
Introduction to Python
Python is a versatile, high-level programming language created by Guido van Rossum and first released in 1991. It is popular for its readability and simplicity, making it an excellent choice for both beginners and experienced developers. Python is widely used in web development, data analysis, artificial intelligence, machine learning, and automation, among many other areas.
Some common use cases for Python include building web applications using frameworks like Django or Flask, analyzing and visualizing data with libraries such as pandas and matplotlib, and developing machine learning models with tools like TensorFlow and scikit-learn.
Python's extensive standard library and thriving ecosystem of third-party packages make it a powerful and flexible language for tackling a broad range of programming tasks.
Basic data types
Python's basic data types include integers (whole numbers), floating-point numbers (numbers with decimals), booleans (true/false values), and strings (sequences of characters):
int: Integer, e.g.42float: Floating-point number, e.g.3.14bool: Boolean, e.g.TrueorFalsestr: String, e.g. "hello"
Example:
integer = 42
floating_point = 3.14
boolean = True
string = "Hello, World!"
Common data structures
Python provides several data structures to help you efficiently organize, store, and manipulate data. The most commonly used ones are lists, tuples, dictionaries, and sets. Lists and tuples maintain an ordered sequence of elements, dictionaries store key-value pairs, and sets store unique elements. Each structure comes with a range of methods tailored to specific use cases.
- List:
my_list = [1, 2, 3, 4] - Tuple:
my_tuple = (1, 2, 3, 4) - Dictionary:
my_dictionary = {'key1': 'value1', 'key2': 'value2'} - Set:
my_set = {1, 2, 3, 4}
Lists
Lists are mutable, ordered collections of elements. They allow duplicates and can contain elements of various data types, including other lists, tuples, dictionaries, or sets. You can easily add, update, and remove elements. Lists are defined within square brackets [] with elements separated by commas.
Key points about lists:
- Mutable and ordered
- Allow duplicate elements
- Maintain the order in which elements are added
- Support multiple data types
- Provide operations for adding, updating, and deleting elements
Lists are commonly used when you need a dynamic and resizable collection of items.
Examples:
# Create a list
my_list = [1, 2, 3, 4, 5]
# Access elements
print(my_list[0]) # Output: 1
print(my_list[-1]) # Output: 5
# Add elements
my_list.append(6)
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
# Update elements
my_list[0] = 0
print(my_list) # Output: [0, 2, 3, 4, 5, 6]
# Delete elements
del my_list[0]
print(my_list) # Output: [2, 3, 4, 5, 6]
Dictionaries
Dictionaries are mutable, unordered collections of key-value pairs. Each key must be unique, and you can use these keys to access their associated values. Like lists, dictionaries can store elements of various data types, including nested collections. They are defined within curly braces {} with key-value pairs separated by commas, and keys and values separated by a colon.
Key points about dictionaries:
- Mutable and unordered collection
- Consist of key-value pairs with unique keys
- Access values using keys
- Store various data types
Dictionaries are ideal for tasks where you need to perform lookups, such as configuration settings or frequency counts.
Examples:
# Create a dictionary
my_dictionary = {'a': 1, 'b': 2, 'c': 3}
# Access elements
print(my_dictionary['a']) # Output: 1
# Add elements
my_dictionary['d'] = 4
print(my_dictionary) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Update elements
my_dictionary['a'] = 0
print(my_dictionary) # Output: {'a': 0, 'b': 2, 'c': 3, 'd': 4}
# Delete elements
del my_dictionary['a']
print(my_dictionary) # Output: {'b': 2, 'c': 3, 'd': 4}
Tuples
Tuples are immutable, ordered collections of elements. They work much like lists, except that once a tuple is created, its elements cannot be changed, added, or removed. Tuples are defined using parentheses () with elements separated by commas.
Key points about tuples:
- Immutable and ordered collection
- Support multiple data types
- Fixed-size structure
Tuples are useful when you need an unchangeable collection, or when you want to use the collection as a dictionary key.
Example:
# Create a tuple
my_tuple = (1, 2, 3, 4, 5)
# Access elements
print(my_tuple[0]) # Output: 1
print(my_tuple[-1]) # Output: 5
# Note: Tuples are immutable
Sets
Sets are mutable, unordered collections that store unique elements. They automatically remove duplicates and do not maintain an order. Sets can hold elements of various data types, excluding mutable types like lists and dictionaries. They can be defined using curly braces {} or the set() constructor.
Key points about sets:
- Mutable and unordered
- Store only unique elements, automatically removing duplicates
- Exclude mutable types (like lists and dictionaries)
Sets are ideal for membership testing, deduplication, and performing set operations like union, intersection, and difference.
# Create a set
my_set = {1, 2, 3, 4, 5}
# Check membership
print(1 in my_set) # Output: True
# Add an element
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
# Update by removing one element and adding another
my_set.remove(1)
my_set.add(0)
print(my_set) # Output: {0, 2, 3, 4, 5, 6}
# Delete an element
my_set.remove(0)
print(my_set) # Output: {2, 3, 4, 5, 6}
Conditional statements: if, elif, else
Conditional statements allow you to execute code based on whether a condition is true or false.
if condition1:
# do something
elif condition2:
# do something else
else:
# do another thing
Example:
x = 42
if x > 50:
print("x is greater than 50")
elif x < 50:
print("x is less than 50")
else:
print("x is equal to 50")
for loop
for loops iterate over a sequence, such as a list or a range, executing a block of code for each element.
Example:
for i in range(5):
print(i)
while loop
while loops execute a block of code as long as a specified condition is true.
Example:
i = 0
while i < 5:
print(i)
i += 1
Functions
Functions encapsulate code into reusable blocks that can accept inputs (arguments) and return outputs. They are defined using the def keyword and can be called by their name.
def function_name(argument1, argument2=default_value):
# do something
return result
Example:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Output: 7
Lambda functions
Lambda functions, also known as anonymous functions, are concise single-expression functions created using the lambda keyword. They are commonly used for short operations, often as arguments to functions like map(), filter(), or sorted().
lambda arguments: expression
Example:
add = lambda a, b: a + b
result = add(3, 4)
print(result) # Output: 7
List comprehensions
List comprehensions let you create lists in a single, readable line by combining an expression with a loop and an optional condition. They are excellent for transforming or filtering data.
new_list = [expression for item in iterable if condition]
Example:
squares = [x * x for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
Exception handling
Exception handling enables your program to manage runtime errors gracefully. Python provides the try, except, and finally blocks to catch and handle exceptions, ensuring that your program continues or exits smoothly.
try:
# code that may raise an exception
except ExceptionType as error_variable:
# handle the exception
finally:
# code to be executed regardless of whether an exception occurred
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Classes and objects
Classes define blueprints for creating objects in object-oriented programming (OOP). Objects are instances of a class with attributes (data) and methods (functions) that perform specific tasks. OOP promotes structured, reusable, and maintainable code.
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
def method_name(self, argument1):
# do something
return result
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
# Create an instance of Dog
dog1 = Dog("Buddy", 3)
dog1.bark() # Output: Woof!
Importing modules
Modules are separate files containing Python code such as functions, classes, or variables. Importing modules enables you to extend your program's functionality by using external libraries and frameworks.
import module_name
from module_name import specific_function_or_class
Example:
import math
print(math.sqrt(16)) # Output: 4.0
File I/O
File input/output (I/O) covers reading from and writing to files in Python. This is essential when working with data storage and retrieval.
Reading a file
with open('filename.txt', 'r') as file:
content = file.read()
Writing to a file
with open('filename.txt', 'w') as file:
file.write('content to write to the file')
Context managers
Context managers help manage resources, such as files or network connections, ensuring that they are properly acquired and released. Using a context manager ensures that your code is cleaner and more fault-tolerant.
with resource as alias:
# use resource as alias
Example:
with open('file.txt', 'r') as file:
content = file.read()
print(content) # Output: Hello, World!
Decorators
Decorators allow you to extend or modify the behaviour of functions or classes without changing their source code. They wrap another function and add some functionality before or after the wrapped function is executed.
def decorator_function(func):
def wrapper(*args, **kwargs):
# do something before calling the function
result = func(*args, **kwargs)
# do something after calling the function
return result
return wrapper
@decorator_function
def my_function():
# do something
Examples:
def greet_decorator(func):
def wrapper(name):
return "Hello, " + func(name) + "!"
return wrapper
@greet_decorator
def get_name(name):
return name
print(get_name("John")) # Output: Hello, John!
Itertools module
The itertools module provides functions for creating and working with iterators. It includes infinite iterators (such as count, cycle, and repeat), finite iterators (such as accumulate, chain, compress), and combinatorial iterators (such as product, permutations, and combinations).
Example:
import itertools
for i in itertools.count(5, 5):
if i > 20:
break
print(i) # Output: 5, 10, 15, 20
Collections module
The collections module offers specialized container data types that can help improve your programs.
from collections import namedtuple, defaultdict, Counter, deque
Examples:
from collections import namedtuple, deque, Counter, OrderedDict, defaultdict
# namedtuple
Person = namedtuple('Person', 'name age')
person1 = Person("Alice", 30)
print(person1.name, person1.age) # Output: Alice 30
# deque
dq = deque([1, 2, 3, 4, 5])
dq.append(6)
dq.appendleft(0)
print(dq) # Output: deque([0, 1, 2, 3, 4, 5, 6])
# Counter
count = Counter("hello world")
print(count) # Output: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od) # Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# defaultdict
dd = defaultdict(int)
dd['a'] += 1
dd['b'] += 2
print(dd) # Output: defaultdict(<class 'int'>, {'a': 1, 'b': 2})
Regular expressions
Regular expressions enable powerful text processing and manipulation. The re module provides functions such as match, search, findall, finditer, split, and sub.
Example:
import re
pattern = r'\d+'
result = re.findall(pattern, "There are 10 cats and 5 dogs.")
print(result) # Output: ['10', '5']
Dates and times
Working with dates and times is a common requirement, especially for data analysis or scheduling tasks. The datetime module provides classes and functions to work with dates, times, and intervals.
import datetime
# datetime, date, time, timedelta, timezone
Examples:
from datetime import datetime, timedelta
# Current date and time
current_time = datetime.now()
print("Current date and time:", current_time)
# Custom date and time
custom_date = datetime(2022, 12, 31, 23, 59, 59)
print("Custom date and time:", custom_date)
# Convert string to datetime
date_str = "2023-01-01 00:00:00"
date_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("String to datetime:", date_obj)
# Convert datetime to string
date_str2 = date_obj.strftime("%Y-%m-%d %H:%M:%S")
print("Datetime to string:", date_str2)
# Date and time arithmetic
one_day = timedelta(days=1)
yesterday = current_time - one_day
tomorrow = current_time + one_day
print("Yesterday:", yesterday)
print("Tomorrow:", tomorrow)
List slicing
List slicing allows you to extract a portion of a list or another sequence type by specifying start, end, and optional step values. This feature is very useful for extracting sub-sequences.
my_list[start:end:step]
Example:
my_list = [0, 1, 2, 3, 4, 5]
sub_list = my_list[1:4]
print(sub_list) # Output: [1, 2, 3]
String formatting
String formatting is the process of combining static text with dynamic values. Python offers several formatting methods, including %-formatting, the str.format() method, and f-strings (Python 3.6+), which allow you to easily generate formatted strings.
%-formatting
print("Hello, %s" % name)
str.format
print("Hello, {}".format(name))
f-strings (Python 3.6+)
print(f"Hello, {name}")
Example:
name = "John"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # Output: My name is John and I am 30 years old.
Command-line arguments
Command-line arguments allow you to pass input values to a Python script when executing it from the command line. The sys.argv list provides access to these arguments, making it easy to parse and use them within your script.
import sys
arguments = sys.argv
Example:
# Save this code in a file named "cmd_args.py"
# Run with: python cmd_args.py Alice
# Expected output: Hello, Alice!
import sys
if len(sys.argv) > 1:
print(f"Hello, {sys.argv[1]}!")
else:
print("No arguments provided.")