KnowledgeBoat Logo
|
OPEN IN APP

Chapter 12

Revision of Python

Class 10 - KIPS Robotics & AI



Activity 12.1

Question 1

Check that the following code snippet will execute properly or not. Justify your answer.

a=10 
b=25 
if a<b: 
print("a" is less than "b") 
else: 
print("b" is less than "a")

Answer

Output: No output

Justification: The given code snippet will not execute properly because of incorrect indentation. In Python, it is mandatory to indent the statements inside the if and else blocks. If the statements under the if condition are not indented, Python will display an IndentationError and the program will not run. Since the print() statements are not indented under if and else, the code is syntactically incorrect.

State True or False

Question 1

Python is popular due to its simplicity and strong libraries.

Answer

True

Reason — Python is considered to be the most appropriate language for beginners due to its simple and clearly defined syntax, and it has a huge standard library with ready-to-use modules.

Question 2

Python keywords can be used as variable names.

Answer

False

Reason — Python keywords should not be used as variable names.

Question 3

The '+' operator can be used for string concatenation.

Answer

True

Reason — The + operator is used to perform concatenation of two strings in Python.

Question 4

In Python, a variable name can consist of letters, digits, and underscore.

Answer

True

Reason — In Python, a variable name must start with a letter (capital or small) or an underscore (_), it can consist of letters, digits, and underscore only, variable names are case-sensitive, and Python keywords should not be used as variable names.

Question 5

The 'for' loop uses membership operator 'in'.

Answer

True

Reason — The for loop in Python uses the membership operator in to check the presence of a value in a sequence and to iterate over each element of that sequence one by one.

Question 6

The 'while' loop can be used to create an infinite loop.

Answer

True

Reason — The while loop executes as long as the given condition evaluates to True. If the condition never becomes False, the loop will continue to execute indefinitely, thereby creating an infinite loop.

Question 7

A loop inside a loop is called nested loop.

Answer

True

Reason — A loop that is written inside the body of another loop is called a nested loop, where one loop (inner loop) executes completely for each iteration of the outer loop.

Question 8

In Python, it is necessary to provide at least one argument in a function.

Answer

False

Reason — A function can take any number of arguments or none. If a function does not accept any arguments, the parentheses are left empty while defining the function. Therefore, it is not necessary to provide at least one argument in a Python function.

Question 9

The return statement in Python function cannot return multiple values.

Answer

False

Reason — In Python, a function is allowed to return more than one value using a single return statement by separating the values with commas.

Question 10

'*args' keyword allows to pass a variable number of arguments and arguments are stored in a tuple.

Answer

True

Reason — The *args keyword is used to pass a variable number of arguments to a function. The arguments passed using *args are automatically stored in a tuple, which can be accessed inside the function.

Select the correct option

Question 1

The NumPy library in Python is mainly used for:

  1. Machine learning
  2. Plotting
  3. Mathematical operations and data analysis
  4. Developing games

Answer

Mathematical operations and data analysis

Reason — NumPy is an important library that provides data manipulation, numerical computing, and statistical analysis facilities.

Question 2

Consider the following statement and answer the question:

data =("name": "Arjit", "age": 24)

This statement:

  1. Will create a dictionary
  2. Will create a tuple
  3. Will produce an error
  4. Will create a set

Answer

Will produce an error

Reason — A dictionary in Python must be defined using curly braces {} with key–value pairs separated by a colon. The given statement does not use curly braces, so it results in an error.

Question 3

The statement 5 % 4 will return ............... .

  1. 0
  2. 1
  3. 2
  4. 3

Answer

1

Reason — The modulus operator (%) returns the remainder after division of two numbers. When 5 is divided by 4, the remainder obtained is 1, hence the result is 1.

Question 4

Which of the following keywords is not used in conditional statements?

  1. if
  2. else
  3. elif
  4. go

Answer

go

Reason — The keywords used in Python conditional statements are if, else, and elif. The keyword go is not a conditional keyword in Python.

Question 5

Which logical operator(s) is/are used to combine multiple conditions in 'if' statement?

  1. and
  2. or
  3. not
  4. both a and b

Answer

both a and b

Reason — In Python, the logical operators and and or are used to combine multiple conditions in an if statement. The and operator checks if all conditions are true, while the or operator checks if any one of the conditions is true.

Question 6

In Python, what would be the condition to check if a value is not equal to 5?

  1. x =! 5
  2. x != 5
  3. x not= 5
  4. x == 5

Answer

x != 5

Reason — In Python, the != operator is the not equal to comparison operator. It is used to check whether two values are not equal. Therefore, the correct condition to check if a value is not equal to 5 is x != 5.

