0% found this document useful (0 votes)
62 views56 pages

L1 2 3unit3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 56

L1,2,3

UNIT-3
• A program is written to solve a simple/complex problem. Generally, a program solving simple problem is very easy to
understand and also to identify mistakes, if any, in them.
• The steps involved in the programs that solve large complex problems are huge and have thousands of lines of code and
become difficult to understand. So, large programs are subdivided into a number of smaller programs called
subprograms.
• Some times, we need to write a particular block of code that needs to be executed more than once in our program. An
error in one such block may introduce many errors in the program. This block of code can be grouped as a
subprogram. Such subprograms specify one or more actions to be performed for the larger program. These
subprograms are called functions.
• Most programming languages provide this feature called functions , where we need to declare and define a group of
statements once and that can be called and used whenever required. This saves both time and effort. So, we can define
a Function as a self-contained block of statements that specifies one or more actions to be performed.
The main reasons for using functions are:
 To improve the readability of code.
 Improves the re-usability of the code, same function can be used in any program rather than writing the same code.
 debugging of the code would be easier if you use functions (errors are easy to be traced).
 reduces the size of the code, duplicate set of statements are replaced by function calls.
Which of the following option is correct?
1. A function is defined once but called many number of times.
2. Function is a block of statements to do one or more tasks.
3. By writing different functions in a program, increases the length of the code.
A. 1 only
B. 2 only
C. 1 and 2
D. 1 and 3
Which of the following option is correct?
1. A function is defined once but called many number of times.
2. Function is a block of statements to do one or more tasks.
3. By writing different functions in a program, increases the length of the code.
A. 1 only
B. 2 only
C. 1 and 2
D. 1 and 3
Solution:
def helloworld():
print("Hello World")
print("Good morning")
print("Have a nice day")
print("The function ends")
helloworld()
Solution:
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)
Calling a function:
Till now we have just defined the functions. It means they are just written and have never been used.
To use a function (to execute the statements in the function), we need to call the function.
A function is called by using the function name in the main program.
Example:
Write a program to know how to call a function in Python.
Take two integer parameters a and b as input from the user using input() function. Define three functions
with names add, sub and mul to perform addition, subtraction and multiplication on the given two
parameters respectively, print the result as shown in the example.
Solution:
# write your code here
def add(a,b):
print(a+b)

def sub(a,b):
print(a-b)

def mul(a,b):
print(a*b)

a=int(input("a: "))
b=int(input("b: "))
add(a,b)
sub(a,b)
mul(a,b)
Docstring
A comment that occurs in the first line of the function body after the colon(:) is known as Docstring.

Let's understand the features of docstrings:


• It is called the Docstring.
• It is a string written between triple quotes """ """.
• It can have multiple lines.
• This string is available in the program as a __doc__ attribute.
• This is a very good practice when you write code and add a docstring to the function.
Which of the following is the correct option?
1. A comment that occurs in the first line of the function body after the colon(:) is known as
Docstring
2. This docstring is available in the program as a __doc__ attribute.
3. A docstring should have only one line.
4. A docstring is written between triple quotes ""“
A. 1,2,3
B. 1,2 and 4
C. 2 and 4
D. 3 and 4
Which of the following is the correct option?
1. A comment that occurs in the first line of the function body after the colon(:) is known as
Docstring
2. This docstring is available in the program as a __doc__ attribute.
3. A docstring should have only one line.
4. A docstring is written between triple quotes ""“
A. 1,2,3
B. 1,2 and 4
C. 2 and 4
D. 3 and 4
Solution:
def abc():
"""Function is defined to print string abc."""
print("abc")

def pqr(a, b):


"""Function is defined to print the product of parameters passed.

a -- is the first parameter.


b -- is the second parameter.
"""
print(a * b)

# Write your code here to print docstring's of abc and pqr methods
print(abc.__doc__)
print(pqr.__doc__)
Return statement in a function :
The return statement is used to quit a function it is executing and to pass the control back to the statement
from where it was called. The syntax of the return statement is as below:
return [expression_list / value]

Features of the return statement:


The return statement can have an expression that gets evaluated and the value is returned or a value
directly can be returned.
 If there is no expression in the statement then the function will return None.
If the function does not have a return statement as we have done a few functions in previous examples,
then the function will return None.
Multiple values can be returned by a Python function
Solution:
def addavg(a,b):
sum1=a+b
avg=sum1/2
return sum1,avg

def sub(a,b):
return a-b

def mul(a,b):
return a*b

