KnowledgeBoat Logo
OPEN IN APP

Chapter 5

Conditional and Looping Constructs

Class 11 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

Statements in Python are executed sequentially while working with a sequence construct.

Question 2

Flow charts are diagrams that show the step-by-step solution to a given problem.

Question 3

Two types of looping statements are for and while.

Question 4

For loop is the best when the number of iterations is known.

Question 5

break statement terminates the loop.

Question 6

A loop that never ends is called an infinite loop.

Question 7

The iterative or looping construct means repetition of a set of statements depending upon a condition test.

Question 8

In nested loop inner loop must be terminated before the outer loop.

Question 9

continue statement abandons the current iteration of the loop.

Question 10

Header line begins with a keyword and ends with a colon.

State True or False

Question 1

Flow chart is not a graphical representation of steps to solve a given problem.

Answer

False

Reason — Flow chart is the pictorial representation of step-by-step solution to a given problem.

Question 2

if, elif, else are not block or compound statements.

Answer

False

Reason — The if, elif, and else are block or compound statements in Python.

Question 3

Every compound statement of Python has a header and indented body below the header.

Answer

True

Reason — In Python, every compound statement has a header and indented body below the header.

Question 4

Block is the group of consecutive statements having some indentation level.

Answer

True

Reason — In Python, a block is a group of consecutive statements that are intended to be executed together under a certain condition or scope.

Question 5

Python offers pass statement as empty statement.

Answer

True

Reason — The pass statement serves as a placeholder in Python. It is an empty statement that does nothing and acts as a dummy statement.

Question 6

To cancel the running of endless loop, you can press CTRL+C key any time during its endless repetition to stop it.

Answer

True

Reason — To cancel the running of endless loop, we can press CTRL+ C key any time during its endless repetition to stop it.

Question 7

Indentation while working with blocks is not necessary in Python.

Answer

False

Reason — In Python, indentation is necessary to define a block of code within control structures such as if, for, and while statements, as well as within functions.

Question 8

else if statement can be used in Python.

Answer

False

Reason — Python does not have an else if statement. Instead, Python uses the elif statement to chain multiple conditional statements together.

Question 9

The continue statement skips the current iteration in a loop and causes the next iteration of loop to take place.

Answer

True

Reason — The continue statement in Python is used within loops to skip the rest of the code inside the current iteration and immediately proceed to the next iteration of the loop.

Question 10

The else block for a loop executes only in the case of normal termination of the loop.

Answer

True

Reason — In Python, the else block associated with a for loop is executed when the loop terminates normally, meaning it has iterated over all items or reached its termination condition.

Question 11

Repeated execution of a set of statements is called iteration.

Answer

True

Reason — Iteration refers to the process of repeatedly executing a set of statements or a block of code for a specified number of times.

Multiple Choice Questions

Question 1

A graphical representation of an algorithm to solve a given problem:

  1. Flow chart
  2. Pie chart
  3. Bar chart
  4. Column chart

Answer

Flow chart

Reason — Flow chart is defined as a graphical representation of an algorithm to solve a given problem.

Question 2

Which of the following is not a decision-making statement?

  1. if-elif statement
  2. for statement
  3. if-else statement
  4. if statement

Answer

for statement

Reason — The for statement is not a decision-making statement in Python. Instead, the for loop statement is used to iterate/repeat itself over a range of values or a sequence.

Question 3

The symbol used to end the if statement:

  1. Semicolon (;)
  2. Hyphen ( - )
  3. Underscore ( _ )
  4. Colon (:)

Answer

Colon (:)

Reason — The symbol used to end the if statement is colon (:).

Question 4

Which of the following is a valid keyword?

  1. IF
  2. If
  3. if
  4. None of these

Answer

if

Reason — In Python, keywords are case-sensitive, meaning they must be written exactly as specified by the Python language. The valid keyword among the options provided is if.

Question 5

What does the following code print to console?

if True:
   print (101) 
else:
   print (202)
  1. 101
  2. 202
  3. 303
  4. 102

Answer

101

Reason — In Python, if True: will always evaluate to True, so the code block under the if branch will execute.

Question 6

Which of the following is not a loop statement in Python?

  1. do-while
  2. while
  3. for
  4. All of these

Answer

do-while