Question 7

From the following, which is not a comparison operator in Python?

  1. ==
  2. !=
  3. >=
  4. <>

Answer

<>

Reason — In Python, the valid comparison operators include ==, !=, and >=. The symbol <> is not a comparison operator in Python.

Question 8

Functions in programming:

  1. allow modular approach
  2. improve program readability
  3. help in code reusability
  4. All of these

Answer

All of these

Reason — Functions help in achieving modularity by breaking a large program into smaller manageable parts. They promote code reusability by allowing the same block of code to be used multiple times, and they improve program readability by organising code into logical blocks.

Question 9

The structure of function header in Python is:

  1. "def" keyword followed by the function name and parameters
  2. "func" keyword followed by the function name and parameters
  3. "def" keyword followed by the return type, function name and parameters
  4. "define" keyword followed by the function name and parameters

Answer

"def" keyword followed by the function name and parameters

Reason — A Python function header consists of the def keyword, followed by the function name, a list of parameters enclosed in parentheses, and ends with a colon.

Question 10

What would be output of the following code snippet?

def multiply(x, y=2): 
    return x*y 
result = multiply(5) 
print(result) 
  1. 5
  2. 10
  3. 2
  4. Error

Answer

10

Reason — Default arguments are used when a value is not provided during the function call. In the given function multiply(x, y=2), the parameter y has a default value of 2. When the function is called as multiply(5), the value 5 is assigned to x and the default value 2 is assigned to y. Therefore, the function returns 5 × 2 = 10, which is printed as the output.

Short answer type questions

Question 1

What do you understand by data type? List names of Python built-in data types.

Answer

A data type specifies the types of data that may be stored in variables as well as the actions that can be performed on them. The range of values that a variable may contain and the amount of memory required to store the value is also determined by the data type of the variable.

The built-in data types in Python are int, float, complex, bool, string, list, tuple, dictionary, and set.

Question 2

Write a Python program to declare and print 'list', 'dictionary', and 'tuple'.

Answer

# Declaring a list
my_list = [10, 20, 30, 40]
print("List:", my_list)

# Declaring a dictionary
my_dict = {"Name": "Amit", "Age": 15, "City": "Delhi"}
print("Dictionary:", my_dict)

# Declaring a tuple
my_tuple = (5, 10, 15, 20)
print("Tuple:", my_tuple)

Question 3

Write a Python program to demonstrate use of string operators.

Answer

a = "KIPS"
b = "Learning"

# String concatenation
print(a + b)

# String replication
print(a * 4)
Output
KIPSLearning
KIPSKIPSKIPSKIPS

Question 4

Explain the use of break statement in Python with the help of an example.

Answer

The break statement in Python is used to terminate a loop immediately and transfer the control outside the loop, even if the loop condition is still true.

Example:

for txt in "Python Language":
    if txt == "n":
        break
    print(txt)
print("The end")

Output:

P
y
t
h
o
The end

In this example, the loop iterates over each character of the string. When the character 'n' is encountered, the break statement is executed, which stops the loop immediately and the control comes out of the loop.

Question 5

Write a Python program to check that if a given number is even or odd.

Solution
num = int(input("Enter a number: "))

if num % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")
Output
Enter a number: 82
The number is even.

Enter a number: 51
The number is odd.

Long answer type questions

Question 1

Write a Python program to demonstrate arithmetic operators in Python.

Answer

a = 5
b = 2

add = a + b
sub = a - b
mul = a * b
div = a / b
mod = a % b
floordiv = a // b
power = a ** b

print("Addition:", add)
print("Subtraction:", sub)
print("Multiplication:", mul)
print("Division:", div)
print("Modulus:", mod)
print("Floor Division:", floordiv)
print("Exponent:", power)

Question 2

Explain relational operators in Python. Give one example for each.

Answer

Relational Operators in Python:

Operator NameOperatorDescriptionExample (a = 5, b = 2)Result
Equality (Is Equal to)==Returns true if a equals to ba == bFalse
Not Equal to!=Returns true if a is not equals to ba != bTrue
Greater than>Returns true if a is greater than ba > bTrue
Greater than or equal to>=Returns true if a is greater than b or a is equals to ba >= bTrue
Less than<Returns true if a is less than ba < bFalse
Less than or equal to<=Returns true if a is less than b or a is equals to ba <= bFalse

Question 3

Write a Python program to demonstrate the use of the if-elif-else statements.

Solution
a = 29
b = 23
c = 90

if b > a:
    print("b is greater than a")
elif c > a:
    print("c is greater than a")
