NCERT Solutions for Class 11 Computer Science : Functions

he chapter defines functions and types, therefore implementing them to equip the learner with skills for writing an efficient and structured program. If one wants more materials, then class 11 computer science chapter 7 pdf is always there to supplement your revision. It provides solutions and practice exercises for the students to fully understand the Functions. It has been disseminated—through this, the concept associated with the motto of Orchids International School: empower students with conceptual clarity of knowledge and its practical application domain so that they are able to face challenges in exams and daily life pertaining to computer science.

Download PDF For NCERT Solutions for Computer-Science Functions

The NCERT Solutions for Class 11 Computer Science : Functions are tailored to help the students master the concepts that are key to success in their classrooms. The solutions given in the PDF are developed by experts and correlate with the CBSE syllabus of 2023-2024. These solutions provide thorough explanations with a step-by-step approach to solving problems. Students can easily get a hold of the subject and learn the basics with a deeper understanding. Additionally, they can practice better, be confident, and perform well in their examinations with the support of this PDF.

Download PDF

Access Answers to NCERT Solutions for Class 11 Computer Science : Functions

Students can access the NCERT Solutions for Class 11 Computer Science : Functions. Curated by experts according to the CBSE syllabus for 2023–2024, these step-by-step solutions make Computer-Science much easier to understand and learn for the students. These solutions can be used in practice by students to attain skills in solving problems, reinforce important learning objectives, and be well-prepared for tests.

Functions

Question 1 :

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.

 


Question 2 :

Observe the following program carefully, and identify the error.

def create (text, freq): 

for i in range (1, freq):

print text

create (5)

#function call

 

Answer :

There are two errors in the given program.

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

b. The syntax of the 'print' function is incorrect. The correct syntax will be 'print(text)'.

 


Question 3 :

Observe the following program carefully, and identify the error.

from math import sqrt, ceil

def calc():

print cos(0)

calc()

        #function call

 

Answer :

There are two errors in the given program.

a. Only square root (sqrt) and ceiling (ceil) functions have been imported from the Math module, but here the cosine function (cos) is used. 'from math import cos' should be written in the first line for the 'cos' function to work properly.

b. The syntax of the 'print' function is incorrect. The correct syntax will be 'print(cos(

 


Question 4 :

Observe the following program carefully, and identify the error.

mynum = 9

def add9():

mynum mynum + 9

print mynum

add9()

#function call

 

Answer :

 There are two errors in the given program.

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

b. The syntax of the 'print' function is incorrect. The correct syntax will be 'print(mynum)'.

 


Question 5 :

Observe the following program carefully, and identify the error.

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

final = (val2 + val3)/ vall

print(final)

#function call

findvalue()

 

Answer :

There are three errors in the given program:

a. The 'function call' in line 4 is calling an invalid function. 'findValue()' is different from 'findvalue()' as Python is case sensitive.

b. 'findValue()' function needs the value of at least 2 arguments val2 and val3 to work, which is not provided in the function call.

c.  As 'vall' is already initialized as 'vall = 1.0', it is called 'Default parameter' and it should be always afte the mandatory parameters in the function definition. i.e. def findValue(val2, val3, vall = 1.0) is the correct statement.


Question 6 :

Observe the following program carefully, and identify the error:

def greet():

return("Good morning"

greet() = message

#function call

 

Answer :

There is one error in the given program.

a. The function 'greet()' returns the 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()'.


Question 7 :

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

Answer :

The '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'.

 


Question 8 :

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 the 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 the 'float' data type. This does not happen in the case of the built-in pow function, however, if

the result is a float data type, the output will be float else it will return an 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))

 


Question 9 :

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

 

Answer :

(a) Either receive the returned values in the form of a tuple variable.

For example:

def squared(x, y, z):

return x, y *y, z * z

t = squared (2,3,4)

print(t)

Tuple t will be printed as:

(4, 9, 16)

(b) Or you can directly unpack the received values of the tuple by specifying the same number of variables on the left-hand side of the assignment in the function call.

For example:

def squared(x, y, z):

return x* x, y * y, z * z

v1, v2, v3 = squared (2, 3, 4)

print ("The returned values are as under:")

print (v1, v2, v3)

Output is :-

4 9 16

 


Question 10 :

Differentiate between the following with the help of an example:

Argument and Parameter

 

Answer :

The parameter is a variable in the declaration of a function. The argument is the actual value of this variable that gets passed to the 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.

 


Question 11 :

Differentiate between the following with the help of an example:

Global and Local variable

 

Answer :

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

 


Question 12 :

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:

# 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

 


Question 13 :

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 a 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 the user ID as "ADMIN" and the password as "St0rE@1" On successful login, display the 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 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 passwor again.

Program:

counter = 0

def logintry():

##This function will ask for a 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 the username and password are 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

 


Question 14 :

Answer :

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 the customer is not a member, the value of member is passed as e

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

 


Question 15 :

The '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 the 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 ()

else:

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

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

 