Reason — In Python, the do-while loop statement does not exist. The language provides only two primary loop constructs: the for loop and the while loop, which are used to handle different looping requirements.

Question 7

How many times will the following code be executed?

a = 5
while a > 0:
    print(a)
print("Thank You")
  1. 5 times
  2. Once
  3. Infinite
  4. None of these

Answer

Infinite

Reason — The code will result in an infinite loop because the value of a is never modified within the loop. The condition a > 0 will always be true, causing the print(a) statement to be executed indefinitely without changing the value of a.

Question 8

Which statement is used to iterate itself over a range of values or a sequence?

  1. if
  2. while
  3. do-while
  4. for

Answer

for

Reason — The for loop statement is used to iterate/repeat itself over a range of values or a sequence.

Question 9

In a Python program, a control structure:

  1. Directs the order of execution of the statements in the program
  2. Dictates what happens before the program starts and after it terminates
  3. Defines program-specific data structures
  4. Manages the input and output of control characters

Answer

Directs the order of execution of the statements in the program

Reason — A control structure in a Python program is used to direct the order of execution of the statements in the program. Control structures, such as loops and conditional statements, determine the flow of control in the program, allowing for the execution of code blocks based on certain conditions or repeatedly based on a loop condition.

Question 9

Find the output of the following Python program:

for x in range(1, 20, 3):
   print(x, end =',')
  1. 1,20,3,
  2. 1,4,7,10,13,16,19,
  3. 13,6,9,12,15,18,
  4. 20,40,60,80,100,

Answer

1,4,7,10,13,16,19,

Reason — The above code uses a for loop to iterate over a sequence of numbers generated by range(1, 20, 3). This range starts at 1, ends before 20, and increments by 3 in each step. During each iteration, the current value of x is printed followed by a comma due to the end=',' parameter in the print function. Therefore, the output is 1,4,7,10,13,16,19, showing the sequence of numbers separated by commas.

Question 11

What abandons the current iteration of the loop?

  1. continue
  2. break
  3. stop
  4. infinite

Answer

break

Reason — The break statement terminates the current loop, i.e., the loop in which it appears, and resumes execution at the next statement immediately after the end of that loop.

Question 12

An empty/null statement in Python is:

  1. go
  2. pass
  3. over
  4. ;

Answer

pass

Reason — The pass statement is an empty/null statement in Python that does nothing and acts as a dummy statement.

Question 13

In Python, which of the following will create a block in a compound statement?

  1. colon
  2. statements indented at a lower, same level
  3. indentation in any form
  4. {}

Answer

statements indented at a lower, same level

Reason — In Python, a block in a compound statement is created by indenting the statements to the same level.

Assertions and Reasons

Question 1

Assertion (A): When a set of statements is indented under the same block, starting from the same indentation, it is said to be a compound statement.

Reasoning (R): Compound Statement begins with a header ending with a colon (:) sign and the statements under the same indentation are marked as a block.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
A compound statement in Python is formed when multiple statements are grouped together under the same block of indentation. The header line begins with a keyword and ends with a colon (:). Subsequent statements that are indented under the same level are considered part of the block.

Question 2

Assertion (A): The conditional flow of control is implemented using if statement.

Reasoning (R): if statements can only be used to execute a single statement or a block of statements if a certain condition is true.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The if statement in Python allows conditional flow of control. It evaluates a condition and executes one or more statements based on whether the condition is true or false. If the condition evaluates to true, the statement block following the if statement (indented code) gets executed, otherwise, if the condition is false, that block is skipped, and the program continues with the next statement after the if block.

Question 3

Assertion (A): In an if-else statement, the if block checks the true part whereas the else checks for the false part.

Reasoning (R): if-else is a conditional construct where else block is mandatory.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
In an if-else statement, the if block checks the condition for the true part, whereas the else block executes if the condition is false. The else block in an if-else statement is not mandatory.

Question 4

Assertion (A): When a Python code is unable to accept an input, it results in runtime error.

Reasoning (R): Runtime error arises due to incorrect statement that results in no output.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
When a Python code is unable to accept an input, it results in a runtime error. Runtime errors arise due to issues that occur while the program is running, such as attempting to use invalid operations on data types. In contrast, syntax error arises due to incorrect statement that results in no output.

Question 5

Assertion (A): The break and continue statements are known as jump statements.

