-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions_guid.py
More file actions
66 lines (49 loc) · 1.5 KB
/
functions_guid.py
File metadata and controls
66 lines (49 loc) · 1.5 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# FUNCTIONS – FULL USAGE GUIDE
# Basic Syntax:
# def function_name(parameters):
# block of code
# --------------------------------------------
# 1. Defining a basic function
def greet():
print("Hello from the function!")
# Call the function AFTER defining it
greet()
# --------------------------------------------
# 2. DOs and DON'Ts
# Don't call a function before it's defined:
# greet() # This would raise NameError if called before definition
# Always define before calling:
def welcome():
print("Welcome to Python!")
welcome()
# --------------------------------------------
# 3. Function that performs a task (prints something)
def print_sum(a, b):
print("The sum is:", a + b)
print_sum(4, 5) # Output: The sum is: 9
# --------------------------------------------
# 4. Function that calculates and returns a value
def get_sum(a, b):
return a + b
result = get_sum(10, 20)
print("Returned sum:", result)
# --------------------------------------------
# 5. Local vs Global Variables
# Global variable
counter = 100
def increase_counter():
# Local variable (does not affect global counter)
counter = 0
counter += 1
print("Local counter:", counter)
increase_counter()
print("Global counter remains:", counter)
# --------------------------------------------
# 6. Using 'global' keyword to modify global variable
count = 0
def modify_global():
global count
count += 1
print("Modified global count:", count)
modify_global()
print("Global count after function:", count)