-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions_scope.py
More file actions
47 lines (36 loc) · 1.46 KB
/
Copy pathfunctions_scope.py
File metadata and controls
47 lines (36 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Python Functions and Scope
# ------------------------------
# 1. DEFINING FUNCTIONS
# A way to wrap code into a reusable block.
def greet(name):
"""This function greets the person passed in as a parameter."""
return f"Hello, {name}!"
# Calling the function
message = greet("Alice")
print(message)
# 2. DEFAULT ARGUMENTS
# You can provide default values for parameters.
def power(base, exponent=2):
return base ** exponent
print(f"\n2 squared: {power(2)}") # Uses default 2
print(f"2 cubed: {power(2, 3)}") # Overrides default with 3
# 3. GLOBAL VS. LOCAL SCOPE
# Variables created inside a function stay inside (Local).
# Variables created outside are accessible everywhere (Global).
count = 10 # Global variable
def increment():
# To modify a global variable, you must use the 'global' keyword
global count
count += 1
local_val = 5 # Local variable
print(f"Inside function: count={count}, local_val={local_val}")
increment()
# print(local_val) # This would crash because local_val only exists inside increment()
# ------------------------------
# EXERCISE TODO:
# 1. Write a function 'calculate_area' that takes 'width' and 'height'.
# It should return width * height.
# 2. Create a function 'describe_pet' with parameters 'name' and 'animal_type'.
# Set the default 'animal_type' to "dog".
# 3. Create a global variable 'total' = 0. Write a function 'add_to_total(amount)'
# that adds the amount to the global 'total' variable.