Reworked Python sheet for new format.

This commit is contained in:
CSnap 2023-11-19 04:37:21 +00:00
parent bec65af4a2
commit b5790400c5
1 changed files with 153 additions and 115 deletions

268
python.md
View File

@ -1,180 +1,218 @@
# Python Cheat Sheet # Python Cheat Sheet
## Variables and Data Types ## Table of Contents
### Variables 1. [Variables](#variables)
2. [Data Types](#data-types)
3. [Operators](#operators)
4. [Control Structures](#control-structures)
5. [Functions](#functions)
6. [Lists](#lists)
7. [Strings](#strings)
8. [Dictionaries](#dictionaries)
9. [Tuples](#tuples)
10. [Sets](#sets)
11. [File Handling](#file-handling)
12. [Exception Handling](#exception-handling)
13. [Classes and Objects](#classes-and-objects)
#### Declaring a variable ## Variables
```
x = 5
```
#### Reassigning a variable
```
x = 10
```
### Data Types
#### Integer ### Declaration and Assignment
``` ```python
x = 5 variable_name = value
```
#### Float
```
x = 5.0
``` ```
#### Boolean ### Variable Types
``` - String: `string_variable = "Hello"`
x = True - Integer: `int_variable = 42`
``` - Float: `float_variable = 3.14`
- Boolean: `bool_variable = True`
#### String ## Data Types
```
x = "Hello, World!" ### Basic Types
``` - String
- Integer
- Float
- Boolean
### Compound Types
- List
- Tuple
- Set
- Dictionary
## Operators ## Operators
#### Arithmetic Operators ### Arithmetic Operators
``` ```python
+, -, *, /, %, ** +, -, *, /, %, ** (exponentiation), //
``` ```
#### Comparison Operators ### Comparison Operators
``` ```python
==, !=, >, <, >=, <= ==, !=, <, >, <=, >=
``` ```
#### Logical Operators ### Logical Operators
``` ```python
and, or, not and, or, not
``` ```
### Assignment Operators
```python
=, +=, -=, *=, /=, %=
```
## Control Structures ## Control Structures
### Conditional Statements ### If Statement
```python
#### If statement if condition:
``` # code to be executed if the condition is true
if x > 5: elif another_condition:
print("x is greater than 5") # code to be executed if the previous condition was false and this one is true
elif x == 5:
print("x is equal to 5")
else: else:
print("x is less than 5") # code to be executed if all conditions are false
```
### Loops
#### For loop
```
for i in range(0, 5):
print(i)
``` ```
#### While loop ### For Loop
```python
for i in range(5):
# code to be executed in each iteration
``` ```
i = 0
while i < 5: ### While Loop
print(i) ```python
i += 1 while condition:
# code to be executed as long as the condition is true
``` ```
## Functions ## Functions
#### Defining a function ### Function Declaration
```python
def function_name(param1, param2):
# code to be executed
return result # optional
``` ```
def my_function(param1, param2):
print(param1 + param2) ### Function Call
``` ```python
#### Calling a function result = function_name(arg1, arg2)
```
my_function(5, 10)
``` ```
## Lists ## Lists
#### Declaring a list ### List Declaration
``` ```python
my_list = [1, 2, 3, 4, 5] my_list = [1, 2, 3, "hello", True]
```
#### Accessing elements of a list
```
my_list[0] # returns 1
my_list[-1] # returns 5
``` ```
#### Slicing a list ### List Operations
``` ```python
my_list[1:3] # returns [2, 3] my_list.append(4) # Add an element to the end
my_list.remove("hello") # Remove a specific element
``` ```
#### Appending to a list ## Strings
```
my_list.append(6) ### String Concatenation
```python
string1 = "Hello"
string2 = "World"
concatenated = string1 + " " + string2
``` ```
#### Removing from a list ### String Methods
``` ```python
my_list.remove(2) 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 ## Dictionaries
#### Declaring a dictionary ### Dictionary Declaration
``` ```python
my_dict = {"key1": "value1", "key2": "value2"} my_dict = {"key1": "value1", "key2": "value2"}
``` ```
#### Accessing elements of a dictionary ### Dictionary Operations
``` ```python
my_dict["key1"] # returns "value1" my_dict["new_key"] = "new_value" # Add a new key-value pair
del my_dict["key1"] # Remove a key-value pair
``` ```
#### Adding to a dictionary ## Tuples
```
my_dict["key3"] = "value3" ### Tuple Declaration
```python
my_tuple = (1, 2, 3, "hello", True)
``` ```
#### Removing from a dictionary ### Immutable Nature
``` ```python
del my_dict["key2"] # Tuple elements cannot be changed once set
my_tuple[0] = 4 # This will result in an error
``` ```
## Classes ## Sets
#### Declaring a class ### Set Declaration
``` ```python
class MyClass: my_set = {1, 2, 3, 3, 4}
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 ### Set Operations
``` ```python
my_instance = MyClass(5, 10) my_set.add(5) # Add an element to the set
my_set.remove(3) # Remove an element from the set
``` ```
#### Calling a method of a class ## File Handling
```
my_instance.my_method() ### Reading from a File
```python
with open("filename.txt", "r") as file:
file_content = file.read()
``` ```
## Exceptions ### Writing to a File
```python
#### Catching an exception with open("filename.txt", "w") as file:
file.write("Hello, World!")
``` ```
## Exception Handling
### Try-Except Block
```python
try: try:
# some code that may raise an exception # code that may raise an exception
except ExceptionType: except Exception as e:
# do something to handle the exception # handle the exception
print("Error:", e)
```
## Classes and Objects
### Class Declaration
```python
class MyClass:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, {self.name}!")
```
### Object Instantiation
```python
obj = MyClass("John")
obj.say_hello() # Outputs: Hello, John!
``` ```
#### Raising an exception
```
raise ExceptionType("Error message")
``` ```