NCERT Solutions for Class 11 Commerce Computer science Chapter 7 Functions are provided here with simple step-by-step explanations. These solutions for Functions are extremely popular among class 11 Commerce students for Computer science Functions Solutions come handy for quickly completing your homework and preparing for exams. All questions and answers from the NCERT Book of class 11 Commerce Computer science Chapter 7 are provided here for you for free. You will also love the ad-free experience on Meritnation’s NCERT Solutions. All NCERT Solutions for class 11 Commerce Computer science are prepared by experts and are 100% accurate.

Page No 170:

Question 1:

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

b) from math import sqrt,ceil
    def calc():
        print cos(0)
    calc()  #function call


c) mynum = 9
    def add9():  
        mynum = mynum + 9
        print mynum
    add9()

d) def findValue(vall = 1.0, val2, val3):
        final = (val2 + val3)/ vall
        print(final)
    findvalue()  #function call


e) def greet():
          return("Good morning")
    greet() = message #function call

Answer:

a) There are two errors in the given program.

  1. The function “create” is defined using two arguments, 'text' and 'freq', but when the function is called in line number 4, only one argument is passed as a parameter. It should be written ‘create(5, 4)’ i.e with two parameters.
  2. The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(text)
b)  There are two errors in the given program.
  1. Only square root (sqrt) and ceiling (ceil) functions have been imported from the Math module, but here cosine function (cos) is used. ‘from math import cos’ should be written in the first line for the 'cos' function to work properly.
  2. The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(cos(0))’. 
c) There are two errors in the given program.
  1. In line 1, ‘mynum’ variable is defined which is a global variable. However, in line 3, a variable with the same name is defined again. Therefore, 'mynum' is treated as a new local variable. As no value has been assigned to it before the operation, hence, it will give an error. The local variable can either be changed to a different name or a value should be assigned to the local 'mynum' variable before line 3.
  2. The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(mynum)’.
d) There are three errors in the given program:
  1. The ‘function call’ in line 4 is calling an invalid function. 'findValue()' is different from 'findvalue()' as Python is case sensitive.
  2. 'findValue()' function needs the value of at least 2 arguments val2 and val3 to work, which is not provided in the function call.
  3. As 'vall' is already initialized as 'vall = 1.0', it is called 'Default parameter' and it should be always after the mandatory parameters in the function definition. i.e. def findValue(val2, val3, vall = 1.0) is the correct statement.
e) There is one error in the given program.
  1. The function 'greet()' returns value “Good Morning” and this value is assigned to the variable "message". Therefore, it should follow the rule of assignment where the value to be assigned should be on RHS and the variable ‘message’ should be on LHS. The correct statement in line 3 will be 'message = greet()'.

Page No 170:

Question 2:

How is math.ceil(89.7) different from math.floor(89.7)?

Answer:

Floor: The function 'floor(x)' in Python returns the largest integer not greater than x. i.e. the integer part from the variable.  
Ceil: The function 'ceil(x)' in Python returns the smallest integer not less than x i.e., the next integer on the RHS of the number line.

Hence, 'math.ceil(89.7)' will return 90 whereas 'math.floor(89.7)' will return 89.

Page No 170:

Question 3:

Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.

Answer:

'randint(a,b)' function will return a random integer within the given range as parameters.
'random()' function generates a random floating-point value in the range (0,1)
Therefore, to generate a random number between 1 and 5 we have to use the randint(1,5) function.

Note: 'randint()' is a part of  'random' module so, before using the same in the program, it has to be imported using the statement ‘from random import randint

Page No 170:

Question 4:

How is built-in function pow() function different from function math.pow()? Explain with an example.

Answer:

There are two main differences between built-in pow() function and math.pow() functions.

  • The built-in pow(x,y [,z]) function has an optional third parameter as modulo to compute x raised to the power of y and optionally do a modulo (% z) on the result. It is same as the mathematical operation: (x ^ y) % z. Whereas, math.pow() function does not have modulo functionality.
  • In math.pow(x,y) both 'x' and 'y' are first converted into 'float' data type and then the power is calculated. Therefore, it always returns a value of  'float' data type. This does not happen in the case of built-in pow function, however, if the result is a float data type, the output will be float else it will return integer data type.
