The four steps to defining a function in Python are the following:
Your functions will get more complex as you go along: you can add for loops, flow control and more to it to make it more finegrained.
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return
hello()
In the above function, you ask the user to give a name. If no name is given, the function will print out “Hello World”. Otherwise, the user will get a personalized “Hello” response.
Remember also that you can define one or more function parameters for your UDF. You’ll learn more about this when you tackle the Function Arguments section. Additionally, you can or can not return one or multiple values as a result of your function.
The return Statement
Note that as you’re printing something in your UDF hello(), you don’t really need to return it. There won’t be any difference between the function above and this one:
def hello_World():
print("Hello World")
However, if you want to continue to work with the result of your function and try out some operations on it, you will need to use the return statement to actually return a value, such as a String, an integer, …. Consider the following scenario, where hello() returns a String "hello", while the function hello_noreturn() returns None:
The second function gives you an error because you can’t perform any operations with a None. You’ll get a TypeError that says that you can’t do the multiplication operation for NoneType (the None that is the result of hello_noreturn()) and int (2).
Tip functions immediately exit when they come across a return statement, even if it means that they won’t return any value:
Another thing that is worth mentioning when you’re working with the return statement is the fact that you can use it to return multiple values. To do this, you make use of tuples.
Remember that this data structure is very similar to that of a list: it can contain multiple values. However, tuples are immutable, which means that you can’t modify any amounts that are stored in it! You construct it with the help of double parentheses (). You can unpack tuples into multiple variables with the help of the comma and the assignment operator.
Check out the following example to understand how your function can return multiple values: