None Keywordglobaltry, except)else and finallyModule 4 focuses on:
try, except, else, and finally.def say_hello():
print("Hello!")
say_hello() # Output: Hello!
def keyword, function name, and parentheses.Nonedef get_greeting(name):
return f"Hello, {name}!"
result = get_greeting('Alice')
print(result) # Output: Hello, Alice!
def does_nothing():
pass
print(does_nothing()) # Output: None
def power(base, exponent=2):
return base ** exponent
print(power(4)) # 16
print(power(2, 8)) # 256
def many(*args):
return sum(args)
print(many(1,2,3)) # 6
globalx = 10
def set_x():
global x
x = 99
set_x()
print(x) # Output: 99
def factorial(n):
if n==0: return 1
return n * factorial(n-1)
print(factorial(5)) # Output: 120
Write a recursive function to compute the nth Fibonacci number.
global unless necessary.| Exception | Typical Use |
|---|---|
BaseException |
Base for all exceptions |
Exception |
Most user exceptions |
SystemExit |
Raised by sys.exit() |
KeyboardInterrupt |
Interrupts program |
ArithmeticError |
Numeric errors |
ZeroDivisionError |
Divide by zero |
IndexError |
Sequence index out of range |
KeyError |
Dict key not found |
TypeError |
Invalid type |
ValueError |
Invalid value |
FileNotFoundError |
File I/O fails |
ImportError |
Import fails |
try:
print(10/0)
except ZeroDivisionError:
print('Division by zero!')
try:
f = open("test.txt")
data = int(f.read())
except FileNotFoundError:
print("File not found!")
except ValueError:
print("Non-integer in file!")
except Exception as e:
print(f"Other error: {e}")
try:
x = int(input())
except ValueError:
print('Not an integer!')
else:
print('You entered:', x)
finally:
print('This always runs.')
def check_positive(x):
if x < 0:
raise ValueError("Negative value!")
check_positive(-5) # Raises ValueError
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error!")
except CustomError as e:
print(e)
except: clauses.finally if needed.True if a string is palindrome.get_element(seq, idx) that safely gets the element at index, handling both IndexError and TypeError (e.g., for dicts and lists).| Concept | Syntax Example | Purpose |
|---|---|---|
| Function Definition | def fun(...): ... |
Define reusable code block |
| Function Call | fun(args) |
Invoke function |
| Return Value | return x |
Function outputs a value |
| Default Args | def foo(x=5): ... |
Optional parameter |
| Keyword Args | def bar(a, b=1): ... |
Explicit param assignment |
| *args/**kwargs | def f(*a, **kw): ... |
Pass arbitrary args and keyword args |
| Recursion | def rec(n): return rec(n-1) |
Self-calling function |
| try/except/finally | try: ... except: ... finally: ... |
Exception handling and code cleanup |
| Raising Exception | raise ValueError("msg") |
Manually raise an error |
| Custom Exception | class X(Exception): ... |
User-defined exception |
| Exception Hierarchy | ZeroDivisionError, KeyError, etc |
Built-in error types |
| global | global var |
Access/modify global variable inside function |