cheetsheetz/python.md

3.6 KiB

Python Cheat Sheet

Table of Contents

  1. Variables
  2. Data Types
  3. Operators
  4. Control Structures
  5. Functions
  6. Lists
  7. Strings
  8. Dictionaries
  9. Tuples
  10. Sets
  11. File Handling
  12. Exception Handling
  13. Classes and Objects

Variables

Declaration and Assignment

variable_name = value

Variable Types

  • String: string_variable = "Hello"
  • Integer: int_variable = 42
  • Float: float_variable = 3.14
  • Boolean: bool_variable = True

Data Types

Basic Types

  • String
  • Integer
  • Float
  • Boolean

Compound Types

  • List
  • Tuple
  • Set
  • Dictionary

Operators

Arithmetic Operators

+, -, *, /, %, ** (exponentiation), //

Comparison Operators

==, !=, <, >, <=, >=

Logical Operators

and, or, not

Assignment Operators

=, +=, -=, *=, /=, %=

Control Structures

If Statement

if condition:
    # code to be executed if the condition is true
elif another_condition:
    # code to be executed if the previous condition was false and this one is true
else:
    # code to be executed if all conditions are false

For Loop

for i in range(5):
    # code to be executed in each iteration

While Loop

while condition:
    # code to be executed as long as the condition is true

Functions

Function Declaration

def function_name(param1, param2):
    # code to be executed
    return result  # optional

Function Call

result = function_name(arg1, arg2)

Lists

List Declaration

my_list = [1, 2, 3, "hello", True]

List Operations

my_list.append(4)  # Add an element to the end
my_list.remove("hello")  # Remove a specific element

Strings

String Concatenation

string1 = "Hello"
string2 = "World"
concatenated = string1 + " " + string2

String Methods

len(my_string)  # Length of the string
my_string.find("find")  # Index of the first occurrence of "find"
my_string.split(",")  # Split the string into a list

Dictionaries

Dictionary Declaration

my_dict = {"key1": "value1", "key2": "value2"}

Dictionary Operations

my_dict["new_key"] = "new_value"  # Add a new key-value pair
del my_dict["key1"]  # Remove a key-value pair

Tuples

Tuple Declaration

my_tuple = (1, 2, 3, "hello", True)

Immutable Nature

# Tuple elements cannot be changed once set
my_tuple[0] = 4  # This will result in an error

Sets

Set Declaration

my_set = {1, 2, 3, 3, 4}

Set Operations

my_set.add(5)  # Add an element to the set
my_set.remove(3)  # Remove an element from the set

File Handling

Reading from a File

with open("filename.txt", "r") as file:
    file_content = file.read()

Writing to a File

with open("filename.txt", "w") as file:
    file.write("Hello, World!")

Exception Handling

Try-Except Block

try:
    # code that may raise an exception
except Exception as e:
    # handle the exception
    print("Error:", e)

Classes and Objects

Class Declaration

class MyClass:
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print(f"Hello, {self.name}!")

Object Instantiation

obj = MyClass("John")
obj.say_hello()  # Outputs: Hello, John!