# Python Cheat Sheet ## Variables and Data Types ### Variables #### Declaring a variable ``` x = 5 ``` #### Reassigning a variable ``` x = 10 ``` ### Data Types #### Integer ``` x = 5 ``` #### Float ``` x = 5.0 ``` #### Boolean ``` x = True ``` #### String ``` x = "Hello, World!" ``` ## Operators #### Arithmetic Operators ``` +, -, *, /, %, ** ``` #### Comparison Operators ``` ==, !=, >, <, >=, <= ``` #### Logical Operators ``` and, or, not ``` ## Control Structures ### Conditional Statements #### If statement ``` if x > 5: print("x is greater than 5") elif x == 5: print("x is equal to 5") else: print("x is less than 5") ``` ### Loops #### For loop ``` for i in range(0, 5): print(i) ``` #### While loop ``` i = 0 while i < 5: print(i) i += 1 ``` ## Functions #### Defining a function ``` def my_function(param1, param2): print(param1 + param2) ``` #### Calling a function ``` my_function(5, 10) ``` ## Lists #### Declaring a list ``` my_list = [1, 2, 3, 4, 5] ``` #### Accessing elements of a list ``` my_list[0] # returns 1 my_list[-1] # returns 5 ``` #### Slicing a list ``` my_list[1:3] # returns [2, 3] ``` #### Appending to a list ``` my_list.append(6) ``` #### Removing from a list ``` my_list.remove(2) ``` ## Dictionaries #### Declaring a dictionary ``` my_dict = {"key1": "value1", "key2": "value2"} ``` #### Accessing elements of a dictionary ``` my_dict["key1"] # returns "value1" ``` #### Adding to a dictionary ``` my_dict["key3"] = "value3" ``` #### Removing from a dictionary ``` del my_dict["key2"] ``` ## Classes #### Declaring a class ``` class MyClass: def __init__(self, param1, param2): self.param1 = param1 self.param2 = param2 def my_method(self): print(self.param1 + self.param2) ``` #### Creating an instance of a class ``` my_instance = MyClass(5, 10) ``` #### Calling a method of a class ``` my_instance.my_method() ``` ## Exceptions #### Catching an exception ``` try: # some code that may raise an exception except ExceptionType: # do something to handle the exception ``` #### Raising an exception ``` raise ExceptionType("Error message") ```