📜  def (1)

📅  最后修改于: 2023-12-03 15:30:25.282000             🧑  作者: Mango

Introduction to def

In Python, def is a keyword used to define functions. Functions are a set of instructions that can be called anytime and anywhere in a program. They allow us to avoid repetition of code and make programs easier to read and maintain.

Here is an example of a function defined using def, which takes two parameters a and b, and returns their sum:

def add(a, b):
    return a + b

The function add takes two arguments, a and b, and returns their sum using the return statement.

To call this function, we can simply provide the arguments:

result = add(2, 3)
print(result)  # outputs 5

We can also define functions with default arguments, like so:

def greet(name, greeting="Hello"):
    print(greeting + ", " + name)

greet("John")  # outputs "Hello, John"
greet("Bob", "Hi")  # outputs "Hi, Bob"

In this example, the function greet takes two arguments, name and greeting, with greeting having a default value of "Hello". If greeting is not provided, it defaults to "Hello".

Conclusion

Overall, def is a fundamental keyword in Python for defining functions. Its usage can greatly improve the readability and maintainability of programs by avoiding repetition of code.