1# declare a function
2def function_name(param) :
3 # content inside a function
4
5function_name(param) # calling function
1#A function is a block of code which only runs when it is called.
2#You can pass data, known as parameters, into a function.
3#following is a simple function
4def exmple_of_function():
5 print("Hello from a function")
6
7example_of_function()
1def FunctionName(Parameters):
2 # Function Content
3FunctionName() #Calling Function
1#Functions can be re used in programmes and can be extremely useful.
2#You would use functions a lot when you make programmes using packages such
3#as Tkinter, of which you will in the future.
4#The Format:
5#def [Whatever name you want]()
6#[The "()" at the end is compulsory as we are making a function.]
7
8#Think of it like using an inbuilt function from python like .lower()
9
10
11def greet():
12 print("Hello!")
13
14greet() #We are recalling the function by typing out its name and brackets
15
16
17#This function will have something known as a parameter aka arguement
18#This example will show a non changeable arguement unless coded
19
20
21#Option 1, will directly print the sum:
22def math(num1, num2):
23 sum = num1+num2
24 print(sum)
25
26math(1, 2) #We change the num 1 and num 2 to the one and 2, though this can't change unless progammed to.
27
28#Option 2, will return the sum and then print upon command.
29def math(num1, num2):
30 sum = num1+num2
31 return sum
32
33print(math(1, 2))
34
35#Good luck to all my future Software engineers! Hope life treats you all well!
36#Inshallah! (Meaning if Allah allows it!)
1def function1(): # outer function
2 print ("Hello from outer function")
3 def function2(): # inner function
4 print ("Hello from inner function")
5 function2()
6
7function1()
8
1#Use this to shortern a task that you may want to repeat
2#Used for making custom commands
3def paste(a, b)
4 for i in b:
5 print(a)
6
7
8while True:
9 paste("Python is Cool!!!", 3)
10
11#Output:
12#Python is Cool!!!
13#Python is Cool!!!
14#Python is Cool!!!
15
16
17
18
19
20## - ANOTHER EXAMPLE - ##
21
22
23
24
25
26happy = "NEUTRAL"
27
28def yes():
29 happy="TRUE"
30 print("Thank you!")
31
32def no():
33 happy="FALSE"
34 print("That's not nice!")
35
36answer=str(input("Do you like my new shoes? (y/n) ")
37if answer=="yes" or "y" or "Yes" or "Y" or "YES":
38 yes()
39elif answer=="no" or "n" or "No" or "N" or "NO":
40 no()