Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  NCERT Solutions: Functions

Functions NCERT Solutions | Computer Science for Class 11 - Humanities/Arts PDF Download

Q1: Observe the following programs carefully, and identify the error:

(a) def create (text, freq):

         for i in range (1, freq):

                print text

    create(5) #function call

Ans: There are two errors in the above code
1. Mismatch of arguments in Function Call and Function create statements.
2. In third line it should be print(“text”)

(b) from math import sqrt,ceil

    def calc():

         print cos(0)

    calc( ) #function call

Ans: There are two errors in he above code:
1. Import function [sqrt( ), ceil( ) ] and used function [cos( ) ] are different.
2. Syntax of print statement is wrong. It should be print(cos(0)).

(c) mynum = 9

    def add9( ):

          mynum = mynum + 9

          print mynum

     add9( ) #function call

Ans: There are two errors in the above code :
1. mynum is a global variable which can be used inside a function only by using a keyword “global” which is missing in above code.
2. Syntax of print statement is wrong. It should be print(mynum).

(d) def findValue( vall = 1.1, val2, val3):

         final = (val2 + val3)/ vall

         print(final)

    findvalue() #function call

Ans: There are three errors in the above code :
1. Function name is different in function call (findvalue( )) statement and function create statement (findValue( ))
2. First line of above code should be def findValue(val2, val3, vall = 1.0)
3. There should be minimum two arguments in function call statement which is missing in above code.

(e) def greet( ):

         return("Good morning")

    greet( ) = message #function call

Ans: There is one errors in the above code :
Third line of above code should be message = greet( )

Q2: How is math.ceil(89.7) different from math.floor(89.7)?
Ans: math.ceil(89.7) gives output 90 while math.floor(89.7) gives output 89.

Q3: Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.
Ans: 
randint( ) function is used to generate random number between 1 and 5. This function generate a random number between two given integers as argument like randint(1, 5).

Q4: How is built-in function pow() function different from function math.pow() ? Explain with an example.
Ans: In built function pow( ) will return an integer while math.pow( ) function will return a floating point number like