Example: 
import math
print()
#it will return 25.0 i.e float
print(math.pow(5,2))
print()
#it will return 25 i.e int
print(pow(5,2))

Page No 170:

Question 5:

Using an example, show how a function in Python can return multiple values.  

Answer:

Program:
def myfun():
    return 1, 2, 3
a, b, c = myfun()
print(a)

print(b)
print(c)


OUTPUT:
1
2
3


NOTE: Although it looks like 'myfun()' returns multiple values, but actually a tuple is being created here. It is the comma that forms a tuple, not the parentheses, unless it is absolutely required there, such as in the case of a blank tuple.
 

Page No 170:

Question 6:

Differentiate between the following with the help of an example:

a) Argument and Parameter
b) Global and Local variable

Answer:

a) Argument and Parameter:

The parameter is variable in the declaration of a function. The argument is the actual value of this variable that gets passed to function when the function is called. 
Program:
def create (text, freq):
  for i in range (1, freq):
    print text
 create(5, 4)  #function call

Here, in line 1, 'text' and 'freq' are the parameters whereas, in line 4 the values '5'and '4' are the arguments.

b) Global and Local 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 function defined in the program. Any change made to the global variable will impact all the functions in the program where that variable is being accessed.

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. It exists only till the function executes. 

Program:
# Global Variable
a = "Hi Everyone!!"
def func():
    # Local variable
    b = "Welcome"
    # Global variable accessed
    print(a)        
    # Local variable accessed
    print(b)        
func()
# Global variable accessed, return Hi! Everyone
print(a)
# Local variable accessed, will give error: b is not defined
print(b)        

Page No 170:

Question 7:

Does a function always return a value? Explain with an example.

Answer:

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 are 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



 



Page No 171:

Question 1:

 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”.

Answer:

Points to consider:

i) As per the question, user-defined function login(uid,pwd)needs to be created which should display either “Login Successful” or “Account Blocked” after 3 wrong attempts. Therefore, a global variable should be used and its value should increase by 1 after every unsuccessful attempt. 
ii) If the username and password are correct, the program should display “Login Successful” and terminate.
iii) Once the check for the username/password is complete and if the credentials are incorrect, the program should check for the counter value, and if ‘counter’ is more than 2, the program should display “Account Blocked” and exit, otherwise it should give the option to enter the username and password again.

The flow chart for the program can be drawn as follows:



​

Program:

counter = 0
def logintry():

    ##This function will ask for username and password from the user and then pass the entered value to the login function
    username = input("Enter username: ")
    password = input("Enter password: ")
    login(username, password);
def login(uid,pwd):
    global counter
    if(uid=="ADMIN" and pwd =="St0rE@1"):
        print("Login Successful")
        return

    #If username and password is correct the program will exit
    else:
        counter += 1
        print("The username or password is incorrect")
    if(counter>2):

        # check counter value to see
        # the no.of incorrect attempts
        print("Account blocked")
        return
    else:

        # Calling logintry() function to # start the process again
        print("Try again")
        logintry()

# Start the program by calling the function
logintry()


OUTPUT:

When Incorrect values are entered:

Enter username:  user
Enter password: pwd
The username or password is incorrect
Try again

Enter username: uname
Enter password: password
The username or password is incorrect
Try again

Enter username: user
Enter password: password
The username or password is incorrect
Account blocked


When the correct values are entered:

Enter username: ADMIN
Enter password: St0rE@1
Login Successful

Page No 171:

Question 2:

 XYZ store plans to give a festival discount to its customers. The store management has decided to give discount on the following criteria: 
 

Shopping Amount Discount Offered
>=500 and <1000  5%
>=1000 and <2000  8%
>=2000  10%

