Module 3: Fundamentals of Python Programming Language
Module 3: Fundamentals of Python Programming Language
Programming Language
Functions
Sometimes we copy and paste our code
import datetime
task completed
first_name = 'Susan' 2019-05-30 16:55:01.815327
print('task completed')
0
print(datetime.datetime.now()) 1
print() 2
3
4
for x in range(0,10): 5
print(x) 6
print('task completed') 7
8
print(datetime.datetime.now()) 9
print() task completed
2019-05-30 16:55:01.817263
Use functions instead of repeating code
import datetime task completed
# Print the current time 2019-05-30 16:55:45.397319
def print_time():
print('task completed') 0
1
print(datetime.datetime.now())
2
print() 3
4
first_name = 'Susan' 5
print_time() 6
7
for x in range(0,10): 8
print(x) 9
print_time() task completed
2019-05-30 16:55:45.399314
We can pass values to functions
def print_hello(n):
print(‘Welcome ’*n)
print()
print_hello(3)
times = 2
print_hello(times)
multiple_print(‘Hello’,5)
multiple_print(‘A’, 10)
HelloHelloHelloHelloHello
AAAAAAAAAA
You can make a default arguments
def multiple_print(string,n = 1):
print(string*n)
print()
multiple_print(‘Hello’,5)
multiple_print(‘Hello’)
HelloHelloHelloHelloHello
Hello
We can write functions that perform
calculations and return a result
def convert(t):
x = t * 9/5 + 32
return x
print(convert(20))
68
We can write functions that perform
calculations and return a result
def solve(a,b,c,d,e,f):
x = (d*e – b*f) / (a*d – b*c)
y = (a*f – c*e) / (a*d – b*c)
return [x,y]
def multiple_print(string,n,bad_words):
if string in bad_words:
return
print(string * n)
print()
Calling a function in another function
def func1():
for i in range(10):
print(i,’ ’,end=‘’)
def func2():
i = 100
print()
func1()
print()
print(i)
0 1 2 3 4 5 6 7 8 9
func1() 0 1 2 3 4 5 6 7 8 9
func2() 100
Function: Local Variables
def func1():
for i in range(10):
print(i,’ ’,end=‘’)
def func2():
i = 100
print()
func1()
print()
print(i)
0 1 2 3 4 5 6 7 8 9
func1() 0 1 2 3 4 5 6 7 8 9
func2() 100
Function: Global Variables
def reset():
global time_left
time_left = 0
def print_time():
print(time_left)
time_left = 30
Functions make your code more readable and easier to maintain
Functions must be declared before the line of code where the function is called
End of Module 3
Thank you