xxxxxxxxxx
# declare a function
def function_name(param) :
# content inside a function
function_name(param) # calling function
xxxxxxxxxx
# In here im giving examples on how the def function works in python.
# Each example is separated by ===
def functionName():
# What to make the function do
==================================================================
def myfunction():
print("Hello World")
myfunction()
==================================================================
def subtractNum():
print(34 - 4)
subtractNum()
# Output: 30
==================================================================
def functionName(arg1, arg2):
# What to do with function
functionName(valueForArg1, valueForArg2)
==================================================================
def addNum(num1, num2):
print(num1 + num2)
addNum(2, 4)
# Output: 6
==================================================================
def multiplyNum(num1):
return num1 * 8
result = multiplyNum(8)
print(result)
# Output: 64
==================================================================
xxxxxxxxxx
def example(): #This defines it
print("Example.") #This is the defined commands
example() #And this is the commands being run
xxxxxxxxxx
OK, basically def function() is a block where you will have one task that you can repeat all over again in the code to make it look short and clean
xxxxxxxxxx
def test_function(argument1,argument2,argument3) :
# Do something with the code, and the arguments.
print(argument1)
print(argument2)
print(argument3)
# Calling the function.
test_function('Hello','World','!')
# Output
'''
Hello
World
!
'''
xxxxxxxxxx
a = 34
b = 78
def total():
print("The total of a+b is:",a+b)
#how to print def function
total()
xxxxxxxxxx
#to create a function in python, do the following
#create func
def func(): #can add variables inside the brackets
print("This is the function of the func")
# to call a function, do the following
func()
#you would get a line of code saying "This is the function of the func"
# By Codexel
xxxxxxxxxx
def main():
#this will define your function, which you can use in the program
#or you can use it in other programs too, which ill show later
#also you have to call your function once atleast
userinput = input("String: ")
#ask the user for input, which is being stored in userinput
if len(userinput) < 5:
print("it is longer")
else:
print("it is shorter")
main()
#this will call the function
'''
to use your function in other programs, you can just do the following
from (the name of the program you want to import the function from) import (function name)
done!
Really hoped this helped
'''
xxxxxxxxxx
print("Hello below this is function")
def hi():
print("Hi I am a function")
hi() # You must call the function