An 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.


 

Answer:

In this program, the shopping amount needs to be compared multiple times, hence ‘elif’ function will be used after first ‘if’.
If the comparison is started from the highest amount, each subsequent comparison will eliminate the need to compare maximum value.

Program:
# function definition,
def discount(amount, member):
    disc = 0
    if amount >= 2000:
        disc = round((10 + member) * amount/100, 2)
    elif amount>= 1000:
        disc = round((8 + member) * amount/100, 2)
    elif amount >= 500:
        disc = round((5 + member) * amount/100, 2)
    payable = amount - disc
    print("Discount Amount: ",disc)
    print("Net Payable Amount: ", payable)

amount = float(input("Enter the shopping amount: "))
member = input("Is the Customer a member?(Y/N) ")
if(member == "y" or member == "Y"):
    #Calling the function with member value 5
    discount(amount,5)
else:

    #if customer is not a member, the value of member is passed as 0  
    discount(amount, 0)

OUTPUT:
Enter the shopping amount: 2500
Is the Customer a member?(Y/N) Y
Discount Amount:  375.0
Net Payable Amount:  2125.0


​​​Enter the shopping amount: 2500
Is the Customer a member?(Y/N) N
Discount Amount:  250.0
Net Payable Amount:  2250.0

Page No 171:

Question 3:

‘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.

Answer:

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()

 



Page No 172:

Question 4:

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. 

Answer:

The number of terms of the Fibonacci series can be returned using the program by getting the input from the user about the number of terms to be displayed.
The first two terms will be printed as 1 and 1 and then using ‘for’ loop (n - 2) times, the rest of the values will be printed.
Here, ‘fib’ is the user-defined function which will print the next term by adding the two terms passed to it and then it will return the current term and previous term. The return values are assigned to the variables such that the next two values are now the input terms.

Program:
def fib(x, y):
    z = x + y
    print(z, end=",")
    return y, z

n = int(input("How many numbers in the Fibonacci series do you want to display? "))

x = 1
y = 1

if(n <= 0):
    print("Please enter positive numbers only")
elif (n == 1):
    print("Fibonacci series up to",n,"terms:")
    print(x)
else:
    print("Fibonacci series up to",n,"terms:")
    print(x, end =",")
    print(y, end =",")
    for a in range(0, n - 2):
        x,y = fib(x, y)

    print()

​OUTPUT:
How many numbers in the Fibonacci series do you want to display? 5
Fibonacci series up to 5 terms:
1,1,2,3,5,

Page No 172:

Question 5:

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)

Answer:

a) Basic arithmetic operations

Program:
#Asking for the user input
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))

#printing the Menu
print("What would you like to do?")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

#Asking user about the arithmetic operation choice
n = int(input("Enter your choice:(1-4) "))

#Calculation as per input from the user
if n == 1:
    print("The result of addition:",(x + y))
elif n == 2:
    print("The result of subtraction:",(x - y))
elif n == 3:
    print("The result of multiplication:",(x * y))
elif n == 4:
    print("The result of division:",(x / y))
else:
    print("Invalid Choice")


b) log10(x), sin(x), cos(x)

Program:
import math

#Providing the Menu to Choose
print("What would you like to do?")
print("1. Log10(x)")
print("2. Sin(x)")
print("3. Cos(x)")

#Asking user about the choice
n = int(input("Enter your choice(1-3): "))

