Python Short Notes
1. List vs Tuple
List: Mutable, defined with [ ]. Example: [1, 2, 3]
Tuple: Immutable, defined with ( ). Example: (1, 2, 3)
Use list when data may change, tuple when fixed.
2. Operators
Arithmetic: +, -, *, /, %, //, **
Comparison: ==, !=, >, <, >=, <=
Logical: and, or, not
Assignment: =, +=, -=, *=, etc.
3. Recursion
Function that calls itself.
Example: def fact(n):
if n == 0: return 1
return n * fact(n-1)
4. Factorial Program
Recursive:
def fact(n):
if n <= 1: return 1
return n * fact(n-1)
Iterative:
def fact(n):
result = 1
for i in range(1, n+1): result *= i
return result
Python Short Notes
5. File Handling
read(): Read entire file
readline(): Read one line
readlines(): Read all lines as list
Example:
f = open('[Link]', 'r')
print([Link]())
[Link]()
6. range() Function
Used to generate sequences.
range(5) -> 0 to 4
range(1, 6) -> 1 to 5
range(1, 10, 2) -> 1, 3, 5, 7, 9
7. *args and **kwargs
*args: Multiple positional args
def fun(*args):
for a in args: print(a)
**kwargs: Multiple keyword args
def fun(**kwargs):
for k, v in [Link](): print(k, v)