Create Function
def basic_function():
Use def to define a function with parenthesis for parameters. Optionally pass parameters (data) into the function to return a result.
Indent codelines in the body of the function. Any lines not indented will run before the function is called.
Run the function by calling it.
Example:
def greeting(): #define function.
print("Hello!") #indented lines of code belong to function.
print("This is my first function.")
greeting() #call the function.
Hello!
This is my first function.
Example:
def calcPercent(number, percent): #define parameters.
numPercent = (number * percent) / 100
print(numPercent,'%',sep='')
def main():
number = float(input('Enter a number: '))
percent = float(input('Enter a percent: '))
calcPercent(number, percent) #pass user input into calcPercent.
main() #call the main function.
Enter a number: 220
Enter a percent: 10
22.0%
Example:
def calcPercent(number, percent): #define parameters.
numPercent = (number * percent) / 100
return numPercent
def main():
number = float(input('Enter a number: '))
percent = float(input('Enter a percent: '))
print(calcPercent(number, percent),'%',sep='') #pass-in user input.
main() #call the function.
Enter a number: 220
Enter a percent: 10
22.0%