print(pow(2, 3) will return 8
import math
print(math.pow(2, 3)) will return 8.0

Q5: Using an example show how a function in Python can return multiple values.
Ans: 

def fun():

   x = 3

   y = 7

   return x,y

 a, b = fun()

 print(a)

 print(b)

OUTPUT
3
7

Q6: Differentiate between following with the help of an example:
(a) Argument and Parameter
(b) Global and Local variable

Ans: 
(a) A parameter is a variable/value which is given in function declaration statement while argument is a variable / value which is given in function call statement like

def fun(a, b):

    return a + b

S = fun(3, 7)

print("Sum is ", S)

Here a and b in first line are parameter while 3 and 7 given in third line are argument

(b) Global Variable: In Python, a variable that is defined outside any function or any block is known as a global variable. It can be accessed in any functions defined onwards
Local Variable: A variable that is defined inside any function or a block is known as a local variable. It can be accessed only in the function or a block where it is defined.

Q7: Does a function always return a value? Explain with an example.
Ans: 
A function does not always return a value. In a user-defined function, a return statement is used to return a value.

Example:

Program:

# This function will not return any value

def func1():

    a = 5

    b = 6

# This function will return the value of 'a' i.e. 5

def func2():

    a = 5

    return a

# The return type of the functions is stored in the variables

message1 = func1()

message2 = func2()

print("Return from function 1-->", message1)

print("Return from function 2-->", message2)

OUTPUT:

Return from function 1--> None

Return from function 2--> 5

Activity-Based Questions

Q1: To secure your account, whether it be an email, online bank account or any other account, it is important that we use authentication. Use your programming expertise to create a program using user defined function named login that accepts userid and password as parameters (login(uid,pwd)) that displays a message “account blocked” in case of  three wrong attempts. The login is successful if the user enters user ID as "ADMIN" and password as "St0rE@1". On successful login, display a message “login successful”. 
Ans: 

c=0

def login(uid, pwd):

   global c

   if uid == "ADMIN" and pwd == "St0rE@1":

        print("Login Successful")

        return

   else:

        c=c+1

     if c == 3:

         print("Account Blocked")

         return

     else:

         ltry()

def ltry():

   global c

   print("Attempt : ",c+1)

   uid = input("Enter User Id")

   pwd = input("Enter Password")

   login(uid,pwd)

ltry() # This function is called to start the program

Q2: XYZ store plans to give festival discount to its customers. The store management has decided to give discount on the following criteria:
Functions NCERT Solutions | Computer Science for Class 11 - Humanities/ArtsAn additional discount of 5% is given to customers who are the members of the store. Create a program using user defined function that accepts the shopping amount as a parameter and calculates discount and net amount payable on the basis of the following conditions: Net Payable Amount = Total Shopping Amount – Discount.
Ans: 

def amount(sa, sd):

   print(sa,sd)

   dis=0

   if sa >=500 and sa <1000:     dis = 5 + sd   elif sa >=1000 and sa <2000 :

        dis = 8 + sd

   else:

        dis = 10 + sd

   Disc = dis/100 * sa

   amt = sa - Disc

   print("Total Discount offered is  :",Disc)

   print("Total Amount to pay after discount is  : ", amt)

sa = int(input("Enter Shopping Amount"))

sm = input("You are Special Member??(y/n)") 

if sm.lower() == 'y':

   amount(sa,5)

else:

   amount(sa, 0)

Q3: ‘Play and learn’ strategy helps toddlers understand concepts in a fun way. Being a senior student you have taken responsibility to develop a program using user defined functions to help children master two and three-letter words using English alphabets and addition of single digit numbers. Make sure that you perform a careful analysis of the type of questions that can be included as per the age and curriculum.
Ans: 

This program can be implemented in many ways. The structure will depend on the type of questions and options provided. A basic structure to start the program is given below. It can be built into a more complex program as per the options and type of questions to be included.

Program:

import random

#defining options to take input from the user

def options():

    print("\n\nWhat would you like to practice today?")

    print("1. Addition")

    print("2. Two(2) letters words")

    print("3. Three(3) letter words")

    print("4. Word Substitution")

    print("5. Exit")

    inp=int(input("Enter your choice(1-5)"))

    #calling the functions as per the input

    if inp == 1:

        sumOfDigit()

    elif inp == 2:

        twoLetterWords()

    elif inp == 3:

        threeLetterWords()

    elif inp == 4:

        wordSubstitution()

    elif inp == 5:

        return

    else:

        print("Invalid Input. Please try again\n")

        options()

#Defining a function to provide single digit addition with random numbers

def sumOfDigit():

    x = random.randint(1,9)

    y = random.randint(1,9)

    print("What will be the sum of",x,"and",y,"? ")

    z = int(input())

    if(z == (x+y)):

        print("Congratulation...Correct Answer...\n")

        a = input("Do you want to try again(Y/N)? ")

        if a == "n" or a == "N":

            options()

        else:

            sumOfDigit()

    else:

        print("Oops!!! Wrong Answer...\n")

        a = input("Do you want to try again(Y/N)? ")

        if a == "n" or a == "N":

            options()

        else:

            sumOfDigit()        

#This function will display the two letter words

def twoLetterWords():

    words = ["up","if","is","my","no"]

    i = 0

    while i < len(words):

        print("\n\nNew Word: ",words[i])

        i += 1

        inp = input("\n\nContinue(Y/N):")

        if(inp == "n" or inp == "N"):

            break;

    options()

#This function will display the three letter words

def threeLetterWords():

    words = ["bad","cup","hat","cub","rat"]

    i = 0

    while i < len(words):

        print("\n\nNew Word: ",words[i])

        i += 1

        inp = input("Continue(Y/N):")

        if(inp == "n" or inp == "N"):

            break;

    options()

#This function will display the word with missing character

def wordSubstitution():

    words = ["b_d","c_p","_at","c_b","_at"]

    ans = ["a","u","h","u","r"]

    i = 0

    while i < len(words):

        print("\n\nWhat is the missing letter: ",words[i])

        x = input()

        if(x == ans[i]):

            print("Congratulation...Correct Answer...\n")

        else:

            print("Oops!!!Wrong Answer...\n")

        i += 1

        inp = input("Continue(Y/N):")

        if(inp == "n" or inp == "N"):

            break;

    options()

#This function call will print the options and start the program

options()

Q4: Take a look at the series below: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55… 
To form the pattern, start by writing 1 and 1. Add them together to get 2. Add the last two numbers: 1+2 = 3.Continue adding the previous two numbers to find the next number in the series. These numbers make up the famed Fibonacci sequence: previous two numbers are added to get the immediate new number.
Ans: 

def fib(n):

   if n==1:

     print("1")

   elif n == 2:

     print("1, 1")

   elif n <= 0:

     print("Please enter positive number greater than 0")

   else:

     ft = 1

     st = 1

     print(ft,end=" ")

     print(st,end=" ")

     for i in range(2,n):

          nt = ft + st

          print(nt,end = " ")

          ft = st

          st = nt

 nt = int(input("How many terms you want in Fibinacci Series"))

 fib(nt)

Q5: Create a menu driven program using user defined functions to implement a calculator that performs the following: 
(a) Basic arithmetic operations(+,-,*,/) 
(b) log10(x),sin(x),cos(x)
Ans: 

(a)

ch ='y'

while (ch=='y' or ch == 'Y'):

   a = int(input("Enter first number: "))

   b = int(input("Enter second number: "))

   print("1. Addition")

   print("2. Subtraction")

   print("3. Multiplication")

   print("4. Division")

   print("5. Exit")

   n = int(input("Enter your choice:"))

   if n == 1:

        print("The result of addition : ", a + b)

   elif n == 2:

        print("The result of subtraction : ", a - b)

   elif n == 3:

        print("The result of multiplication :  ", a * b)

   elif n == 4:

        print("The result of division : " , a / b)

   elif n == 5:

        quit()

   else:

        print("Enter Correct Choice")

   ch = input("Do you want to continue(Y/N)")

(b)

import math

ch ='y'

while (ch=='y' or ch == 'Y'):

   x = int(input("Enter value of x : "))

   print("1. Log10(x)")

   print("2. Sin(x)")

   print("3. Cos(x)")

   print("4. Exit")

   n = int(input("Enter your choice:"))

   if n == 1:

        print("Log Value of ",(x),"is :",math.log10(x))

   elif n == 2:

        print("Sin(x) is : ",math.sin(math.radians(x)))

   elif n == 3:

        print("Cos(x) is : ",math.cos(math.radians(x)))

   elif n == 4:

        quit()

   else:

        print("Enter Correct Choice")

   ch = input("Do you want to continue(Y/N)")

Lab Exercises

Q1: Write a program to check the divisibility of a number by 7 that is passed as a parameter to the user defined function.
Ans:
 

def check(a):

   if a % 7 == 0:

     print("It is divisible by 7")

   else:

     print("It is not divisible by 7")

 check(343)

OUTPUT :

It is divisible by 7

Q2: Write a program that uses a user defined function that accepts name and gender (as M for Male, F for Female) and prefixes Mr/Ms on the basis of the gender. 
Ans: 

def check(n,g):

   if g == 'F' :

     print ("Name is : ", "Ms. "+ n)

   elif g == 'M' :

     print ("Name is : ", "Mr. "+ n)

   else :

     print("Pass only M or F as gender")

 check("Amit","M")

OUTPUT:

Name is :  Mr. Amit

Q3: Write a program that has a user defined function to accept the coefficients of a quadratic equation in variables and calculates its determinant. For example : if the coefficients are stored in the variables a,b,c then calculate determinant as b2-4ac. Write the appropriate condition to check determinants on positive, zero and negative and output appropriate result. 
Ans: 

import math

 def deter(a, b, c):

   D = b*2 - 4a*c

   if D > 0 :

        print("Roots of Quadratic equation are real and distinct")

   elif D == 0:

        print("Roots of Quadratic equation are real and equal")

   else:

        print("No real Roots of Quadratic equation")

 A = int(input("Enter Coefficient of square of x :"))

 B = int(input("Enter Coefficient of x :"))

 C = int(input("Enter Constant :"))

 deter(A,B,C)

Q4: ABC School has allotted unique token IDs from (1 to 600) to all the parents for facilitating a lucky draw on the day of their Annual day function. The winner would receive a special prize. Write a program using Python that helps to automate the task.(Hint: use random module) 
Ans: 

import random
win=random.randint(1, 600)
print("Winner is : Token Number : ", win)

Q5: Write a program that implements a user defined function that accepts Principal Amount, Rate, Time, Number of Times the interest is compounded  to calculate and displays compound interest. (Hint: CI=P*(1+r/n)nt)
Ans:

def compound(p, r, t, n):

   amt = p * (1 + r/100) ** n * t

   cint = amt - p

   print("Compound Interest is  : ",cint)

p = int(input("Enter the Principal"))

r  = int(input("Enter the Rate of interest"))

t  = int(input("Enter the time period in Years"))

n = int(input("Enter the number of times the interest is compounded"))

compound(p, r, t, n)

Q6: Write a program that has a user defined function to accept 2 numbers as parameters, if number 1 is less than number 2 then numbers are swapped and returned, i.e., number 2 is returned in place of number1 and number 1 is reformed in place of number 2, otherwise the same order is returned. 
Ans: 

def swap(n1, n2):

   if n1 < n2:

        n1, n2 = n2, n1

        return(n1,n2)

   else:

        return (n1,n2)

n1 = int(input("Enter First number"))

n2 = int(input("Enter Second number"))

x,y = swap(n1,n2)

print("After Swapping Result is")

print("First Number is  : ",x)

print("Second Number is  : ",y)

Q7: Write a program that contains user defined functions to calculate area, perimeter or surface area whichever is applicable for various shapes like square, rectangle, triangle, circle and cylinder. The user defined functions should accept the values for calculation as parameters and the calculated value should be returned. Import the module and use the appropriate functions. 
Ans: 

import math

def sqarea(s):

   return s * s 

def sqperi(s):   

   return 4 * s

def recarea(l,b):

   return l * b 

def recperi(l,b):   

   return 2 * (l+b)

def Rtriarea(b,h):

   return 1/2 * b * h

def triarea(a,b,c):

   s = (a + b + c )/2

   return math.sqrt(s * (s-a) * (s-b) * (s-c))

def cirarea(r):

   return math.pi * r ** 2

def cirperi(r):

   return 2 * math.pi * r

def cylTarea(r,h):

   return 2*math.pi * r * (r + h)

 def cylCarea(r,h):

   return 2 * math.pi * r * h

 print("1. Calculate Area of Square")

 print("2. Calculate Perimeter of Square")

 print("3. Calculate Area of Rectangle")

 print("4. Calculate Perimeter of Rectangle")

 print("5. Calculate Area of Right angle triangle")

 print("6. Calculate Area of Scalene Triangle")

 print("7. Calculate Area of Circle")

 print("8. Calculate Circumference of Circle")

 print("9. Calculate Total Surface Area of Cylinder")

 print("10. Calculate Curved Surface Area of Cylinder")

 ch = int(input("Enter Your Choice"))

 if ch == 1:

   s = int(input("Enter Side of Square"))

   ar = sqarea(s)

   print("Area of Square is  : ",ar)

 elif ch == 2:

     s = int(input("Enter Side of Square"))

     p = sqperi(s)

     print("Perimeter of Square is  : ",p)

 elif ch == 3:

     l = int(input("Enter the length of Rectangle"))

     b = int(input("Enter the breadth of Rectangle"))

     a = recarea(l,b)

     print("Area of Rectangle is  : ",a)

 elif ch == 4:

     l = int(input("Enter the length of Rectangle"))

     b = int(input("Enter the breadth of Rectangle"))

     p = recperi(l,b)

     print("Perimeter of Rectangle is  : ",p)

 elif ch == 5:

     b = int(input("Enter base of triangle"))

     h = int(input("Enter height of triangle"))

     a = Rtriarea(b,h)

     print("Area of triangle is  : ",a)

 elif ch == 6 :

     a = int(input("Enter First side of triangle"))

     b = int(input("Enter Second side of triangle"))

     c = int(input("Enter Third side of triangle"))

     ar = triarea(a,b,c)

     print("Area of triangle is  : ",ar)

 elif ch == 7 :

     r = int(input("Enter radius of Circle"))

     a = cirarea(r)

     print("Area of Circle is  : ",a)

 elif ch == 8:

     r = int(input("Enter radius of Circle"))

     cr = cirperi(r)

     print("Circumference of Circle is  : ",cr)

 elif ch == 9 :

     r = int(input("Enter radius of base of Cylinder"))

     h = int(input("Enter height of Cylinder"))

     tsa = cylTarea(r,h)

     print("Total Surface area of Cylinder is  : ",tsa)

 elif ch == 10:

     r = int(input("Enter radius of base of Cylinder"))

     h = int(input("Enter height of Cylinder"))

     csa = cylCarea(r,h)

     print("Curved Surface area of Cylinder is  : ",csa)

Q8: Write a program that creates a GK quiz  consisting of any five questions of your choice. The questions should be displayed randomly. Create a user defined function  score() to calculate the score of the quiz and another user defined function remark (scorevalue) that accepts the final score to display remarks as follows:
Functions NCERT Solutions | Computer Science for Class 11 - Humanities/ArtsAns:

This program can be easily written using the ‘list’ datatype.

Program:

import random

#this list will store the questions

quiz = ["What is the capital of Uttar Pradesh?","How many states are in North-East India?\nWrite the answer in words.","Which is India\'s largest city in terms of population?","What is the national song of India?","Which Indian state has the highest literacy rate?"]

#the 'ans' list will store the correct answer

ans = ["LUCKNOW","EIGHT","MUMBAI","VANDE MATARAM","KERALA"]

#This list will store the user input

userInp = []

#This list will store the sequence of question displayed

sequence = []

#This list will be storing remarks to display as per the score

remarks =["General knowledge will always help you. Take it seriously", "Needs to take interest", "Read more to score more", "Good", "Excellent", "Outstanding"]

#This user defined function will check the score

def score():

    s = 0;

    for i in range(0,5):

        #Users answer recorded at each index is compared with the answer(using sequence to check the index)

        if(userInp[i] == ans[sequence[i]]):

            s += 1

    return s

#This function will print the remarks as per the score

def remark(score):

    print(remarks[score])

#This function will display the question as per the index passed to it

#It will also store the user input and the sequence of the question asked

def disp(r):

    print(quiz[r])

    inp = input("Answer:")

    #User input is recorded after changing it to the upper case

    userInp.append(inp.upper())

    #The sequence of the question is also recorded, to compare answers later

    sequence.append(r)                    

i = 0;

while i < 5:

    #Random number is generated between 0 to 4

    r = random.randint(0, 4)

    # If that number is not already used, it will be passed to disp function to display the question on that index

    if(r not in sequence):

        i += 1                                    

        disp(r)

#calling score function to the correct answer by each user

s = score()

print("Your score :", s, "out of 5")

#calling remark function to print the remark as per the score

remark(s)

Output:

Which Indian state has the highest literacy rate?

Answer: kerala

Which is India's largest city in terms of population?

Answer:delhi

What is the national song of India?

Answer: vande mataram

What is the capital of Uttar Pradesh?

Answer: lucknow

How many states are in North-East India?

Write the answer in words.

Answer:three

Your score : 3 out of 5

Good

The document Functions NCERT Solutions | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
33 docs|11 tests

FAQs on Functions NCERT Solutions - Computer Science for Class 11 - Humanities/Arts

1. What are the different types of functions in mathematics?
Ans. In mathematics, there are several types of functions, including linear functions, quadratic functions, polynomial functions, rational functions, exponential functions, and logarithmic functions. Each type has its characteristics and graphs associated with them. For instance, linear functions have a constant rate of change and graph as straight lines, while quadratic functions graph as parabolas.
2. How do you determine if a relation is a function?
Ans. A relation is considered a function if every input (or x-value) is associated with exactly one output (or y-value). To determine this, you can use the vertical line test: if a vertical line intersects the graph of the relation at more than one point, then it is not a function.
3. What is the significance of the domain and range in functions?
Ans. The domain of a function is the set of all possible input values (x-values) for which the function is defined, while the range is the set of all possible output values (y-values) that the function can produce. Understanding the domain and range is crucial because it helps identify the limits of the function and ensures that calculations remain valid.
4. Can a function be both even and odd?
Ans. A function cannot be both even and odd at the same time. An even function satisfies the condition f(x) = f(-x) for all x in the domain, meaning its graph is symmetric about the y-axis. An odd function satisfies the condition f(-x) = -f(x), indicating that its graph is symmetric about the origin. If a function meets both conditions, it must be the zero function.
5. How do you find the inverse of a function?
Ans. To find the inverse of a function, follow these steps: first, replace the function notation f(x) with y. Then, swap the x and y variables. Next, solve the equation for y. Finally, replace y with f⁻¹(x) to denote the inverse function. It’s essential to check if the original function is one-to-one (meaning it has an inverse) before proceeding with these steps.
Related Searches

MCQs

,

Free

,

Functions NCERT Solutions | Computer Science for Class 11 - Humanities/Arts

,

Extra Questions

,

Previous Year Questions with Solutions

,

mock tests for examination

,

practice quizzes

,

Important questions

,

pdf

,

video lectures

,

Functions NCERT Solutions | Computer Science for Class 11 - Humanities/Arts

,

Sample Paper

,

Functions NCERT Solutions | Computer Science for Class 11 - Humanities/Arts

,

Viva Questions

,

study material

,

past year papers

,

Objective type Questions

,

ppt

,

shortcuts and tricks

,

Summary

,

Exam

,

Semester Notes

;