Python Code Examples
Python Code Examples
# 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.
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.
add_numbers()
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.
# Function call
result = calculate_square(8)
print(f"The square is: {result}")
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
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.