Python Cheatsheet - main.py - VSCode
Twitter Facebook LinkedIn
Copied!
# 1. Basics: basics.py
# 1. Basics: Variables, Data Types, Operators, Control Flow

# Variables and Data Types
name = "Alice"               # String
age = 30                      # Integer
height = 1.75                 # Float
is_student = True           # Boolean
fruits = ["apple", "banana", "cherry"] # List
coordinates = (10, 20)          # Tuple
person = {"name": "Bob", "age": 25} # Dictionary
unique_numbers = {1, 2, 3}     # Set

# Basic Output
print("Hello, Python!")
print(f"Name: {name}, Age: {age}")

# Operators
x = 10
y = 3
print(f"Addition: {x + y}")
print(f"Division: {x / y}")    # Float division
print(f"Floor Division: {x // y}") # Integer division
print(f"Modulus: {x % y}")
print(f"Exponentiation: {x ** y}")

# Conditional Statements (if/elif/else)
if age < 18:
    print("Minor")
elif age >= 18 and age < 65:
    print("Adult")
else:
    print("Senior")

# Loops (for, while)
# For loop with range
for i in range(5): # 0, 1, 2, 3, 4
    print(f"Count: {i}")

# For loop through a list
for fruit in fruits:
    print(f"Fruit: {fruit}")

# While loop
count = 0
while count < 3:
    print(f"While count: {count}")
    count += 1

# Break and Continue
for i in range(10):
    if i == 3:
        continue  # Skip to next iteration
    if i == 7:
        break     # Exit loop
    print(f"Loop item: {i}")
# 2. Data Structures: data_structures.py
# 2. Data Structures in Detail

# Lists (mutable, ordered, allows duplicates)
my_list = [1, 2, 3, 2]
print(f"List: {my_list}")
my_list.append(4)
print(f"Appended: {my_list}")
print(f"First element: {my_list[0]}")
print(f"Slice: {my_list[1:3]}")

# Tuples (immutable, ordered, allows duplicates)
my_tuple = (1, "hello", True)
print(f"Tuple: {my_tuple}")
print(f"Second element: {my_tuple[1]}")
# my_tuple[0] = 5  # This would raise an error

# Dictionaries (mutable, unordered before Python 3.7, key-value pairs)
my_dict = {"name": "Alice", "age": 30}
print(f"Dictionary: {my_dict}")
print(f"Name: {my_dict['name']}")
my_dict["city"] = "New York"
print(f"Updated Dictionary: {my_dict}")

# Sets (mutable, unordered, unique elements)
my_set = {1, 2, 3, 2} # Duplicates are ignored
print(f"Set: {my_set}")
my_set.add(4)
print(f"Added to Set: {my_set}")
# 3. Functions & Classes: functions_classes.py
# 3. Functions and Classes

# Functions
def greet(name):
    """Greets the given name."""
    return f"Hello, {name}!"

print(greet("World"))

# Function with default argument
def power(base, exp=2):
    return base ** exp

print(f"2 squared: {power(2)}")
print(f"2 cubed: {power(2, 3)}")

# Lambda functions (anonymous functions)
multiply = lambda a, b: a * b
print(f"Lambda multiply: {multiply(5, 4)}")

# Classes (Object-Oriented Programming)
class Dog:
    """A simple Dog class."""
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return f"{self.name} says Woof!"

my_dog = Dog("Buddy", "Golden Retriever")
print(f"Dog name: {my_dog.name}")
print(my_dog.bark())
# 4. Error Handling: error_handling.py
# 4. Error Handling (try-except-finally)

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
finally:
    print("Execution finished (regardless of error).")
# 5. File I/O: file_io.py
# 5. File I/O (Input/Output)

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello from Python!\n")
    file.write("This is a new line.")
print("Content written to example.txt")

# Reading from a file
try:
    with open("example.txt", "r") as file:
        content = file.read()
        print("\nContent of example.txt:")
        print(content)
except FileNotFoundError:
    print("Error: example.txt not found.")

# 6. Imports
import math
print(f"\nPi: {math.pi}")
print(f"Square root of 16: {math.sqrt(16)}")

from datetime import datetime
now = datetime.now()
print(f"Current datetime: {now}")
Settings Problems: 0
Python 3.9.7 UTF-8 LF Spaces: 4 Go Live