Files
the_information_nexus/dev/programming/Python Cheat Sheet(1).md
2023-11-11 11:23:51 -07:00

152 lines
3.9 KiB
Markdown

# Python Cheat Sheet
## 1. Variables, Data Types, and Basic Operations
Python has several fundamental data types, including integers (int), floating point numbers (float), and strings (str). Python is a dynamically typed language, which means you don't need to declare the data type of a variable when you define it.
```python
a = 10 # Integer
b = 3.14 # Float
c = "Hello, World!" # String
```
Operators allow you to perform operations on variables. Arithmetic, comparison, assignment, logical, and identity operators are some of the main types in Python.
```python
a = 10
b = 20
sum = a + b # Addition
difference = a - b # Subtraction
#... remaining code ...
```
## 2. Control Structures (Conditionals and Loops)
Python uses `if`, `elif`, and `else` for conditional statements. Loops in Python can be programmed using a `for` or `while` loop.
```python
# If-else statement
if a > b:
print("a is greater than b")
else:
print("a is not greater than b")
# For loop
for i in range(5):
print(i)
```
## 3. Functions
Functions in Python are defined using the `def` keyword. They are used to encapsulate a piece of code that performs a specific task.
```python
def greet(name):
print("Hello, " + name)
greet("Alice")
```
## 4. Lists, Tuples, Sets, and Dictionaries
Python has several types of compound data structures that can hold multiple values, including lists, tuples, sets, and dictionaries.
```python
# Lists
my_list = [1, 2, 3, 4, 5]
# Dictionaries
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
```
## 5. File Handling
Python has built-in functions for reading and writing files. `open()` function is used to open a file. It returns a file object and is most commonly used with two arguments: `open(filename, mode)`.
```python
# Reading a file
file = open('file.txt', 'r')
content = file.read()
file.close()
# Writing to a file
file = open('file.txt', 'w')
file.write("Hello, World!")
file.close()
```
## 6. Exception Handling
Python uses `try` and `except` blocks to catch and handle exceptions. Python executes code following the `try` statement as a "normal" part of the program. The code that follows the `except` statement is the program's response to any exceptions in the preceding try clause.
```python
try:
# Code that may raise an exception
x = 1 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
```
## 7. Classes and Objects
Python is an object-oriented programming language. You define classes to create your own types.
```python
class MyClass:
x = 5
p1 = MyClass() # Create an object of MyClass
print(p1.x) # Access the properties of MyClass using the object
```
## 8. Modules and Packages
Modules in Python are simply Python files with a .py extension, which implement a set of functions. A package is a way of organizing related modules into a single directory hierarchy.
```python
# Importing a module
import math
print(math.sqrt(16)) # Use a function from the math module
# Importing
ChatGPT
a package
import os.path
print(os.path.join('/a', 'b', 'c')) # Use a function from the os.path package
```
## 9. Working with JSON
Python has a built-in package called `json`, which can be used to work with JSON data.
```python
import json
# Some JSON:
x = '{"name": "John", "age": 30, "city": "New York"}'
# Parse x:
y = json.loads(x)
# The result is a Python dictionary:
print(y["age"])
```
## 10. Making HTTP requests
The `requests` library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services and consuming data in your application.
```python
import requests
response = requests.get('https://www.example.com')
# Print the status code
print(response.status_code)
# Print the content
print(response.text)
```
These are the basics to get you started with Python! Each of these topics has more depth to explore as you become more comfortable with the language.