Reasoning (R): Jump statements are used only with looping constructs and not with conditional constructs.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In Python, break and continue are categorized as jump statements because they alter the flow of control in loops. Jump statements, such as break and continue, are used within loop constructs to control the flow of execution. Python does not have a switch-case conditional construct. Hence, in Python, jump statements are not used with conditional constructs.

Question 6

Assertion (A): The range() method is used with both for and while loops.

Reasoning (R): By default, the values for start and step are 0 (zero) and 1 (one), respectively.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is false but R is true.

Explanation
The range() function is used with for loops to iterate over a sequence of numbers, not with while loops. By default, the values for start and step are 0 (zero) and 1 (one), respectively.

Question 7

Assertion (A): The for loop is described as finite loop and while loop is described as unknown or indefinite iterative construct.

Reasoning (R): You cannot use while loop for menu-driven programs.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
The for loop is described as a finite loop because it iterates over a sequence of elements with a known length. The while loop is described as an indefinite iterative construct because it continues to execute as long as a condition is true, without a predetermined number of iterations. We can use a while loop for menu-driven programs to repeatedly display a menu and process user input until a certain condition is met.

Solutions to Unsolved Questions

Question 1

What are compound statements?

Answer

A compound statement is a statement which comprises of a group of statements. The compound statements usually execute when a condition is satisfied, or a code block is called directly or through a function call.

Question 2

What are jump statements?

Answer

Jump statements are used to unconditionally transfer program control to other parts within a program.

Question 3

What is nested loop? Explain with example.

Answer

A loop may contain another loop as a part of its body. This loop inside a loop is called a nested loop. Once the condition of outer loop is true, the control is transferred to the inner loop. The inner loop is terminated first and then the outer loop terminates.

For example,

for i in range(1, 4):
    for j in range(1, i+1):
        print(j, end = '')
    print()
Output
1
12
123

Here, range function will generate value 1, 2, 3 in the outer loop. The inner loop will run for each value of i used in outer loop. The value of outer loop variable will change only after the inner loop completely terminates.

Question 4

What is the significance of updating loop control variable in while statements?

Answer

Updating the loop control variable in while statements is essential to prevent infinite loops. If the loop control variable is not updated within the loop body, the condition may always evaluate to true, causing the loop to run indefinitely.

Question 5

Construct a logical expression to represent each of the following conditions:

(a) Mark is greater than or equal to 100 but less than 70.

(b) Num is between 0 and 5 but not equal to 2.

(c) Answer is either 'N' OR 'n'.

(d) Age is greater than or equal to 18 and gender is male.

(e) City is either 'Kolkata' or 'Mumbai'.

Answer

(a) (marks >= 100) and (marks < 70)

(b) (num > 0) and (num < 5) and (num != 2)

(c) (answer == 'N') or (answer == 'n')

(d) (age >= 18) and (gender == 'male')

(e) (city == 'Kolkata') or (city == 'Mumbai')

Question 6

Find error in the following code (if any) and correct it by rewriting the code and underline the corrections:

code=input ("Enter season code : ")
if code=w:
   print "winter season" 
elif code==r:
   PRINT "rainy season" 
else:
   Print "summer season"

Answer

code = input("Enter season code : ")
if code=w: #Error 1
   print "winter season" #Error 2
elif code==r: #Error 3
   PRINT "rainy season" #Error 4 
else:
   Print "summer season" # Error 5

Error 1 — The assignment operator '=' is used instead of equality operator '==' in the if statement and the string 'w' should be enclosed in quotes.

Error 2 — Parentheses around the print statement are missing.

Error 3 — String 'r' should be enclosed in quotes.

Error 4 — The print statement should be in lowercase letters and there should be parentheses around the print statement.

Error 5 — The print statement should be in lowercase letters and there should be parentheses around the print statement.

The corrected code is :

code = input("Enter season code: ")
if code == "w":
   print("winter season") 
elif code == "r":  
   print("rainy season") 
else:
   print("summer season")  

Question 7(i)

Write the output of the following:

for i in '123':
    print("guru99",i,)

Answer

Output
guru99 1
guru99 2
guru99 3
Explanation

The for loop iterates over each character in the string '123'. For each character, it prints "guru99" followed by the character. The comma after i in the print() function ensures a space between "guru99" and each character.

Question 7(ii)

Write the output of the following:

