What is the syntax to create a function?

A function should be created for a group of code that gets executed multiple times. This way, you can shorten your code without having to copy-paste repetitive code over and over.

#to create a function
def <function name>(<parameters, if any>):
     <function code here>
     return <value to be returned> #optional

#to call a function
<function name>(<arguments passed to parameters, if any>)

A parameter is a variable that is stored within a function when it is called. Parameters should be referred to in the function code, otherwise, they are redundant. Arguments are actual values passed to a parameter.

Code pertaining to function definition is executed whenever the function is called, not when it is defined. In other words, defining a function but never using it means its code is never used and therefore redundant.

#example with no parameters
def greetings():
     print('Hello!')
     print('Goodbye!')
greetings()
greetings()

#output
Hello!
Goodbye!
Hello!
Goodbye!
#example with parameters
def customGreetings(name):
     print('Hello, ' + name)
hello('David')

#output
Hello, David
#example with parameters, return statement
def passOrFail(grade):
     if grade>50:
          return 'Student passed'
     else:
          return 'Student failed'
print(passOrFail(100))

#output
Student passed
Advertisements