Python Cheatsheet
Python Cheatsheet
- Integers: num = 42
- Floats: pi = 3.14
2. Conditional Statements
if condition:
# Code
elif other_condition:
# Code
else:
# Code
3. Loops
# For Loop
# Code
# While Loop
while condition:
# Code
4. Functions
def function_name(parameters):
# Code
return result
# Example
return a + b
class ClassName:
self.param1 = param1
self.param2 = param2
def method(self):
# Code
# Example
class Person:
self.name = name
self.age = age
def greet(self):
6. File Handling
# Read File
content = file.read()
# Write File
file.write("Hello World")
8. List Comprehensions
squares = [x**2 for x in range(10) if x % 2 == 0]
9. Exception Handling
try:
except Exception as e:
# Handle exception
finally:
# Always executed
import module_name
# Example
import math
print(math.sqrt(16))