Question 16 :

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: the 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 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 the 'for' loop (n - 2) times, the rest of the values will be printed.

Here, 'fib' is the user-defined function that will print the next term by adding the two terms passed to it, and then it will return the current term and the previous term. The return values are assigned to the variables such that the next two values are now the input terms.

# Function to generate the Fibonacci sequence up to 'n' terms

def fibonacci(n):

    # Step 1: Initialize the first two Fibonacci numbers

    a, b = 1, 1

    sequence = [a, b]

    # Step 2: Generate the remaining Fibonacci numbers until we reach 'n' terms

    for i in range(2, n):

        next_number = a + b

        sequence.append(next_number)

        # Update 'a' and 'b' to the next pair in the sequence

        a = b

        b = next_number

    return sequence

# Step 3: Input the number of terms to generate in the Fibonacci sequence

n = int(input("Enter the number of terms in the Fibonacci sequence: "))

# Step 4: Print the Fibonacci sequence

print(fibonacci(n))


Question 17 :

Create a menu-driven program using user-defined functions to implement a calculator that performs the following:

Basic arithmetic operations(+, -, *, /)

 

Answer :

 #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 the 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")


Question 18 :

Create a menu-driven program using user-defined functions to implement a calculator that performs the following:

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

 

Answer :

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


Question 19 :

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

 

Answer :

#defining the function to check the divisibility using the modulus operator

def checkDivisibility(n):

if n % 7 == 0:

print(n, "is divisible by 7")

else:

print(n, "is not divisible by 7")

#asking the 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

 


Question 20 :

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

 

Answer :

#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

 


Question 21 :

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

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 a value of 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.")

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.

 


Question 22 :

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, the '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

 


Question 23 :

Write a program that implements a user-defined function that accepts Principal Amount, Rate, Time, and 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 compound 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 compounded 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

 


Question 24 :

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 :

import math

# Functions for square

def square_area(side):

    return side * side

def square_perimeter(side):

    return 4 * side

# Functions for rectangle

def rectangle_area(length, width):

    return length * width

def rectangle_perimeter(length, width):

    return 2 * (length + width)

# Functions for circle

def circle_area(radius):

    return math.pi * radius * radius

def circle_circumference(radius):

    return 2 * math.pi * radius

# Functions for triangle

def triangle_area(base, height):

    return 0.5 * base * height

def triangle_perimeter(side1, side2, side3):

    return side1 + side2 + side3

# Main code to use the functions

shape = input("Enter the shape (square, rectangle, circle, triangle): ").lower()

if shape == "square":

    side = float(input("Enter the side length of the square: "))

    print("Area:", square_area(side))

    print("Perimeter:", square_perimeter(side))

elif shape == "rectangle":

    length = float(input("Enter the length: "))

    width = float(input("Enter the width: "))

    print("Area:", rectangle_area(length, width))

    print("Perimeter:", rectangle_perimeter(length, width))

elif shape == "circle":

    radius = float(input("Enter the radius: "))

    print("Area:", circle_area(radius))

    print("Circumference:", circle_circumference(radius))

elif shape == "triangle":

    base = float(input("Enter the base of the triangle: "))

    height = float(input("Enter the height of the triangle: "))

    side1 = float(input("Enter side 1: "))

    side2 = float(input("Enter side 2: "))

    side3 = float(input("Enter side 3: "))

    print("Area:", triangle_area(base, height))

    print("Perimeter:", triangle_perimeter(side1, side2, side3))

else:

    print("Invalid shape entered.")


Question 25 :

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, the '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

 


Question 26 :

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 :

import random

# List of questions and answers

questions = [

    {"question": "What is the capital of France?", "answer": "Paris"},

    {"question": "Which planet is known as the Red Planet?", "answer": "Mars"},

    {"question": "Who wrote 'Hamlet'?", "answer": "Shakespeare"},

    {"question": "What is the smallest prime number?", "answer": "2"},

    {"question": "Who was the first president of the United States?", "answer": "George Washington"}

]

# Function to calculate score

def score():

    random.shuffle(questions)  # Shuffle the questions randomly

    correct_answers = 0

    for i in range(5):

        print(f"Q{i+1}: {questions[i]['question']}")

        user_answer = input("Your answer: ")

        if user_answer.strip().lower() == questions[i]['answer'].strip().lower():

            correct_answers += 1

    return correct_answers

# Function to display remarks based on score

def remark(scorevalue):

    if scorevalue == 5:

        return "Outstanding"

    elif scorevalue == 4:

        return "Excellent"

    elif scorevalue == 3:

        return "Good"

    elif scorevalue == 2:

        return "Read more to score more"

    elif scorevalue == 1:

        return "Needs to take interest"

    else:

        return "General knowledge will always help you. Take it seriously"

# Main program

def main():

    final_score = score()  # Calculate the final score

    print(f"Your final score: {final_score}/5")

    print("Remark:", remark(final_score))  # Display the remark based on score

if __name__ == "__main__":

    main()

 


Enquire Now