#Asking the number on which the operation should be performed
x = int(input("Enter value of x : "))
​#Calculation as per input from the user
if n == 1:
    print("Log of",(x),"with base 10 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)))
else:
    print("Invalid Choice")


​​

Page No 172:

Question 1:

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

Answer:

Program:
#defining the function to check the divisibility using modulus operator
def checkDivisibility(n):
    if n % 7 == 0:
        print(n, "is divisible by 7")
    else:
        print(n, "is not divisible by 7")

#asking user to provide value for a number
n = int(input("Enter a number to check if it is divisible by 7 : "))

#calling the function
checkDivisibility(n)


OUTPUT:
Enter a number to check if it is divisible by 7 : 7712838152
7712838152 is not divisible by 7

Page No 172:

Question 2:

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.

Answer:

Program:
#Defining a function which takes name and gender as input
def prefix(name,gender):
    if (gender == 'M' or gender == 'm'):
        print("Hello, Mr.",name)
    elif (gender == 'F' or gender == 'f'):
        print("Hello, Ms.",name)
    else:
        print("Please enter only M or F in gender")

#Asking the user to enter the name
name = input("Enter your name: ")

#Asking the user to enter the gender as M/F
gender = input("Enter your gender: M for Male, and F for Female: ")

#calling the function
prefix(name,gender)


OUTPUT:
Enter your name: John
Enter your gender: M for Male, and F for Female: M
Hello, Mr. John

Page No 172:

Question 3:

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.

Answer:

A discriminant can be positive, zero, or negative, and this determines the number of solutions to the given quadratic equation.

  • A positive discriminant indicates that the quadratic equation has two distinct real number solutions.
  • A discriminant with value zero indicates that the quadratic equation has a repeated real number solution.
  • A negative discriminant indicates that neither of the solutions of the quadratic equation is a real number.

Program:
#defining the function which will calculate the discriminant
def discriminant(a, b, c):
    d = b**2 - 4 * a * c
    return d

#asking the user to provide values of a, b, and c
print("For a quadratic equation in the form of ax^2 + bx + c = 0")
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))

#Calling the function to get the discriminant
det = discriminant(a,b,c)

#Printing the result based on the discriminant value
if (det > 0):
    print("The quadratic equation has two real roots.")
elif (det == 0):
    print("The quadratic equation has one real root.")
else:
    print("The quadratic equation doesn't have any real root.")


OUTPUT:
For a quadratic equation in the form of ax^2 + bx + c = 0
Enter the value of a: 2
Enter the value of b: 6
Enter the value of c: 3
The quadratic equation has two real roots.

Page No 172:

Question 4:

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)

Answer:

It is suggested in the question to use the 'random' module. Therefore, ‘randint()’ function can be used which will return a random integer within the given range as parameters. 

Program:
from random import randint

#Defining the function to generate the random number between 1 and 600
def generateRandom():
    print("The winner of the lucky draw is the parent with token id: ",randint(1, 600))
    print("")
    

#calling the function
generateRandom()


OUTPUT:
The winner of the lucky draw is the parent with token id:  313

Page No 172:

Question 5:

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)

Answer:

The hint given in the question has a mistake. The formula (P*(1+R/N)NT) will give us the amount, not the Compound Interest.

Program:
#Defining the function
def calculate(p,r,t,n=1):
    #calculating the amount
    amount = p * (1 + r/(n * 100))**(n * t)
    #calculating the compund interest and rounding it off to 2 decimal places
    ci = round(amount - p, 2)
    #displaying the value of the compound interest
    print("The compound interest will be ",ci)

#asking the principal, rate and time
p = float(input("Enter the principal amount: "))
r = float(input("Enter the rate of interest: "))
t = float(input("Enter total time: "))
n = int(input("Number of times the interest is compounded in a year\n(e.g.Enter 1 for yearly, 2 for half-yearly): "))
if(n > 365):
    calculate(p,r,t,n)

else:
    print("Maximum number of times an interest is compunded can not be more than 365")


​OUTPUT:
Enter the principal amount: 10000
Enter the rate of interest: 8
Enter total time:  5
Number of times the interest is compounded in a year
(e.g. Enter 1 for yearly, 2 for half-yearly): 4
The compound interest will be  4859.47



Page No 173:

Question 6:

 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.

Answer:

As per the question, the user-defined function should accept two numbers and then compare them before returning the values. Therefore, ‘if’ statement can be used inside the user-defined function to compare and return the values.
​
Program:
#defining a function to swap the numbers
def swapN(a, b):
    if(a < b):
        return b,a
    else:
        return a,b

