Defining and calling functions:
Functions are used to encapsulate a block of code that performs a specific task. In Python, a function is defined using the "def" keyword followed by the function name, any arguments that the function takes, and a colon. The body of the function is indented beneath the function definition. For example:
python
Copy code
def greet(name):
print("Hello, " + name + "!")
This defines a function called "greet" that takes one argument called "name". When called with a string value, the function will print "Hello, <name>!" where <name> is the value of the "name" argument.
To call a function, simply write the function name followed by any arguments that it takes, enclosed in parentheses. For example:
arduino
Copy code
greet("Alice") # prints "Hello, Alice!"
Passing arguments to functions:
Functions can take arguments, which are values passed to the function when it is called. To define a function that takes arguments, include the argument names in the function definition separated by commas. For example:
python
Copy code
def add_numbers(x, y):
result = x + y
print(result)
This defines a function called "add_numbers" that takes two arguments called "x" and "y". When called with two numeric values, the function will add them together and print the result.
To call a function with arguments, simply include the argument values in the function call, separated by commas. For example:
scss
Copy code
add_numbers(2, 3) # prints 5
Return values from functions:
Functions can also return values, which are values that the function computes and sends back to the calling code. To specify a return value, use the "return" keyword followed by the value to be returned. For example:
arduino
Copy code
def add_numbers(x, y):
result = x + y
return result
This defines a function called "add_numbers" that takes two arguments called "x" and "y" and returns their sum.
To use the return value from a function, assign the function call to a variable or use the function call directly in an expression. For example:
bash
Copy code
sum = add_numbers(2, 3)
print(sum) # prints 5
Local and global variables:
Variables defined within a function are called local variables, and they exist only within the scope of that function. Variables defined outside of a function are called global variables, and they exist throughout the program. For example:
python
Copy code
x = 5 # global variable
def add_numbers(y):
x = 10 # local variable
result = x + y
print(result)
add_numbers(2) # prints 12
print(x) # prints 5
In this example, the global variable x has a value of 5. When the function "add_numbers" is called, it defines a local variable x with a value of 10. The function adds the value of y (2) to the local variable x (10), resulting in a printout of 12. However, when the global variable x is printed after the function call, it still has a value of 5. This is because the local variable x exists only within the function and does not affect the global variable x.
0 Comments