Intro to Python Programming
Functions in Python are reusable code blocks that perform specific tasks. They help break down complex problems into manageable parts, promoting code organization and reusability. Functions can accept input values as parameters and return results, making them versatile tools for modular programming. Understanding function syntax, parameters, and return statements is crucial for effective Python programming. Functions have their own scope for variables and can be either built-in or user-defined. Mastering functions allows developers to write more efficient, maintainable, and organized code.
def
keyword followed by the function name and parenthesesreturn
statementprint()
, len()
, sum()
)def
keyword followed by the function name and parentheses ()
return
statement is used to specify the value to be returned by the function (optional)def greet(name): print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!
func(param1=value1)
)def func(param1=default_value)
)return
statement is used to specify the value that a function should returnreturn
statement immediately exits the function and returns control to the calling codereturn
statement is specified, the function implicitly returns None
def add_numbers(a, b): return a + b result = add_numbers(5, 3) print(result) # Output: 8
global
keyword must be usedx = 10 # Global variable def print_x(): print(x) # Accessing global variable def modify_x(): global x x = 20 # Modifying global variable print_x() # Output: 10 modify_x() print_x() # Output: 20
print()
: Outputs text to the consolelen()
: Returns the length of an object (e.g., string, list)sum()
: Returns the sum of elements in an iterablemin()
and max()
: Return the minimum and maximum values from an iterabledef
keyword and can be customized based on the program's requirementsdef calculate_average(numbers): total = sum(numbers) count = len(numbers) average = total / count return average
return
statement when a return value is expectedglobal
keyword