Python Basics
By
17 December 2024 -
2 mins read time
Tags:
Study Guide
Python
Software
Basics
Control Flow
if 1 == 1:
print("1 is equal to 1")
elif 1 == 2:
print("1 is equal to 2")
else:
print("1 is not equal to 1 or 2")
Loops
for i in range(0, 10):
print(i)
i = 0
while i < 10:
print(i)
i += 1
Functions
def add(a, b):
return a + b
List Comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Lambda function
square = lambda x: x**2
print(square(5)) # 25
Map
nums = [1, 2, 3]
squared = list(map(lambda x: x**2, nums)) # [1, 4, 9]
Filter
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2]
Data Structures
List
list = [1, 2, 3, 4, 5]
list.append(6)
list.pop()
list[0]
Bit Strings
bit_str = "1011"
hex_val = hex(int(bit_str, 2))[2:]
Tuple
tuple = (1, 2)
x, y = tuple
Dictionary
dictionary = {"key": "value"}
dictionary["new_key"] = "new_value"
dictionary.pop("key")
dictionary["key"]
Set (unique elements)
set = {1, 2, 3, 4, 5}
set.add(6)
set.remove(1)
Algorithms
Efficient Sorting
list = [1, 2, 3, 4, 5]
sorted_list = sorted(list)
list.sorted()
Classes
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def drive(self):
return f"{self.brand} {self.model} is driving."
# Create object
my_car = Car("Tesla", "Model S")
print(my_car.drive()) # Tesla Model S is driving.
Files
Read file
with open("file.txt", "r") as file:
content = file.read()
Write file
with open("file.txt", "w") as file:
file.write("Hello, File!")
Exceptions
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Cannot divide by zero:", e)
finally:
print("Cleanup")
# Single-line input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Multiple inputs in one line
x, y = map(int, input("Enter two numbers: ").split())
print(f"x: {x}, y: {y}")
# Multiple lines of input
lines = []
while True:
line = input("Enter a line (or 'exit' to stop): ")
if line == "exit":
break
lines.append(line)
print(lines)
Standard Ouput
# Print with formatting
name, age = "Alice", 30
print(f"{name} is {age} years old.") # Using f-strings
# Print without newline
print("Hello", end=" ")
print("World") # Output: Hello World
# Print to file
with open("output.txt", "w") as file:
print("Writing to file!", file=file)
Crib Sheet