Python Code Examples with Explanations
Example 1: Define a Function That Takes an Argument
# Function definition
def greet(name): # 'name' is the parameter
print(f"Hello, {name}! Welcome to Python programming.")
# Function call
greet("Musa") # "Musa" is the argument
Explanation:
- Parameter: 'name' in the function definition is a placeholder that the function uses to
receive input.
- Argument: 'Musa' is the actual value passed to the function when it's called.
Example 2: Call the Function with Different Arguments
# Function call with a value (literal)
greet("Aisha") # Argument is a literal value.
# Function call with a variable
friend_name = "Kabir"
greet(friend_name) # Argument is a variable.
# Function call with an expression
greet("Hassan" + " Umar") # Argument is an expression (concatenation).
Explanation:
1. Value Argument: 'Aisha' is directly passed as a string.
2. Variable Argument: 'friend_name' stores a string that is passed to the function.
3. Expression Argument: '"Hassan" + " Umar"' evaluates to 'Hassan Umar', which is passed
as the argument.
Example 3: Function with a Local Variable
# Function definition with a local variable
def add_numbers():
total = 5 + 10 # 'total' is a local variable
print(f"The sum is: {total}")
add_numbers()
# Trying to access 'total' outside the function
try:
print(total) # This will cause an error
except NameError as e:
print(f"Error: {e}")
Explanation:
- 'total' is a local variable defined inside the function. It exists only within the function's
scope.
- When we try to access 'total' outside the function, a 'NameError' occurs because 'total' is
not defined globally.
Example 4: Function with a Uniquely Named Parameter
# Function with a unique parameter name
def calculate_square(unique_number): # 'unique_number' is the parameter
return unique_number ** 2
# Function call
result = calculate_square(8)
print(f"The square is: {result}")
# Trying to access 'unique_number' outside the function
try:
print(unique_number) # This will cause an error
except NameError as e:
print(f"Error: {e}")
Explanation:
- 'unique_number' is a parameter and behaves like a local variable during the function's
execution.
- Outside the function, 'unique_number' is undefined, causing a 'NameError'.
Example 5: Variable Defined Outside and Inside a Function with the Same Name
# Global variable
message = "Hello from the global scope!"
def display_message():
# Local variable with the same name
message = "Hello from the local scope!"
print(message) # This refers to the local variable
# Call the function
display_message()
# Print the global variable
print(message) # This refers to the global variable
Explanation:
- When 'message' is defined inside the function, it overrides the global variable within the
function's scope. This is called shadowing.
- Outside the function, the global 'message' remains unchanged. The two variables exist
independently because they belong to different scopes.