DEV Community

SCDan0624
SCDan0624

Posted on

Functions in Python for Beginners

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

Calling a function
To call your function you use the function name, followed by a parenthesis:

def myFunction():
    print("Hello")

myFunction() # prints Hello
Enter fullscreen mode Exit fullscreen mode

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}")

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)