Defining Functions
Functions are an essential part of programming. They allow us to write reusable code that can be easily organized and maintained. In this lesson, we will learn how to define and call functions in Python 3.
Defining a Function
To define a function in Python, we use the def keyword followed by the function name and a set of parentheses. Inside the parentheses, we can specify any input parameters that the function will take. Here is an example:
In this example, we have defined a function called greet that takes a single input parameter called name.
Calling a Function
To call a function, we simply use its name followed by a set of parentheses. Inside the parentheses, we can specify any input arguments that the function requires. Here is an example of calling the greet function we defined above:
greet("John")
This will print "Hello, John!" to the screen.
Returning a Value from a Function:
In addition to performing a specific task, a function can also return a value. To return a value from a function, we use the return keyword followed by the value we want to return. Here is an example of a function that returns a value:
In this example, the square function takes a single input parameter called x and returns the square of that number. We call the function and store it in the result variable, before printing the value which is 25 in this example.
That's it! Great job with this lecture. See you in the next one!
No comments yet. Add the first comment to start the discussion.