for i in [100,200,300] :
   print (i)

Answer

Output
100
200
300
Explanation

The above code iterates through each element in the list [100, 200, 300] using a for loop. During each iteration, it prints the current element i.

Question 7(iii)

Write the output of the following:

for j in range (10,6,-2) :
   print (j*2)

Answer

Output
20
16
Explanation

1. range(10, 6, -2): This generates a sequence of numbers starting from 10 (inclusive) and decreases by 2 each time, stopping before it reaches 6 (exclusive).

The general form of the range function is range(start, stop, step), where:

  • start is the starting number of the sequence.
  • stop is the endpoint (the number is not included in the sequence).
  • step specifies the increment (or decrement, if negative) between each number in the sequence.

2. The sequence generated by range(10, 6, -2) is:

  • Start at 10.
  • Decrement by 2: 10 - 2 = 8.
  • The next decrement would be 8 - 2 = 6, but 6 is not included as it is exclusive.

So, the sequence generated is: 10, 8.

3. for j in range(10, 6, -2):: The for loop iterates over each number in the sequence generated by the range function.

4. print(j * 2): This prints the value of j multiplied by 2 for each iteration.

Let’s analyze the loop iteration by iteration:

First iteration (j = 10):

print(10 * 2)

This prints:

20

Second iteration (j = 8):

print(8 * 2)

This prints:

16

Putting it all together, the full output will be:

20
16

Question 7(iv)

Write the output of the following:

for x in range (1, 6) :
   for y in range (1, x+1):
      print (x, ' ', y)

Answer

Output
1   1
2   1
2   2
3   1
3   2
3   3
4   1
4   2
4   3
4   4
5   1
5   2
5   3
5   4
5   5
Explanation

Below is the detailed explanation of this code:

1. Outer Loop: for x in range(1, 6):

  • This loop iterates over the range of numbers starting from 1 up to but not including 6. So, x will take on the values: 1, 2, 3, 4, 5.

2. Inner Loop: for y in range(1, x + 1):

  • For each value of x in the outer loop, y will iterate over the range of numbers starting from 1 up to and including x (since x + 1 is exclusive).

3. print(x, ' ', y)

  • This prints the current values of x and y separated by a space.

Let’s analyze the loops iteration by iteration.

Outer loop (x values ranging from 1 to 5):

When x = 1:

  • The inner loop range(1, 2) results in y taking values: 1.
  • Output:
    1   1
    

When x = 2:

  • The inner loop range(1, 3) results in y taking values: 1, 2.
  • Output:
    2   1
    2   2
    

When x = 3:

  • The inner loop range(1, 4) results in y taking values: 1, 2, 3.
  • Output:
    3   1
    3   2
    3   3
    

When x = 4:

  • The inner loop range(1, 5) results in y taking values: 1, 2, 3, 4.
  • Output:
    4   1
    4   2
    4   3
    4   4
    

When x = 5:

  • The inner loop range(1, 6) results in y taking values: 1, 2, 3, 4, 5.
  • Output:
    5   1
    5   2
    5   3
    5   4
    5   5
    

Putting all these outputs together, we get:

1   1
2   1
2   2
3   1
3   2
3   3
4   1
4   2
4   3
4   4
5   1
5   2
5   3
5   4
5   5

Question 7(v)

Write the output of the following:

for x in range (10, 20):
   if (x == 15):
      break
   print(x)

Answer

Output
10
11
12
13
14
Explanation

The code starts a for loop where x iterates over the range from 10 to 19. Within each iteration, it checks if x is equal to 15. If true, the break statement exits the loop. Therefore, the loop prints numbers from 10 to 14, each on a new line.

Question 7(vi)

Write the output of the following:

for x in range (10, 20):
   if (x % 2 == 0):
      continue
   print (x)

Answer

Output
11
13
15
17
19
Explanation

Below is the detailed explanation of this code:

  1. for x in range(10, 20): → This loop iterates over the range of numbers starting from 10 (inclusive) up to but not including 20 (exclusive). So, x will take on the values: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19.

  2. if x % 2 == 0: → For each value of x, this condition checks if x is an even number. The modulus operator % returns the remainder of x divided by 2. If the remainder is 0, x is even.

  3. continue → If the condition x % 2 == 0 is true (i.e., x is even), the continue statement is executed. This statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.

  4. print(x) → This line prints the value of x if it is not even (i.e., if the continue statement is not executed).