a=int(input("a: "))
b=int(input("b: "))
r1,r2=addavg(a,b)
print("sum, average: ({}, {})".format(r1,r2))
print("subtraction:",sub(a,b))
print("multiplication:",mul(a,b))
Solution:
def add(a,b):
return a+b

def sub(a,b):
return a-b

a=int(input("a: "))
b=int(input("b: "))
print("addition:",add(a,b))
print("subtraction:",sub(a,b)) Lesson-1 completes here
ARGUMENT
An argument is an expression which is passed to a function by its caller, in order for the function to perform its
task.
It is an expression in the comma-separated list bound by the parentheses in a function call expression.
Arguments are local to the particular function.
These variables are placed in the function declaration and function call.
These arguments are defined in the calling function.
PARAMETER
 Parameters are variables defined in the function to receive the arguments.
 Parameters are those defined in the function definition.
 Parameters are available only with in the specified function and parameters belong to the called function.
 Parameters are the local variables to the function.
 The Parameters occupy memory only when the function execution starts and are destroyed when the function
execution completes.
Select the correct statements given below:
1. An argument is an expression which is passed to a function by its caller, in order for the function
to perform its task.
2. Arguments are local to the particular function.
3. Parameters are available only with in the specified function and parameters belong to the called
function.
4. Parameters occupy memory through out the program execution.
A. 1 and 2
B. 1,2 and 3
C. 2 and 3
D. 1 and 3
Select the correct statements given below:
1. An argument is an expression which is passed to a function by its caller, in order for the function
to perform its task.
2. Arguments are local to the particular function.
3. Parameters are available only with in the specified function and parameters belong to the called
function.
4. Parameters occupy memory through out the program execution.
A. 1 and 2
B. 1,2 and 3
C. 2 and 3
D. 1 and 3
Solution:
a=int(input("a: "))
b=int(input("b: "))

def add(a, b):


return a+b

print(add(a,b))
Solution:
def sayhello(username):
greet="Hello"
print(greet+" "+username)

users = ['Ram', 'Mahesh', 'Vasudha', 'Uma', 'Sekhar', 'John']


for i in users:
sayhello(i)
Solution:
Solution:
def printPascal(n):
for line in range(1, n + 1):
C = 1; # used to represent C(line, i)
for i in range(1, line + 1):
print(C, end = " ");
C = int(C * (line - i) / i);
print();

# Driver code
n = int(input("num: "))
printPascal(n);
Keyword arguments
Whenever a function is called with some arguments, the arguments passed get assigned to the
parameters of the function and the function uses these parameter values inside the body of the
function.
Example:
Let's look at a function which takes two arguments name and age and prints whether the person can
apply for voter id or not, voter_id(name, age).
The first parameter is name which is a string and the second parameter is age which is an integer.
Whenever we call this function, the first argument should be name and the second argument should be
age.
We cannot call this function with the first argument as age and second argument as name.
These are called Positional arguments. Readers must examine the documentation to understand what
the arguments mean, especially if there are many arguments. To avoid this problem, we use keyword
arguments.
Notice the sequence in which the arguments are passed.

They are not in the same sequence as they are in the


function definition.

This passing of arguments in any order by passing the


names and assigning them to the right parameters is
called keyword arguments.

Keyword arguments simply augment to Python’s core


philosophy that “readability counts”.
Select all the correct statements given below.
1. When the values are passed, as arguments to the function in any order and these values get assigned,
these arguments are called keyword arguments.
2. Calling the function add(a = 10,b = 20) or by add(10, 20) produce the same result.
3. Calling the function add(b = 20, a = 10) or by add(10, 20) do not produce the same result.
A. 1 and 2
B. 2 and 3
C. 1 and 3
D. 1 only
Select all the correct statements given below.
1. When the values are passed, as arguments to the function in any order and these values get assigned,
these arguments are called keyword arguments.
2. Calling the function add(a = 10,b = 20) or by add(10, 20) produce the same result.
3. Calling the function add(b = 20, a = 10) or by add(10, 20) do not produce the same result.
A. 1 and 2
B. 2 and 3
C. 1 and 3
D. 1 only
Solution:
#Program to illustrate keyword parameters

#define your function here and perform arithmetic operations addition, subtraction,
multiplicateion and print the result.
def simplecalc(a,b):
print("addition:",a+b)
print("subtraction:",a-b)
print("multiplication:",a*b)

simplecalc(a = 3, b = 5)
simplecalc(b = 4, a = 5)
#This function can also be called with positional arguments
simplecalc(8, 4)
Solution:
def saysomething(name,message):
print("Good"+" "+message+" "+name)

