Functions in Python
Functions in Python
Python has a large standard library that includes many built-in functions.
These functions can be used to perform a variety of tasks, such as
mathematical operations, file manipulation, and network communication.
For example, the following code uses the math.pi function to calculate the
circumference of a circle:
Python
import math
radius = 5
print(circumference)
31.41592653589793
User-defined functions
You can also define your own functions. This allows you to customize the
functionality of your program and create reusable code blocks.
For example, the following code defines a function called greet(), which
takes a name as an argument and prints a greeting to the console:
Python
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Parameter passing
When you call a function, you can pass arguments to it. These arguments are
known as parameters.
For example, the following code calls the greet() function and passes the
name "Alice" as an argument:
Python
greet("Alice")
The greet() function will receive the name "Alice" as a parameter and print a
greeting to the console.
Global variables
Global variables are variables that can be accessed from anywhere in your
program. This can be useful for sharing data between different parts of your
program.
Default parameters
You can specify default values for parameters in your functions. This allows
you to call the function without passing any arguments, and the default values
will be used instead.
Python
def greet_with_default(name="Bard"):
print(f"Hello, {name}!")
greet_with_default()
greet_with_default("Alice")
Hello, Bard!
Hello, Alice!
Recursion
Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
120
Functions as data
Functions can also be treated as data in Python. This means that you can
pass functions as arguments to other functions and store them in variables.
For example, the following code defines a function called greet(), which
takes a name as an argument and prints a greeting to the console. The code
then creates a variable called greeter and assigns the greet() function to it.
Finally, the code calls the greeter() variable to print a greeting to the
console:
Python
def greet(name):
print(f"Hello, {name}!")
greeter = greet
greeter("Alice")
Hello, Alice!
Conclusion
Functions are a powerful tool for writing efficient and reusable code. By
understanding functions, you can write more complex and sophisticated
programs.