#asking the user to provide two numbers
n1 = int(input("Enter Number 1: "))
n2 = int(input("Enter Number 2: "))

print("Returned value from function:")
#calling the function to get the returned value
n1, n2 = swapN(n1, n2)
print("Number 1:",n1," Number 2: ",n2)


OUTPUT:
Enter Number 1: 3
Enter Number 2: 4
Returned value from function: 
Number 1: 4  Number 2: 3

Page No 173:

Question 7:

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.

Answer:

As per the question, user-defined functions need to be created which accept the value and the calculated values should be returned. 
Also, these user-defined functions can be very simple or very complex depending upon the approach taken. Therefore, a simple approach has been taken here by defining user-defined functions for area, perimeter and surface area of various shapes separately.

The function list is as follows:

  • Square - Area, Perimeter
  • Rectangle - Area, Perimeter
  • Triangle - Area(base, height), Area(using all 3 sides), Perimeter
  • Circle - Area, Perimeter
  • Cylinder - Surface Area
Therefore, a total of 10 functions are defined. The first step will be to ask the shape on which the calculations is to be done and the second step will be to ask whether to calculate area, perimeter or both. 

Program:
import math

#Using formula area of square = square of side
def areaSquare(a):
    area = pow(a,2)        
    return area

# Using formula area(rectangle) = length * breadth
def areaRectangle(a, b):
    area = a * b            
    return area

# using herons formula when all three sides are given
def areaTriangleSide(a, b, c):
    s = (a + b + c) / 2        
    area = math.sqrt(s * (s - a) * (s - b) * (s - c))
    return round(area,2)

#Using formula area(triangle) = base * height / 2
def areaTrianglebh(a, b):
    area = (a * b) / 2    
    return round(area,2)

# Using formula area(circle) = πr^2
def areaCircle(r):
    area = (math.pi * r * r);    
    return round(area, 2)

# using formula area(cylinder) = 2πrh + 2πr^2
def surfaceAreaCylinder(r,h):
    area = (2 * math.pi * r * h) + (2 *math.pi * r * r)
    return round(area, 2)

# Using formula perimeter(square) = 4 * Side
def perimeterSquare(a):
    per = 4 * a
    return per

# Using formula perimeter(rectangle) = 2 (l + b)
def perimeterRectangle(a, b):
    per = 2 * ( a + b)    
    return per
def perimeterTriangle(a, b, c):
    per = a + b + c
    return per

# Using formula perimeter(circle) = 2πr
def perimeterCircle(r):
    per = (2 * math.pi * r )        
    return round(per, 2)

#Providing the menu to the user
print("On which geometric shape would you like to operate on?")
print("1. Square")
print("2. Rectangle")
print("3. Triangle")
print("4. Circle")
print("5. Cylinder")
inp = int(input("Enter your choice(1-5) : "))


#Calculating the values as per the geometric shape choice entered
if(inp == 1):
    print("Functions Available\n1.Area\n2.Perimeter\n3.Both Area and Perimeter")
    i = int(input("Enter your choice(1-3): "))
    a = float(input("Enter the side of square: "))
    if(i == 1):
        ret = areaSquare(a)
        print("Area of square with side",a," is ",ret)
    elif(i == 2):
        ret = perimeterSquare(a)
        print("Perimeter of square with side",a," is ",ret)
    elif(i == 3):
        ret = areaSquare(a)
        print("Area of square with side",a," is ",ret)
        ret = perimeterSquare(a)
        print("Perimeter of square with side",a," is ",ret)
    else:
        print("Invalid Choice")