n=input("name: ")
m=input("morning/night: ")
saysomething(name=n,message=m)
saysomething(message=m,name=n)
Solution:
def nameage(*, name, age):
print(name, age)
n=input("name: ")
a=int(input("age: "))
nameage(age = a, name = n)
nameage(name = n, age = a)

Note: This syntax will make sure we can pass only keyword arguments, but not
positional arguments

Lesson 2 ends here..


Default arguments
• Function arguments can have default values.
• A default value can be provided to an argument by the use of assignment operator (=). The default
value is assigned only when no value is passed for that argument.
• In case of passing a value for the parameter that has the default value, the default value is replaced
with the passed value.
• Number of arguments in any function can have default value.
Solution:
def simplecalc(a, b = 100):
# write your code here

print("addition:",a+b)
print("subtraction:",a-b)
print("multiplication:",a*b)

num1=int(input("num1: "))
num2=int(input("num2: "))

simplecalc(a = num1)
simplecalc(b = num2, a = num1)
Solution:
def calculateTax(salary,percent=20):
taxAmount=(salary*percent)/100
print(taxAmount)
salary=int(input("salary: "))
percent=float(input("tax percentage: "))
calculateTax(salary)
calculateTax(salary,percent)
Important points on default arguments.
• Function arguments can have default values in Python.
• A default value can be provided to an argument by using assignment operator (=).
• The default value is assigned only when no value is passed for that argument.
• In case of passing a value for the parameter that has the default value, the default value
is replaced with the passed value.
• Any number of arguments in a function can have a default value.
• But once we have a default argument, all the arguments to its right must also have
default values.
• This means Non-default arguments cannot follow default arguments.
Which of the following is the correct option?
1. Function arguments can have default values in Python.
2. The default value is assigned even when a value is passed for that argument.
3. Any number of arguments in a function can have a default values.
4. non-default arguments cannot follow default arguments.
A. 1,2 and 3
B. 1 and 2
C. 1,3 and 4
D. All options are correct
Which of the following is the correct option?
1. Function arguments can have default values in Python.
2. The default value is assigned even when a value is passed for that argument.
3. Any number of arguments in a function can have a default values.
4. non-default arguments cannot follow default arguments.
A. 1,2 and 3
B. 1 and 2
C. 1,3 and 4
D. All options are correct
Solution:
def fun1(name = 'Padma',age = 12):
'''Body of the function'''
print (name,"is",age, "years old.")
fun1('Aruna', 16) #Call 1 -- positional parameters
fun1(age = 16, name = 'Karuna’) #Call 2 -- Keyword parameters
fun1(age = 16) #Call 3 -- Name is default
fun1(name = 'Karuna') #Call 4 -- Age is default
fun1() #Call 5 -- Name and Age are default
Arbitrary/Variable length arguments :

• In some cases, the user may not have an idea of the correct number of arguments that will be passed
into a function During of execution.
• This kind of scenario can be dealt with a function being defined for an arbitrary number of arguments
and then called.
• This is done by using an asterisk (*) in the function definition, where we use this before the parameter
name to specify that these type of arguments can be many.
• The function body should be written in such a way to handle these arguments.
• The syntax for specifying arbitrary number of arguments are
def fun_name( * args)
Which of the following is the correct option?
1. If the correct number of arguments that will be passed to a function at the time
of execution is not known , we can use function with arbitrary arguments.
2. Arbitrary arguments. is specified by using an asterisk (*) in the function
definition before the parameter name.
3. Arbitrary/Variable length arguments are two different functionalities.
A. 1 and 2
B. 2 and 3
C. 1 only
D. 1,2 and 3
Which of the following is the correct option?
1. If the correct number of arguments that will be passed to a function at the time
of execution is not known , we can use function with arbitrary arguments.
2. Arbitrary arguments. is specified by using an asterisk (*) in the function
definition before the parameter name.
3. Arbitrary/Variable length arguments are two different functionalities.
A. 1 and 2
B. 2 and 3
C. 1 only
D. 1,2 and 3
Solution:
#Program to illustrate variable number of arguments
def mySum(*args):
sum1 = 0
for i in args:
sum1 = sum1 + i
return(sum1)
print(mySum(1, 2, 3, 4, 5, 6, 7)) #7 arguments
print(mySum(1, 2)) #2 arguments
print(mySum(1, 2, 3)) #3 arguments
Solution:
#Program to illustrate Variable number of arguments
def largestNumber( * numbers):
m = numbers[0]
for num in numbers:
if num > m:
m = num

print("largest:",m)
# write your code here

largestNumber(1, 2, 3, 4) #4 arguments
largestNumber(8, 9, 3, 4, 2, 5) #6 arguments
Lesson-3 ends here..

You might also like