Let’s analyze the loop iteration by iteration:

  • When x = 10:

    • 10 % 2 == 0 is true.
    • continue is executed, so print(x) is skipped.
  • When x = 11:

    • 11 % 2 == 0 is false.
    • print(x) outputs:
      11
      
  • When x = 12:

    • 12 % 2 == 0 is true.
    • continue is executed, so print(x) is skipped.
  • When x = 13:

    • 13 % 2 == 0 is false.
    • print(x) outputs:
      13
      
  • When x = 14:

    • 14 % 2 == 0 is true.
    • continue is executed, so print(x) is skipped.
  • When x = 15:

    • 15 % 2 == 0 is false.
    • print(x) outputs:
      15
      
  • When x = 16:

    • 16 % 2 == 0 is true.
    • continue is executed, so print(x) is skipped.
  • When x = 17:

    • 17 % 2 == 0 is false.
    • print(x) outputs:
      17
      
  • When x = 18:

    • 18 % 2 == 0 is true.
    • continue is executed, so print(x) is skipped.
  • When x = 19:

    • 19 % 2 == 0 is false.
    • print(x) outputs:
      19
      

Putting all these outputs together, the full output will be:

11
13
15
17
19

Question 8

Write the output of the following program on execution if x = 50:

if x > 10:
   if x > 25:
      print ( 'ok' )
      if x > 60:
           print ( 'good' )
      elif x > 40:
           print ( 'average' )
      else:
           print ('no output')

Answer

Output
ok
average
Explanation
  1. if x > 10:

    • The condition checks if x is greater than 10.
    • Since x = 50, which is greater than 10, this condition is true.
  2. Nested if x > 25:

    • Since the outer condition is true, the program proceeds to this nested condition, which checks if x is greater than 25.
    • Since x = 50, which is greater than 25, this condition is also true.
    • Consequently, it prints ok
  3. Nested if x > 60:

    • After printing 'ok', the program checks this nested condition, which verifies if x is greater than 60.
    • Since x = 50, which is not greater than 60, this condition is false.
    • Therefore, the program proceeds to the elif part.
  4. Nested elif x > 40:

    • This condition checks if x is greater than 40.
    • Since x = 50, which is greater than 40, this condition is true.
    • Consequently, it prints average
  5. The else block

    • The else block is not executed because the elif x > 40: condition was true.

Question 9

Write the output of the following code:

for i in range (2) :
  for j in range (1) :
   if i+2 == j:
      print ("+",end=" ") 
   else:
      print ("o",end=" ")

Answer

Output
o o
Explanation

Let’s break down the code step-by-step:

  1. Outer Loop: for i in range(2): → This loop iterates over the range of numbers starting from 0 up to but not including 2. So, i will take on the values: 0, 1.

  2. Inner Loop: for j in range(1): → For each value of i in the outer loop, j will iterate over the range of numbers starting from 0 up to but not including 1. So, j will take on the only value: 0.

  3. if i + 2 == j: → This condition checks if i + 2 is equal to j.

  4. print("+", end=" ") → If the condition i + 2 == j is true, this statement prints a "+", followed by a space, without moving to a new line.

  5. print("o", end=" ") → If the condition i + 2 == j is false, this statement prints an "o", followed by a space, without moving to a new line.

Let’s analyze the loops iteration by iteration:

  • First iteration of the outer loop (i = 0):
    • Inner loop (j = 0):
      • i + 2 == j becomes 0 + 2 == 0, which is 2 == 0, is false.
      • Therefore, the else block is executed, and the output is o
  • Second iteration of the outer loop (i = 1):
    • Inner loop (j = 0):
      • i + 2 == j becomes 1 + 2 == 0, which is 3 == 0, is false.
      • Therefore, the else block is executed, and the output is o

So, combining the outputs of all iterations, the full output will be:

o o 

Each "o" is followed by a space, and there is no new line between them due to the end=" " parameter in the print function.

Question 10(a)

Give the output of the following when num1 = 4, num2 = 3, num3 = 2.

num1 += num2 + num3
print(num1)

Answer

Output
9
Explanation

In the above code, num1 += num2 + num3 is a shorthand notation for num1 = num1 + num2 + num3.

Given,

