Python Functions
Define a function
def myFunc ():
# Your code here
- Indent the lines of code before the definition to indicate that they are part of the function.
- Functions are useful because you can cause a group of code to be executed multiple times simply by calling the function each time.
Call a function
myFunc()
- This will execute the code within the function that you defined with the name 'myFunc'.
Pass values (parameters) to the function
def myAddFunc ( num1, num2 ):
print(num1 + num2)
myAddFunc(312,528) # Call the function with the parameters
- The parameters num1 and num2 are treated as variables within the function.
- The first value passed in the function call will be the value of the first parameter named in the function definition (num1 will be 312 in this case).
- If you pass a variable as a parameter to a function, any changes made to that variable will not continue after the function has ended (unless it is a mutable type such as a List or Dictionary).
- Parameters can be assigned a default value in case no value is passed in the function call. Just assign a value when naming the parameter, e.g. num2 = 22
- A parameter can be made to accept multiple values as input. Just put an asterisk '*' before the parameter name.
Have the function generate a value
def myFunc ():
return 5
print( myFunc() ) # Calls the function and prints the value that is returned
- This will replace the function call with number 5, of course you will more likely return a calculated value.
- You can return any data type you want.
Add a function description
def myFunc ():
'''
Your description
here
'''
# Your code here
- The description can then be displayed if you use the help() function with the function name as a parameter.
- This is useful for others so they can get a description of how to use your function.
Challenge
Write a function that will display a count down starting from the number passed as a parameter and stopping at 0 : e.g. "Countdown: 9", "Countdown: 8", ... (with each count on a new line).
Completed