Intro
Similar to other coding languages, functions in python are a blocks of code that will run only after being called. Today we will look at how to create a function and how to use arguments in functions.
Syntax
To call a function you use the def
keyword followed by the function name, a parenthesis, and a colon:
def myFunction():
print("Hello")
When creating a function in python you must have your block of code after the function name indented:
# correct
def myFunction():
print("Hello")
# incorrect
def myFunction():
print("Hello")
Calling a function
To call your function you use the function name, followed by a parenthesis:
def myFunction():
print("Hello")
myFunction() # prints Hello
Arguments
Arguments are used to pass information into the function. Arguments are written inside the parentheses of your function. You can name the arguments what you like (similar to a variable) and you can have as many arguments as you like:
def myFunction(name):
print(f"Hello {name}")
When we call the function we pass along the information we want used as our argument:
def myFunction(name):
print(f"Hello {name}")
myFunction("Bobby") # prints Hello Bobby
myFunction("Cade") # prints Hello Cade
myFunction("Scott") # prints Hello Scott
Keyword Arguments
You can also send your arguments in a key = value syntax in python:
def myFunction(name):
print(f"Hello {name}")
myFunction(name="Bobby") # prints Hello Bobby
myFunction(name="Cade") # prints Hello Cade
myFunction(name="Scott") # prints Hello Scott
Default Parameter Value
If you want to have a default parameter value for when a function is called without an argument the following syntax is used:
def myFunction(name="Dan"):
print(f"Hello {name}")
myFunction("Bobby") # prints Hello Bobby
myFunction() # prints Hello Dan
Pass Statement
If you have a function written with no code you can use the pass statement to avoid getting an error:
def myFunction():
pass
Top comments (0)