num1 = 4
num2 = 3
num3 = 2

First, the expression num2 + num3 is evaluated:

num2 + num3 = 3 + 2 = 5

Now the expression becomes:

num1 = num1 + 5

which translates to:

num1 = 4 + 5 = 9

Question 10(b)

Give the output of the following when num1 = 4, num2 = 3, num3 = 2.

num1 = num1 ** (num2 + num3)
print (num1)

Answer

Output
1024
Explanation

In the given code, num1 = num1 ** (num2 + num3) calculates the result of raising num1 to the power of the sum of num2 and num3. The expression becomes 4 ** (3 + 2), which simplifies to 4 ** 5. Evaluating 4 ** 5 results in 1024, so the output of print(num1) is 1024.

Question 10(c)

Give the output of the following when num1 = 4, num2 = 3, num3 = 2.

num1 **= num2 + c
print (num1)

Answer

There is an error in the given code because the variable c is not defined. This will raise a NameError at runtime.

Question 10(d)

Give the output of the following when num1 = 4, num2 = 3, num3 = 2.

num1 = '5' + '5'
print (num1)

Answer

Output
55
Explanation

The expression '5' + '5' performs string concatenation as they are enclosed in quotes. Therefore, '5' and '5' are concatenated to form the string '55', which is then assigned to num1. The print(num1) statement outputs the string '55'.

Question 10(e)

Give the output of the following when num1 = 4, num2 = 3, num3 = 2.

print(4.00 / (2.0+2.0))

Answer

Output
1.0
Explanation

1. Evaluate the expression inside the parentheses first:

2.0 + 2.0

This calculation is straightforward:

2.0 + 2.0 = 4.0

2. Perform the division operation:

4.00 / 4.0 = 1.0

3. Print the result:

print(1.0)

Therefore, the output of the given code snippet is:

1.0

Question 10(f)

Give the output of the following when num1 = 4, num2 = 3, num3 = 2.

num1 = 2 + 9 * ((3*12)-8)/10
print(num1)

Answer

Output
27.2
Explanation
num1 = 2 + 9 * ((3*12)-8)/10

Let's calculate this step by step, following the precedence of operators in Python:

1. Evaluate the innermost parentheses first:

3 * 12 = 36

2. Replace and continue evaluating inside the parentheses:

((3*12)-8) => (36 - 8) = 28

3. Now, evaluate the multiplication and division:

9 * 28 = 252

4. Continue with dividing by 10:

252 / 10 = 25.2

5. Finally, add 2:

2 + 25.2 = 27.2

The print(num1) statement outputs 27.2

Question 10(g)

Give the output of the following when num1 = 4, num2 = 3, num3 = 2.

num1 = float(10)
print(num1)

Answer

Output
10.0
Explanation

The float(10) function converts the integer 10 to the floating-point number 10.0. Therefore, num1 is assigned the value 10.0.

Question 10(h)

Give the output of the following:

num1 = int(float('3.14'))
print(num1)

Answer

Output
3
Explanation

The expression float('3.14') converts the string '3.14' to the floating-point number 3.14. The int() function then converts 3.14 to the integer 3 by truncating the decimal part. Thus, num1 is assigned the value 3, and print(num1) outputs 3.

Question 10(i)

Give the output of the following:

print (10 != 9 and 20 >= 20) 

Answer

Output
True
Explanation

The expression 10 != 9 and 20 >= 20 evaluates to True because both conditions separated by the and operator are true. Specifically, 10 != 9 is true because 10 is not equal to 9, and 20 >= 20 is true because 20 is equal to 20.

Question 10(j)

Give the output of the following:

print(5 % 10 + 10 < 50 and 29 <= 29)

Answer

Output
True
Explanation

In the expression 5 % 10 + 10 < 50 and 29 <= 29, according to operator precedence, 5 % 10 calculates to 5, then 5 + 10 equals 15. Next, 15 < 50 evaluates to True. Separately, 29 <= 29 also evaluates to True. The and operator then combines these results. Since both conditions are True, the and operator yields True, which is printed.

Question 11

What is the difference between else and elif constructs of if statement?

Answer

The else statement is a default condition that executes when the preceding if and elif (if any) conditions evaluate to False. It does not take any conditions and is written simply as else:, followed by an indented block of code. On the other hand, elif is used to check additional conditions after the initial if statement. If the if condition is False, Python evaluates the elif condition. It is followed by a condition and ends with a colon (:), followed by a block of code.

