Python Syntax Cheat Sheet

Here’s a cheat sheet for Python syntax:

Variables and Data Types

# Variable assignment
x = 10

# Data types
integer_var = 42
float_var = 3.14
string_var = "Hello, Python!"
boolean_var = True

Control Flow

# Conditional statements
if condition:
    # Code block

# Looping
for item in iterable:
    # Code block

while condition:
    # Code block

Functions

# Function definition
def my_function(arg1, arg2):
    # Code block
    return result

# Function call
result = my_function(value1, value2)

Lists

# List creation
my_list = [1, 2, 3, 4]

# Accessing elements
element = my_list[0]

# List methods
my_list.append(5)
my_list.pop()

Dictionaries

# Dictionary creation
my_dict = {"key1": "value1", "key2": "value2"}

# Accessing values
value = my_dict["key1"]

# Dictionary methods
my_dict["key3"] = "value3"
del my_dict["key2"]

Strings

# String creation
my_string = "Python"

# String methods
length = len(my_string)
substring = my_string[1:4]

Exception Handling

# Try-except block
try:
    # Code block
except SomeException as e:
    # Exception handling code

File Handling

# Reading from a file
with open("filename.txt", "r") as file:
    content = file.read()

# Writing to a file
with open("new_file.txt", "w") as file:
    file.write("Hello, Python!")

Classes and Objects

# Class definition
class MyClass:
    def __init__(self, attribute):
        self.attribute = attribute

    def my_method(self):
        # Code block

# Object instantiation
obj = MyClass("value")

Modules and Packages

# Importing modules
import math
from my_module import my_function

# Creating packages
# (Create a directory with an __init__.py file)

List Comprehensions

# List comprehension
squares = [x**2 for x in range(10)]

Lambda Functions

# Lambda function
square = lambda x: x**2

Virtual Environments

# Creating a virtual environment
python -m venv myenv

# Activating the virtual environment
source myenv/bin/activate  # On Unix/Linux
myenv\Scripts\activate  # On Windows

# Deactivating the virtual environment
deactivate

This cheat sheet covers basic Python syntax. Remember to refer to the Python documentation for more detailed information and advanced topics.