elif c > b:
    print("c is greater than b")
else:
    print("invalid option")
Output
c is greater than a

Question 4

Describe user-defined functions in Python with the help of an example.

Answer

A user-defined function is a function that is defined by the user to perform a specific task. It enables the user to write their own code and reuse it whenever required. User-defined functions help in reducing repetition of code and make programs easier to understand and maintain.

In Python, a user-defined function is created using the def keyword, followed by the function name, parameters enclosed in parentheses, and a colon. The statements that define the task of the function form the function body.

Example:

def add(a, b):
    return a + b
result = add(5, 6)
print(result)

In the above example, the function add() is a user-defined function that takes two parameters and returns their sum using the return statement. This function can be called any number of times with different arguments.

Question 5

Distinguish between void functions and non-void functions with the help of an example.

Answer

Void functions are those functions that do not return any value. They may or may not contain a return statement, but even if the return statement is present, it returns no value. When such a function is called, it automatically returns None. Void functions are also called non-fruitful functions.

Example of a void function:

def msg():
    print("Welcome")
msg()

In this example, the function msg() only prints a message and does not return any value. Hence, it is a void (non-fruitful) function.

A non-void function is a function that returns a value using the return statement after execution. The value returned is passed back to the calling statement. Non-void functions are also known as fruitful functions.

Example of a non-void function:

def add(a, b):
    return a + b
result = add(4, 6)
print(result)

In this example, the function add() returns the sum of two numbers using the return statement. Hence, it is a non-void (fruitful) function.

Higher Order Thinking Skills (HOTS)

Question 1

What is the difference between division operator and floor division operator?

Answer

The division operator (/) divides two numbers and returns the result in decimal (floating-point) form, whereas the floor division operator (//) performs integer division and returns only the quotient without the decimal part.

Example:

  • 7 / 3 = 2.3333333333333335
  • 7 // 3 = 2

Thus, the division operator gives the exact result, while the floor division operator gives the integer quotient.

Question 2

Write a python program to print a pyramid using 'for' loop.

Solution
for i in range(1, 6):
    for j in range(i):
        print("*", end=" ")
    print()
Output
* 
* * 
* * *
* * * *
* * * * *

Question 3

Write a program to store marks of your class students and show their percentage.

Solution
n = int(input("Enter number of students: "))
total = 0

for i in range(n):
    marks = int(input("Enter marks of student: "))
    total = total + marks

percentage = (total / (n * 100)) * 100

print("Total Marks:", total)
print("Percentage:", percentage)
Output
Enter number of students: 4
Enter marks of student: 89
Enter marks of student: 78
Enter marks of student: 88
Enter marks of student: 67
Total Marks: 322
Percentage: 80.5

Question 4

Write a program to print the longest word in the given list of words.

Solution
n = int(input("Enter number of words: "))
words = []

for i in range(n):
    w = input("Enter word: ")
    words.append(w)

longest = words[0]

for w in words:
    count1 = 0
    for ch in w:
        count1 = count1 + 1

    count2 = 0
    for ch in longest:
        count2 = count2 + 1

    if count1 > count2:
        longest = w

print("The longest word is:", longest)
Output
Enter number of words: 4
Enter word: apple
Enter word: banana
Enter word: kiwi
Enter word: watermelon
The longest word is: watermelon

Question 5

Write a function which returns if a number passed as as argument is a perfect number or an Armstrong number.

Solution
def check_number(n):
    s = 0
    temp = n
    while temp > 0:
        d = temp % 10
        s = s + d ** 3
        temp = temp // 10

    p = 0
    for i in range(1, n):
        if n % i == 0:
            p = p + i

    if p == n:
        return "Perfect Number"
    elif s == n:
        return "Armstrong Number"
    else:
        return "Neither Perfect nor Armstrong"

num = int(input("Enter a number: "))
print(check_number(num))
Output
Enter a number: 153
Armstrong Number

Enter a number: 28
Perfect Number

Question 6

Write a function which takes a number and a list as arguments and counts the occurrence of that number in the given list.

Solution
def count_occurrence(num, lst):
    count = 0
    for x in lst:
        if x == num:
            count = count + 1
    return count

numbers = []
n = int(input("Enter number of elements: "))

for i in range(n):
    numbers.append(int(input("Enter number: ")))

num = int(input("Enter the number to count: "))

result = count_occurrence(num, numbers)
print("Occurrence:", result)
Output
Enter number of elements: 5
Enter number: 4
Enter number: 6
Enter number: 4
Enter number: 2
Enter number: 4
Enter the number to count: 4
Occurrence: 3
PrevNext