Unit 3 - Lesson 1

24.1.1. What is a function

(a) A function can be called many number of times.
(b) A Function is a block of statements to do one or more tasks.

24.1.2. Function syntax

(a) Th keyword def always occurs at the start of the function header.
(b) The function_name follows the same rules as any identifiers of Python.

24.1.3. Defining a function

def helloworld():
	
	# write your code here
	print("Hello World")
	print("Good morning")
	print("Have a nice day")
	print("The function ends")
helloworld()

24.1.4. Defining multiple functions

#fill in the missing code..
def add(x, y):
	print(x+y)
def sub(x, y):
	print(x-y)
def mul(x, y):
	print(x*y)

x =int(input("x: "))
y =int(input("y: "))

add(x, y)
sub(x, y)
mul(x, y)

24.1.5. Defining and calling a function

def add():
	print(a + b)
def sub():
	print(a - b)
def mul():
	print(a * b)
a = int(input("a: "))
b = int(input("b: "))

#call the add() function
add()
#call the sub() function
sub()
#call the mul() function
mul()

24.1.6. The DocString in Python

(a) A comment that occurs in the first line of the function body after the colon(:) is known as Docstring
(b) This docstring is available in the program as a __doc__ attribute.
(d) A docstring is written between triple quotes """ """

24.1.7. Return statement in a function

def addavg():
#return sum and average of a and b
	return(a+b,(a+b)/2)

def sub():
#return the difference of a and b
	return(a-b)

def mul():
#return the product of a and b
	return(a*b)

a = int(input("a: "))
b = int(input("b: "))
print("sum, average:", addavg())
print("subtraction:", sub())
print("multiplication:", mul())

Post a Comment