cheetsheetz/python.md

356 lines
6.0 KiB
Markdown

# Python Cheat Sheet
## Table of Contents
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)
14. [SQLite3 Database Connection](#sqlite3-database-connection)
14.1 [Connecting to a Database](#connecting-to-a-database)
14.2 [Creating a Table](#creating-a-table)
14.3 [Inserting Data](#inserting-data)
14.4 [Querying Data](#querying-data)
14.5 [Updating Data](#updating-data)
14.6 [Deleting Data](#deleting-data)
14.7 [Closing the Connection](#closing-the-connection)
15. [JSON Data Connection](#json-data-connection)
15.1 [Loading JSON Data](#loading-json-data)
15.2 [Writing JSON Data](#writing-json-data)
## Variables
### Declaration and Assignment
```python
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
```python
+, -, *, /, %, ** (exponentiation), //
```
### Comparison Operators
```python
==, !=, <, >, <=, >=
```
### Logical Operators
```python
and, or, not
```
### Assignment Operators
```python
=, +=, -=, *=, /=, %=
```
## Control Structures
### If Statement
```python
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
```python
for i in range(5):
# code to be executed in each iteration
```
### While Loop
```python
while condition:
# code to be executed as long as the condition is true
```
## Functions
### Function Declaration
```python
def function_name(param1, param2):
# code to be executed
return result # optional
```
### Function Call
```python
result = function_name(arg1, arg2)
```
## Lists
### List Declaration
```python
my_list = [1, 2, 3, "hello", True]
```
### List Operations
```python
my_list.append(4) # Add an element to the end
my_list.remove("hello") # Remove a specific element
```
## Strings
### String Concatenation
```python
string1 = "Hello"
string2 = "World"
concatenated = string1 + " " + string2
```
### String Methods
```python
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
```python
my_dict = {"key1": "value1", "key2": "value2"}
```
### Dictionary Operations
```python
my_dict["new_key"] = "new_value" # Add a new key-value pair
del my_dict["key1"] # Remove a key-value pair
```
## Tuples
### Tuple Declaration
```python
my_tuple = (1, 2, 3, "hello", True)
```
### Immutable Nature
```python
# Tuple elements cannot be changed once set
my_tuple[0] = 4 # This will result in an error
```
## Sets
### Set Declaration
```python
my_set = {1, 2, 3, 3, 4}
```
### Set Operations
```python
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
```python
with open("filename.txt", "r") as file:
file_content = file.read()
```
### Writing to a File
```python
with open("filename.txt", "w") as file:
file.write("Hello, World!")
```
## Exception Handling
### Try-Except Block
```python
try:
# code that may raise an exception
except Exception as e:
# 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!
```
## Working with Data
```python
# Import necessary modules
import sqlite3
import json
```
## SQLite3 Database Connection
### Connecting to a Database
```python
# Connect to a database (creates a new database if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
```
### Creating a Table
```python
# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
email TEXT NOT NULL
)
''')
# Commit the changes
conn.commit()
```
### Inserting Data
```python
# Insert data into the table
cursor.execute('''
INSERT INTO users (username, email)
VALUES ('john_doe', 'john@example.com')
''')
# Commit the changes
conn.commit()
```
### Querying Data
```python
# Fetch all rows from the table
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
# Print the results
for row in rows:
print(row)
```
### Updating Data
```python
# Update data in the table
cursor.execute('''
UPDATE users
SET email = 'john.doe@example.com'
WHERE username = 'john_doe'
''')
# Commit the changes
conn.commit()
```
### Deleting Data
```python
# Delete data from the table
cursor.execute('''
DELETE FROM users
WHERE username = 'john_doe'
''')
# Commit the changes
conn.commit()
```
### Closing the Connection
```python
# Close the cursor and connection when done
cursor.close()
conn.close()
```
## JSON Data Connection
### Loading JSON Data
```python
# Load JSON data from a file
with open('data.json', 'r') as json_file:
data = json.load(json_file)
print(data)
```
### Writing JSON Data
```python
# Write Python data to a JSON file
data_to_write = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('output.json', 'w') as json_file:
json.dump(data_to_write, json_file)
```