Question 12(a)

Find the output of the following program segment:

for i in range(20, 30, 2):                        
   print(i)                                         

Answer

Output
20
22
24
26
28
Explanation

Below is a detailed explanation of this code:

  1. range(20, 30, 2): This generates a sequence of numbers starting from 20 (inclusive) up to but not including 30 (exclusive), incrementing by 2 each time.
    The general form of the range function is range(start, stop, step),where:

    • start is the starting number of the sequence.
    • stop is the endpoint (the number is not included in the sequence).
    • step specifies the increment between each number in the sequence.
  2. for i in range(20, 30, 2):: The for loop iterates over each number generated by the range function and assigns it to the variable i during each iteration.

  3. print(i): This prints the current value of i for each iteration.

Let's list the numbers generated by range(20, 30, 2):

  • Start at 20.
  • Increment by 2: 20 + 2 = 22.
  • Increment by 2: 22 + 2 = 24.
  • Increment by 2: 24 + 2 = 26.
  • Increment by 2: 26 + 2 = 28.
  • The next increment would be 28 + 2 = 30, but 30 is not included as the stop parameter is exclusive of the value.

Therefore, the sequence of numbers is: 20, 22, 24, 26, 28.

Question 12(b)

Find the output of the following program segment:

country = 'INDIA'
for i in country:
   print (i)

Answer

Output
I
N
D
I
A
Explanation

Here's the detailed explanation:

1. String Assignment:

country = 'INDIA'

This line assigns the string 'INDIA' to the variable country.

2. for i in country:: The for loop iterates over each character in the string country. The variable i will take on the value of each character in the string one at a time.

3. print(i): This prints the current character stored in the variable i for each iteration.

Let’s analyze the loop iteration by iteration:

  • In the first iteration, i is 'I', so print(i) outputs: I.
  • In the second iteration, i is 'N', so print(i) outputs: N.
  • In the third iteration, i is 'D', so print(i) outputs: D.
  • In the fourth iteration, i is 'I', so print(i) outputs: I.
  • In the fifth iteration, i is 'A', so print(i) outputs: A.

Putting it all together, the output will be each character of the string 'INDIA' printed on a new line:

I
N
D
I
A

Question 12(c)

Find the output of the following program segment:

i = 0; sum = 0
while i < 9:
      if i % 4 == 0:
         sum = sum + i
      i = i + 2
print (sum)

Answer

Output
12
Explanation

Let's break down the code step-by-step:

1. Initial Assignments:

i = 0
sum = 0

Two variables are initialized: i is set to 0, and sum is set to 0.

2. while i < 9: → This loop continues to execute as long as i is less than 9.

3. Inside the while loop:

  • First iteration (i = 0):

    • if i % 4 == 0:0 % 4 equals 0, so the condition is true.
    • sum = sum + isum is updated to sum + 0, which is 0 + 0 = 0.
    • i = i + 2i is updated to 0 + 2 = 2.
  • Second iteration (i = 2):

    • if i % 4 == 0:2 % 4 equals 2, so the condition is false.
    • The value of sum remains unchanged.
    • i = i + 2i is updated to 2 + 2 = 4.
  • Third iteration (i = 4):

    • if i % 4 == 0:4 % 4 equals 0, so the condition is true.
    • sum = sum + isum is updated to sum + 4, which is 0 + 4 = 4.
    • i = i + 2i is updated to 4 + 2 = 6.
  • Fourth iteration (i = 6):

    • if i % 4 == 0:6 % 4 equals 2, so the condition is false.
    • The value of sum remains unchanged.
    • i = i + 2i is updated to 6 + 2 = 8.
  • Fifth iteration (i = 8):

    • if i % 4 == 0:8 % 4 equals 0, so the condition is true.
    • sum = sum + isum is updated to sum + 8, which is 4 + 8 = 12.
    • i = i + 2i is updated to 8 + 2 = 10.
  • Sixth iteration (i = 10):

    • The loop condition while i < 9: is no longer true (10 is not less than 9), so the loop terminates.

4. print(sum) → After exiting the loop, the value of sum is printed.

