Functions

1. Defining a Function
A function in Python is a block of reusable code that performs a specific action. It is defined using the def keyword, followed by the function name and parentheses.
Example:
def greet():
print("Hello, world!")
2. Calling a Function
To execute the code inside a function, you need to call it by using its name followed by parentheses.
Example:
greet() # This will output: Hello, world!
3. Defining & Calling a Function
You should define a function before you call it. This is because Python needs to know about the function's existence before you attempt to use it.
Example:
def say_hello():
print("Hello!")
say_hello() # Outputs: Hello!
4. Printing a Message with External Variables
If you want to use a variable that is defined outside the function, you can do so by accessing it from within the function.
Example:
name = "Alice"
def print_message():
print(f"Hello, {name}!")
print_message() # Outputs: Hello, Alice!
5. Function With Arguments
You can pass values to a function using arguments. These values are used within the function to perform operations.
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Bob") # Outputs: Hello, Bob!
6. Variables Inside a Function
Variables defined inside a function are local to that function and cannot be accessed outside of it.
Example:
def calculate_sum(a, b):
result = a + b
return result
print(calculate_sum(5, 3)) # Outputs: 8
# print(result) # This will raise an error since 'result' is local to calculate_sum.
7. Returning a Value
To return a value from a function, use the return keyword. After the return statement is executed, the function exits and the returned value can be used elsewhere.
Example:
def square(number):
return number ** 2
print(square(4)) # Outputs: 16
8. Code After Return Statement
Any code written after the return statement will not be executed.
Example:
def example_function():
return "This will be returned."
print("This will not be executed.") # This line is never reached.
print(example_function()) # Outputs: This will be returned.
9. Built-in Functions
Python provides several built-in functions that are readily available for use. Here are a few examples:
print(): Outputs to the console.int(): Converts a value to an integer.str(): Converts a value to a string.len(): Returns the length of an object (like a list or string).
Example:
print(len("Hello")) # Outputs: 5
print(int("123")) # Outputs: 123
print(str(456)) # Outputs: '456'
Function Arguments:
1. Function Arguments
A function in Python can accept multiple arguments. Here’s a basic example of a function with multiple arguments:
Example:
def describe_person(name, age):
print(f"Name: {name}, Age: {age}")
describe_person("Alice", 30)
# Outputs: Name: Alice, Age: 30
2. Keyword Arguments
Keyword arguments allow you to pass values by explicitly specifying the parameter names. This makes your code more readable and flexible.
Example:
def describe_person(name, age):
print(f"Name: {name}, Age: {age}")
describe_person(name="Bob", age=25)
# Outputs: Name: Bob, Age: 25
Possible Mistakes - Keyword Arguments:
Incorrect Order: If you mix positional and keyword arguments, ensure positional arguments come first.
Example:
describe_person("Charlie", age=40) # Correct describe_person(name="Charlie", 40) # Error: positional argument follows keyword argument
3. Positional Arguments
Positional arguments are passed without specifying the parameter names. They are assigned based on their position in the function call.
Example:
def greet(greeting, name):
print(f"{greeting}, {name}!")
greet("Hello", "Eve") # Outputs: Hello, Eve!
Possible Mistakes - Positional Arguments:
Mismatched Order: If you change the order of arguments, it can lead to incorrect results.
Example:
greet("Eve", "Hello") # Outputs: Eve, Hello! (not as intended)Missing Arguments: If you forget to provide all required positional arguments, you'll get an error.
Example:
greet("Hi") # Error: missing 1 required positional argument: 'name'
4. Default Values
Default values allow you to provide a default for one or more arguments. If the caller does not provide a value for these arguments, the default is used.
Example - 1:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Frank") # Outputs: Hello, Frank!
Example - 2:
def add(x, y=10):
return x + y
print(add(5)) # Outputs: 15
Example - 3:
def power(base, exponent=2):
return base ** exponent
print(power(3)) # Outputs: 9
Example - 4:
def describe(name, age=30, city="New York"):
print(f"Name: {name}, Age: {age}, City: {city}")
describe("Grace") # Outputs: Name: Grace, Age: 30, City: New York
Example - 5:
def multiply(a, b=1, c=1):
return a * b * c
print(multiply(2, c=5)) # Outputs: 10
Non-default arguments cannot follow default arguments.
Example - 6:
def example(a, b=5, c): # Error: non-default argument follows default argument
return a + b + c
5. Passing Immutable Objects
When you pass immutable objects (like integers, strings, or tuples) to a function, changing the value inside the function does not affect the original object outside the function.
Example:
def modify_string(s):
s = s + " world"
return s
text = "Hello"
new_text = modify_string(text)
print(text) # Outputs: Hello
print(new_text) # Outputs: Hello world
In this example, the text variable outside the function remains unchanged because strings are immutable.



