Functions
Example of use
Create a file with the .py extension
For example functions_demo.py
Let us look at the simplest function that does nothing.
To declare it use the word def then come up with a name - for example lazy
put parentheses () and a colon
The general syntax is as follows
def function_name(): some code
In our case we get
def lazy(): pass
pass means simply to continue the code without doing anything. It is used in far from every function.
Our function is created, in other words declared. This means that it exists somewhere in the code and can do something.
But it does not. For the function to do something it must be called. In our case it is enough to write its name and parentheses.
lazy()
python functions_demo.py
If no errors are made the output will be empty
Let us declare and call a function that prints Hello World!
def hello(): print("Hello World!")
hello()
python functions_demo.py
Hello World!
A function does not have to be written on one line. It is better to go to a new line after the colon and make an indent of four spaces.
def hello():
print("Hello World!")
hello()
python functions_demo.py
Hello World!
Let us write a function that adds two numbers.
def sum(first, second):
print first + second
sum(3,4)
python functions_demo.py
7
Article author: Andrei Olegovich