Summarizing all updates to sum:

  • After the first iteration, sum = 0.
  • After the third iteration, sum = 4.
  • After the fifth iteration, sum = 12.

Therefore, the output of the code is:

12

Question 13

Write a program to check if the number is positive or negative and display an appropriate message.

Solution
number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
else:
    print("The number is negative.")
Output
Enter a number: 4
The number is positive.

Enter a number: -6
The number is negative.

Question 14

WAP to display even numbers between 10 and 20.

Solution
for num in range(10, 21):
    if num % 2 == 0:
        print(num)
Output
10
12
14
16
18
20

Question 15

WAP to perform all the mathematical operations of a calculator.

Solution
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
    result = num1 + num2
    print(num1, "+", num2, "=", result)
elif choice == '2':
    result = num1 - num2
    print(num1, "-", num2, "=", result)
elif choice == '3':
    result = num1 * num2
    print(num1, "*", num2, "=", result)
elif choice == '4':
    if num2 != 0:
        result = num1 / num2
        print(num1, "/", num2, "=", result)
    else:
        print("Division by zero is not allowed.")
else:
    print("Invalid input")
Output
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter first number: 23
Enter second number: 45
23.0 + 45.0 = 68.0
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 2
Enter first number: 48
Enter second number: 23
48.0 - 23.0 = 25.0
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 3
Enter first number: 3
Enter second number: 6
3.0 * 6.0 = 18.0
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 4
Enter first number: 245
Enter second number: 5
245.0 / 5.0 = 49.0

Question 16

Write a program to accept a number and display the factorial of that number.

Solution
number = int(input("Enter a number: "))
factorial = 1
if number < 0:
    print("Factorial is not defined for negative numbers.")
else:
    for i in range(1, number + 1):
        factorial *= i
    print("The factorial of", number, "is", factorial)
Output
Enter a number: 5
The factorial of 5 is 120


Question 17

Write a function to display prime numbers below 30.

Solution
def prime_numbers():
    for num in range(2, 30):
        for i in range(2, num):
            if num % i == 0:
                break
        else:
                print(num)
    
prime_numbers()
Output
2
3
5
7
11
13
17
19
23
29

Question 18

WAP to print the sum of the series 1 - x1/2! + x2/3! - x3/4! ............... xn/(n + 1)! — exponential series.

Solution
x = int(input("Enter x: "))
n = int(input("Enter n: "))
sum_series = 1  
sign = -1 

for i in range(1, n + 1):
    fact = 1
    for j in range(1, i + 2):
        fact *= j
    
    term = sign * (x ** i) / fact 
    sum_series += term
    sign *= -1 

print("Sum =", sum_series)
Output
Enter x: 2
Enter n: 3
Sum = 0.3333333333333333

Question 19

WAP to print the sum of the series 1 - x2/4! + x3/6! - x4/8! + x5/10! ............... xn/(2n)! — exponential series.

Solution
x = int(input("Enter x: "))
n = int(input("Enter n: "))

sum_series = 1  
sign = -1 

for i in range(2, n + 1):
    fact = 1
    for j in range(1, 2 * i + 1):
        fact *= j
    
    term = sign * (x ** i) / fact
    sum_series += term
    sign *= -1 

print("Sum =", sum_series)
Output
Enter x: 2
Enter n: 3
Sum = 0.8444444444444444

Question 20

WAP to display the sum of the given series:

Sum = 1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3.....n)

Solution
n = int(input("Enter the value of n: "))

sum = 0
for i in range(1, n + 1):
    for j in range(1, i + 1):
        sum += j

print("The sum of the series is:", sum)
Output
Enter the value of n: 4
The sum of the series is: 20

Question 21(a)

WAP to print the following pattern:

*
* *
* * *
* * * *
* * * * *
Solution
n = 5

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

Question 21(b)

WAP to print the following pattern:

A
B B
C C C
D D D D
E E E E E
Solution
n = 5

for i in range(n):
    for j in range(i + 1):
        print(chr(65 + i), end=" ")
    print()
Output
A 
B B
C C C
D D D D
E E E E E

Question 21(c)

WAP to print the following pattern:

1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
Solution
n = 5

for i in range(1, n + 1):
    for j in range(i, 0, -1):
        print(j, end=" ")
    print()
Output
1 
2 1
3 2 1
4 3 2 1
5 4 3 2 1
PrevNext