Table of contents
Functions with Outputs
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
def format_name(f_name, l_name):
"""Take a first and last name and format it to return the title case version of the name."""
#Early return to end the function
if f_name == "" or l_name == "":
return "You didnt input valid inputs."
fromated_f_name = f_name.title()
fromated_l_name = l_name.title()
return f"{fromated_f_name} {fromated_l_name}"
formated_string = format_name(first_name, last_name)
print(formated_string)
- Multiple Return Values: We can use more than one return in one function
- Empty return function
def function()
return
value= function()
print(value)
#output
None
Docstrings
It is a way of documenting a functions.
def format_name(f_name, l_name):
#Docstring
"""Take a first and last name and format it to return the title case version of the name."""
#Early return to end the function
if f_name == "" or l_name == "":
return "You didnt input valid inputs."
fromated_f_name = f_name.title()
fromated_l_name = l_name.title()
return f"{fromated_f_name} {fromated_l_name}"
format_name()
When ever we will call our function, it will show definition of that function that we wrote as a Docstring. You can see in the image below.
It can also be use for Multilines String and Multiline Comments.
Print vs Return
Printing and returning are completely different concepts.
print is a function you call. Calling print will immediately make your program write out text for you to see. Use print when you want to show a value to a human.
return is a keyword. When a return statement is reached, Python will stop the execution of the current function, sending a value out to where the function was called. Use return when you want to send a value from one point in your code to another.
Using return changes the flow of the program. Using print does not.
Source: pythonprinciples
Recursion
When a function call it self, it is called recursion.
Note⚠️: Function must call it self under certain condition otherwise it won't stop calling it self and its execution never ends.
a=2
def function(a)
if a=2:
function(a)
function(a)
Project
Built a simple calculator see the code on Github