scripting:python
Table of Contents
Python Cheatsheet
Basic Syntax
- Variables: Variables do not need explicit declaration.
```python
x = 5 name = "John" ```
- Comments:
```python
# This is a single-line comment
""" This is a multi-line comment """ ```
Data Types
- Common Types:
- int: `x = 10`
- float: `y = 3.14`
- str: `text = “Hello”`
- list: `lst = [1, 2, 3]`
- tuple: `tup = (1, 2, 3)`
- dict: `d = {“key”: “value”}`
- bool: `flag = True`
Control Flow
- If-else statement:
```python
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is 5")
else:
print("x is less than 5")
```
- Loops:
- For loop:
```python
for i in range(5):
print(i)
```
- While loop:
```python
count = 0
while count < 5:
print(count)
count += 1
```
Functions
- Defining a function:
```python
def greet(name):
return f"Hello, {name}"
```
- Lambda Functions:
```python
add = lambda x, y: x + y print(add(2, 3)) ```
Data Structures
- List methods:
```python
lst = [1, 2, 3] lst.append(4) lst.remove(2) print(lst) ```
- Dictionary methods:
```python
d = {"name": "Alice", "age": 25}
print(d["name"])
d["age"] = 26
```
Exceptions
- Try-Except Block:
```python
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("End of try-except block")
```
File Handling
- Reading a file:
```python
with open("file.txt", "r") as file:
content = file.read()
print(content)
```
- Writing to a file:
```python
with open("file.txt", "w") as file:
file.write("Hello, World!")
```
Modules
- Importing a module:
```python
import math print(math.sqrt(16)) ```
- Custom module:
```python
# In mymodule.py
def add(x, y):
return x + y
# In main file from mymodule import add print(add(3, 4)) ```
Classes & Objects
- Defining a class:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
p = Person("Alice", 25)
p.greet()
```
Common Built-in Functions
- Range: `range(5)` generates numbers 0 to 4.
- Len: `len(lst)` returns the length of a list.
- Type: `type(x)` returns the data type of `x`.
- Input: `input(“Enter your name: ”)` takes user input.
Useful Tips
- List comprehensions:
```python
squares = [x**2 for x in range(5)] print(squares) ```
- Unpacking:
```python
a, b = 1, 2 print(a, b) ```
Conclusion
This cheatsheet covers the basics of Python syntax and essential concepts for quick reference. For more details, refer to the official Python documentation.
scripting/python.txt · Last modified: 2025/02/13 09:45 by jmbargallo