elif(inp == 2):
    print("Functions Available\n1.Area\n2.Perimeter\n3.Both Area and Perimeter")
    i = int(input("Enter your choice(1-3): "))
    a = float(input("Enter the length of rectangle: "))
    b = float(input("Enter the breadth of rectangle: "))
    if(i == 1):
        ret = areaRectangle(a,b)
        print("Area of rectangle with sides",a,",",b," is ",ret)
    elif(i == 2):
        ret = perimeterRectangle(a,b)
        print("Perimeter of rectangle with sides",a,",",b," is ",ret)
    elif(i == 3):
        ret = areaRectangle(a,b)
        print("Area of rectangle with sides",a,",",b," is ",ret)
        ret = perimeterRectangle(a,b)
        print("Perimeter of rectangle with sides",a,",",b," is ",ret)
    else:
        print("Invalid Choice")
elif(inp == 3):
    print("Functions Available\n1.Area\n2.Perimeter\n3.Both Area and Perimeter")
    i = int(input("Enter your choice(1-3): "))
    if(i == 1):
        j = int(input("How do you want to calculate area?\n1.By using base and height\n2.By using all 3 sides:\n "))
        if(j == 1):
            a = float(input("Enter the base of triangle: "))
            b = float(input("Enter the height of triangle: "))
            ret = areaTrianglebh(a, b)
            print("Area of triangle with base:",a,"height:",b," is ",ret)
        elif(j == 2):
         a = float(input("Enter the side 1 of triangle: "))
         b = float(input("Enter the side 2 of triangle: "))
         c = float(input("Enter the side 3 of triangle: "))
         ret = areaTriangleSide(a, b, c)
         print("Area of triangle with sides:",a,",",b,",",c," is ",ret)
    elif(i == 2):
        a = float(input("Enter the side 1 of triangle: "))
        b = float(input("Enter the side 2 of triangle: "))
        c = float(input("Enter the side 3 of triangle: "))
        ret = perimeterTriangle(a, b, c)
        print("Perimeter of triangle with sides:",a,",",b,",",c," is ",ret)
    elif(i == 3):
        a = float(input("Enter the side 1 of triangle: "))
        b = float(input("Enter the side 2 of triangle: "))
        c = float(input("Enter the side 3 of triangle: "))
        ret = areaTriangleSide(a, b, c)
        print("Area of triangle with sides:",a,",",b,",",c," is ",ret)
        ret = perimeterTriangle(a, b, c)
        print("Perimeter of triangle with sides:",a,",",b,",",c," is ",ret)
    else:
        print("Invalid Choice")
elif(inp == 4):
    print("Functions Available\n1.Area\n2.Perimeter\n3.Both Area and Perimeter")
    i = int(input("Enter your choice(1-3): "))
    a = float(input("Enter the radius of circle: "))
    if(i == 1):
        ret = areaCircle(a)
        print("Area of the circle with radius",a," is ",ret)
    elif(i == 2):
        ret = perimeterCircle(a)
        print("Perimeter of the circle with radius",a," is ",ret)
    elif(i == 3):
        ret = areaCircle(a)
        print("Area of the circle with radius",a," is ",ret)
        ret = perimeterCircle(a)
        print("Perimeter of the circle with radius",a," is ",ret)
    else:
        print("Invalid Choice")
elif(inp == 5):
    print("Functions available for cylinder \nSurface Area")
    r = float(input("Enter the radius of cylinder: "))
    h = float(input("Enter the height of cylinder: "))
    ret = surfaceAreaCylinder(r, h)
    print("The surface area of cylinder with radius",r,"and height",h," is ",ret)
else:
    print("Please select correct value")


OUTPUT:
On which geometric shape would you like to operate on?
1. Square
2. Rectangle
3. Triangle
4. Circle
5. Cylinder
Enter your choice(1-5) : 1
Functions Available
1. Area
2. Perimeter
3. Both Area and Perimeter
Enter your choice(1-3): 1
Enter the side of square: 4
Area of square with side 4.0 is 16.0

Page No 173:

Question 8:

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:

Marks Remarks
5 Outstanding
4 Excellent
3 Good
2 Read more to score more
1 Needs to take interest
0 General knowledge will always help you. Take it seriously

Answer:

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



View NCERT Solutions for all chapters of Class 13