KnowledgeBoat Logo
OPEN IN APP

Chapter 1

Review of Python Basics

Class 12 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

Assignment (=) operator is the Python operator responsible for assigning values to the variables.

Question 2

Dynamic typing refers to declaring multiple values with different data types as and when required.

Question 3

A comma (,) is used to separate a key-value pair in dictionary.

Question 4

Partition() function will always return tuple of 3 elements.

Question 5

The reserved words in Python are called keywords and these cannot be used as names or identifiers.

Question 6

An operator is a symbol used to perform an action on some value.

Question 7

Tuple(seq) function is used to convert a sequence data type into tuple.

Question 8

The script files in Python have .py extension.

Question 9

id() function is used to retrieve the address of a variable in memory.

Question 10

Each object in Python has three key attributes—a type, a value and an id.

Question 11

In Python, the non-zero value is treated as True and zero value is treated as False.

Question 12

Keys of a dictionary must be unique.

Question 13

In Bubble sort, the adjoining values in a sequence are compared and exchanged repeatedly until the entire array is sorted.

Question 14

Logical operators are used to combine two or more relational/conditional expressions.

Question 15

The len() function returns the length of a specified list.

Question 16

None data type signifies the absence of value and doesn't display anything.

State True or False

Question 1

The two statements x = int(22.0/7) and x = int(22/7.0) yield the same results.

Answer

True

Reason — In Python, when we use the '/' operator to divide two numbers, it performs floating-point division, resulting in a float. Both division operations (22.0/7 and 22/7.0) yield float results due to the '/' operator. The 'int' function is applied to these float results, converting them to integers by truncating the decimal part.

Question 2

The statement: x + 1 = x is a valid statement.

Answer

False

Reason — In Python, literal values and expressions cannot be on the left-hand side (LHS) of an assignment statement. The left-hand side of an assignment statement must be a variable. Therefore, the statement "x + 1 = x" is invalid.

Question 3

List slice is a list in itself.

Answer

True

Reason — A list slice in Python creates a new list object that contains elements from the original list based on the specified indices or slice parameters. This new list is both a list in itself and a subset of the original list.

Question 4

Relational operators return either True or False.

Answer

True

Reason — Relational operators in Python return either True or False based on the comparison result between two operands. For example, the greater than operator (>) returns True if the left operand is greater than the right operand, and False otherwise.

Question 5

break, continue, pass are the three conditional statements.

Answer

False

Reason — In Python, 'break', 'continue', and 'pass' are control flow statements used to manage the flow of execution in a program. On the other hand, conditional statements such as 'if', 'else', and 'elif' are used to perform different actions based on specific conditions.

Question 6

The % (modulus) operator cannot be used with the float data type.

Answer

False

Reason — The % (modulus) operator can be used with float data types in Python. It calculates the remainder of a division operation, just like with integers.

Question 7

The range() function is used to specify the number of iterations to be performed in for loop.

Answer

True

Reason — In Python, the range() function is used to specify the number of iterations to be performed in a for loop. It generates a sequence of numbers that can be used to iterate over a block of code a specific number of times. The range() function takes parameters for the start, stop, and step values to define the range of numbers to be generated.

Question 8

Assignment operator can be used in place of equality operator in the test condition.

Answer

False

Reason — The assignment operator (=) is used to assign a value to a variable, whereas the equality operator (==) is used to compare two values for equality. Using the assignment operator in a test condition would result in assigning a value instead of comparing values. This can lead to unexpected behavior in code and may not achieve the intended comparison.

Question 9

Comments in Python begin with a "$\text{\textdollar}" symbol.

Answer

False

Reason — Comments in Python start with the "#" symbol and continue until the end of the line. They are used to add explanatory notes or disable certain lines of code for testing purposes.

Question 10

In print() function, if we use a concatenate operator (+) between two strings, both the strings are joined with a space in between them.

Answer

False

Reason — In print() function, if we use a concatenate operator (+) between two strings, they are joined together without any space between them. If we want a space between them, we need to explicitly include the space within the strings.

Question 11

If we execute Python code using prompt ">>>" then we call it an interactive interpreter.

Answer

True

Reason — When executing Python code using the prompt ">>>", it indicates direct interaction with the Python interpreter in real-time. In this mode, we can enter Python statements one at a time, and the interpreter will execute them immediately and show the results.

Question 12

Lists are immutable while strings are mutable.

Answer

False

Reason — Lists are mutable, meaning we can modify their elements after creation. For example, we can change the value of a list element or append new elements to a list. Strings are immutable, meaning we cannot change the characters in a string after it has been created.

Question 13

The keys of a dictionary must be of immutable types.

Answer

True

Reason — Dictionaries are indexed by keys. Hence its keys must be of any non-mutable type.

Question 14

Lists and strings in Python support two-way indexing.

Answer

True

Reason — Both lists and strings in Python support two-way indexing, which means we can access elements from the beginning or end of the sequence using positive or negative indices, respectively. Positive indices start from 0 for the first element, while negative indices start from -1 for the last element.

Question 15

Tuples can be nested and can contain other compound objects like lists, dictionaries and other tuples.

Answer

True

Reason — Tuples in Python can be nested, meaning they can contain other tuples, lists, dictionaries, or any other compound objects.

Multiple Choice Questions

Question 1

Which of the following is not considered a valid identifier in Python ?

  1. two2
  2. _main
  3. hello_rsp1
  4. 2 hundred

Answer

2 hundred

Reason — The identifier "2 hundred" is not considered valid in Python because identifiers cannot start with a digit and should not include spaces. They must start with either a letter (a-z, A-Z) or an underscore (_) followed by letters, digits, or underscores.

Question 2

What will be the output of the following code — print("100 + 200") ?

  1. 300
  2. 100200
  3. 100 + 200
  4. 200

Answer

100 + 200

Reason — The output of the code print("100 + 200") will be: 100 + 200. This is because the code is printing the string "100 + 200" as it is written within double quotes. The arithmetic operation inside the string is not evaluated because it's treated as a part of the string literal, not as an actual expression.

Question 3

Which amongst the following is a mutable data type in Python ?

  1. int
  2. string
  3. tuple
  4. list

Answer

list

Reason — The mutable data type in Python from the options given is a list. Lists can be modified after creation, allowing elements to be added, removed, or modified within the list. In contrast, integers (int), strings, and tuples are immutable data types in Python, meaning their values cannot be changed once they are created.

Question 4

Which of the following statements are not correct?

(A) An element in a dictionary is a combination of key-value pair.

(B) A tuple is a mutable data type.

(C) We can repeat a key in a dictionary.

(D) clear() function is used to delete the dictionary.

  1. A, B, C
  2. B, C, D
  3. B, C, A
  4. A, B, C, D

Answer

B, C, D

Reason

(B) Tuples are immutable data types in Python, meaning their values cannot be changed after creation.

(C) Dictionary keys must be unique, we cannot repeat a key in a dictionary.

(D) The clear() function is used to remove all elements from a dictionary, not to delete the dictionary itself.

Question 5

Which of the following statements converts a tuple into a list ?

  1. len(string)
  2. list(tuple)
  3. tup(list)
  4. dict(string)

Answer

list(tuple)

Reason — In Python, the list() constructor function is used to convert iterable objects, such as tuples, into lists. The syntax list(tuple) means that we are passing a tuple as an argument to the list() function, which then creates a new list containing the elements of the tuple.

Question 6

The statement: bval = str1 > str2 shall return ............... as the output if two strings str1 and str2 contains "Delhi" and "New Delhi".

  1. True
  2. Delhi
  3. New Delhi
  4. False

Answer

False

Reason — Python's lexicographical comparison compares strings character by character based on their ASCII values. In the case of "Delhi" and "New Delhi", the comparison stops at the first difference encountered, which is the comparison between 'D' and 'N'. Since 'N' has a greater ASCII value than 'D', the lexicographical comparison returns False.

Question 7

What will be the output generated by the following snippet?

a = [5,10,15,20,25]
k = 1
i = a [1] + 1 
j = a [2] + 1 
m = a [k + 1]
print (i, j , m)
  1. 11 15 16
  2. 11 16 15
  3. 11 15 15
  4. 16 11 15

Answer

11 16 15

Reason — The above code initializes a list named a with the values [5, 10, 15, 20, 25]. Then, the variable k is assigned the value 1. The value of i is calculated using indexing as the element at index 1 of list a (which is 10) plus 1, resulting in 'i = 11'. Similarly, j is calculated as the element at index 2 of list a (which is 15) plus 1, yielding 'j = 16'. m is calculated as the element at index (1 + 1 = 2) of list a, which is 15, leading to 'm = 15'. Finally, the code prints the values of 'i', 'j', and 'm', which are 11, 16, and 15 respectively.

Question 8

The process of arranging the array elements in a specified order is termed as:

  1. Indexing
  2. Slicing
  3. Sorting
  4. Traversing

Answer

Sorting

Reason — Sorting refers to the process of arranging elements in an array or list in a specified order, such as ascending or descending order.

Question 9

Which of the following Python functions is used to iterate over a sequence of numbers by specifying a numeric end value within its parameters ?

  1. range()
  2. len()
  3. substring()
  4. random()

Answer

range()

Reason — The range() function in Python is used to iterate over a sequence of numbers by specifying a numeric end value within its parameters. It takes parameters for the start, stop, and step values to define the range of numbers to be generated.

Question 10

What is the output of the following ?

d = {0: 'a', 1: 'b', 2: 'c'}
for i in d:
    print(i)

1.

0  
1  
2

2.

a  
b  
c

3.

0  
a  
1  
b  
2  
c  

4.

2  
a  
2  
b  
2  
c  

Answer

0  
1  
2

Reason — The code initializes a dictionary d with keys 0, 1, and 2, each mapped to the values 'a', 'b', and 'c' respectively. In Python, when we use a for loop with a dictionary using the in operator, like for i in d:, it iterates over the keys of the dictionary by default. During each iteration, the loop prints the current key i. Therefore, the output will be the keys of the dictionary d, which are 0, 1, and 2.

Question 11

What is the output of the following ?

x = 123
for i in x:
    print(i)
  1. 1 2 3
  2. 123
  3. Error
  4. Infinite loop

Answer

Error

Reason — The output of the code will be an error because we cannot directly iterate over an integer object in Python using a for loop. The for loop in Python iterates over iterable objects such as lists, tuples, strings, or dictionaries, but not individual integers

Question 12

Which arithmetic operator(s) cannot be used with strings ?

  1. +
  2. *
  3. -
  4. All of these

Answer

-

Reason — The arithmetic operator "-" (minus) cannot be used with strings in Python. The "+" operator is used for string concatenation, "*" is used for string repetition, but the "-" (minus) operator does not have a defined meaning for strings and will result in an error if used with strings.

Question 13

What will be the output when the following code is executed?

>>> strl = "helloworld"
>>> strl[ : : -1]
  1. dlrowolleh
  2. hello
  3. world
  4. helloworld

Answer

dlrowolleh

Reason — The code strl[::-1] reverses the string strl using slicing with a step of -1. This means it starts from the end of the string and moves towards the beginning, effectively reversing the order of characters in the string. Therefore, the output will be "dlrowolleh" which is the reverse of "helloworld".

Question 14

What is the output of the following statement?

print("xyyzxyzxzxyy".count('yy', 1))
  1. 2
  2. 0
  3. 1
  4. Error

Answer

2

Reason — The count() method in Python is used to count the occurrences of a substring within a string. In the given code, the string "xyyzxyzxzxyy" is searched for occurrences of the substring 'yy' starting from index 1 (the second position in the string). The substring 'yy' occurs twice in the specified range [1:] of the string "xyyzxyzxzxyy", at indices 1-2 and 10-11. Therefore, the count() method returns 2, indicating that 'yy' occurs twice in the specified range.

Question 15

Suppose list1 = [0.5 * x for x in range(0, 4)], list1 is:

  1. [0, 1, 2, 3]
  2. [0, 1, 2, 3, 4]
  3. [0.0, 0.5, 1.0, 1.5]
  4. [0.0, 0.5, 1.0, 1.5, 2.0]

Answer

[0.0, 0.5, 1.0, 1.5]

Reason — The list comprehension [0.5 * x for x in range(0, 4)] generates a list by calculating 0.5 * x for each value of x in the range from 0 to 3 (not including 4), which results in the list [0.0, 0.5, 1.0, 1.5].

Question 16

Which is the correct form of declaration of dictionary?

  1. Day = {1: 'monday', 2: 'tuesday', 3: 'wednesday'}
  2. Day = (1; 'monday', 2; ' tuesday', 3; 'wednesday')
  3. Day = [1: 'monday', 2: 'tuesday', 3: 'wednesday']
  4. Day = {1'monday', 2'tuesday', 3'wednesday']

Answer

Day = {1: 'monday', 2: 'tuesday', 3: 'wednesday'}

Reason — The syntax of dictionary declaration is:

<dictionary-name> = {<key>:<value>, <key>:<value>}

According to this syntax, Day = {1:'monday', 2:'tuesday', 3:'wednesday'} is the correct answer.

Question 17

Identify the valid declaration of L:

L = [1, 23, 'hi', 6]
  1. list
  2. dictionary
  3. array
  4. tuple

Answer

list

Reason — The given declaration L = [1, 23, 'hi', 6] creates a list in Python. Lists are created using square brackets [] and can contain elements of different data types, including integers, strings, and other lists.

Question 18

Identify the valid declaration of L:

L = {1: 'Mon', 2 : '23', 3: 'hello', 4: '60.5'}
  1. dictionary
  2. string
  3. tuple
  4. list

Answer

dictionary

Reason — The given declaration L = {1: 'Mon', 2: '23', 3: 'hello', 4: '60.5'} creates a dictionary in Python. Dictionaries are created using curly braces {}, and keys are separated from their corresponding values by a colon (:). Each key-value pair is separated by a comma (,) within the dictionary.

Question 19

In which data type does input() function return value ?

  1. Float
  2. Int
  3. String
  4. Boolean

Answer

String

Reason — The input() function always returns a value of String type.

Question 20

Which of the following is a valid relational operator in Python ?

  1. +
  2. **
  3. >
  4. and

Answer

>

Reason — The ">" symbol is a valid relational operator in Python. It checks if the value on the left side is greater than the value on the right side and returns a Boolean result (True or False) accordingly.

The other options provided are:

"+" (plus) is an arithmetic operator used for addition. "**" (double asterisk) is an arithmetic operator used for exponentiation. "and" is a logical operator used for combining conditions in boolean expressions.

Question 21

Write the output of the following code:

a = 10/2
b = 10//3
print(a, b)
  1. 5 3.3
  2. 5.0 3.3
  3. 5.0 3
  4. 5 4

Answer

5.0 3

Reason — The expression a = 10/2 performs floating-point division, resulting in a being assigned the value 5.0. Similarly, the expression b = 10//3 performs integer division (floor division), resulting in b being assigned the value 3. The print(a, b) statement prints the values of variables a and b, which are 5.0 and 3 respectively.

Question 22

Which of the following is a valid variable name ?

  1. Student Name
  2. 3Number
  3. %Name%
  4. Block_number

Answer

Block_number

Reason — A valid variable name in Python can only contain letters (a-z, A-Z), digits (0-9), and underscores (_). It cannot start with a digit and must not contain special characters such as spaces, %, or symbols like $, @, etc.

Assertions and Reasons

Question 1

Assertion (A): Every small unit in a Python programming statement is termed as a token.

Reasoning (R): Tokens are not interpreted but are an integral part while designing the code.

  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
A token is the smallest element of a Python program that holds meaning for the interpreter. This includes keywords, identifiers, literals, operators, and punctuation symbols. Tokens serve as lexical units, acting as building blocks in the structure of Python code. They are interpreted as essential components of the code, contributing to the design and structure of the program.

Question 2

Assertion (A): The data type of a variable is taken according to the type of value assigned to it.

Reasoning (R): Data types do not require initialization at the time of declaration. This process is described as Dynamic Typing.

  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, we are not required to explicitly declare a variable with its type. Whenever we declare a variable with a value, Python automatically assigns the relevant data type to it based on the assigned value. This process is known as dynamic typing.

Question 3

Assertion (A): In Python, strings, lists and tuples are called Sequences.

Reasoning (R): Sequence is referred to as an ordered collection of values having similar or different data types.

  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 sequence is an ordered collection of items in Python, and these items can have similar or different data types. They are indexed by integers. The three main types of sequence data types in Python are strings, lists, and tuples.

Question 4

Assertion (A): break and continue are termed as Jump statements.

Reasoning (R): Jump statements can only be used with looping constructs but 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 5

Assertion (A): The conditional flow of control can be defined with the help of if statement.

Reasoning (R): if statement executes one or more statements based on the given condition. If the condition evaluates to true, the statement block following the indentation gets executed, otherwise nothing gets executed.

  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 6

Assertion (A): Indexing refers to accessing elements of a sequence. Python offers two types of indexing, viz. positive or forward and negative or backward indexing.

Reasoning (R): Both forward and backward indexing are implemented in all the sequences, which start with first (1st) index.

  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
Indexing in Python refers to accessing elements of a sequence, such as strings, lists, tuples, etc. Python supports two types of indexing: positive (forward) indexing and negative (backward) indexing. In Python, indexing starts from 0, not from the first index (1st index). Forward indexing starts from the first element with an index of 0, while backward indexing starts from the last element with an index of -1.

Question 7

Assertion (A): Dictionaries in Python are mutable.

Reasoning (R): The data inside a dictionary is stored as the key:value pairs enclosed within the curly braces {}.

  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 but R is not the correct explanation of A.

Explanation
In Python, dictionaries are mutable, which means we can modify the key-value pairs, add new pairs, or remove existing pairs after the dictionary is created. Dictionaries are created using curly braces {}, and keys are separated from their corresponding values by a colon (:). Each key-value pair is separated by commas (,) within the dictionary.

Question 8

Assertion (A): There is no difference between a list and a tuple in Python.

Reasoning (R): The list elements are enclosed within square brackets [] separated by commas and the tuple elements are enclosed within parentheses () separated by commas.

  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
Lists are mutable, meaning their elements can be changed after creation, and they are enclosed within square brackets [] separated by commas. On the other hand, tuples are immutable, so their elements cannot be changed after creation, and they are enclosed within parentheses () separated by commas. Hence, list and tuples are not same.

Question 9

Assertion (A): Both max() and min() functions are implemented on lists as well as tuples in Python.

Reasoning (R): The max() and min() functions return the highest and the lowest among a set of values stored in a list or tuple 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

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

Explanation
Both max() and min() functions are implemented on lists as well as tuples in Python. This is true because both functions can operate on any iterable, including lists and tuples. The max() function returns the highest value among a set of values, and the min() function returns the lowest value among a set of values, whether they are stored in a list or a tuple.

Question 10

Assertion (A): You can add an element in a dictionary using key:value pair.

Reasoning (R): A new (key:value) pair is added only when the same key doesn't exist in the dictionary. If the key is already present, then the existing key gets updated and the new entry will be made in the dictionary.

  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, dictionaries are mutable, which means we can modify the key:value pairs, add new pairs, or remove existing pairs after the dictionary is created. When adding a new key:value pair to a dictionary, if the key already exists, its corresponding value will be updated. Otherwise, a new (key:value) pair will be added to the dictionary.

Solutions to Unsolved Questions

Question 1

What are the advantages of Python programming language?

Answer

Advantages of Python programming language are:

  1. Easy to Use — Python is compact, programmer-friendly and very easy to use object oriented language with very simple syntax rules.
  2. Expressive Language — Python is an expressive language, it takes fewer lines of codes to represent the same syntax.
  3. Interpreted Language — Python is an interpreted language, not a compiled language. It makes Python an easy-to-debug language and thus suitable for beginners to advanced users.
  4. Completeness — Python has a rich standard library that provides modules for most types of required functionality like emails, web-pages, databases, GUI development, network connections, etc.
  5. Cross-platform Language — Python can run equally well on variety of platforms — Windows, Linux/UNIX, Macintosh, supercomputers, smart phones, etc.
  6. Free and Open Source — Python language is freely available along with its source-code.
  7. Variety of Usage/Applications — Python has evolved into a powerful, complete and useful language over these years. These days Python is being used in many diverse fields/applications, some of which are Scripting, Web Applications, Game development, Database Applications, System Administrations, Rapid Prototyping, GUI Programs.

Question 2

In how many different ways can you work in Python?

Answer

We can work in Python in two ways:

  1. Interactive mode (also called Immediate mode)
  2. Script mode

Question 3

What are the advantages/disadvantages of working in interactive mode in Python?

Answer

Interactive mode is useful for testing code. We can type the commands one by one and get the result of error immediately for each command. Disadvantages of Interactive mode are that it does not save commands in form of a program and also output is sandwiched between commands.

Question 4

Write Python statement for the following in interactive mode:

  1. To display sum of 3, 8.0, 6*12
  2. To print sum of 16, 5.0, 44.0

Answer

1.

>>> 3 + 8.0 + 6 * 12

2.

>>> print(16 + 5.0 + 44.0)

Question 5

What are operators? Give examples of some unary and binary operators.

Answer

Operators are tokens that trigger some computation/action when applied to variables and other objects in an expression. Unary plus (+), Unary minus (-) are a few examples of unary operators. Examples of binary operators are Addition (+), Subtraction (-), Multiplication (*), Division (/).

Question 6

What is an expression and a statement?

Answer

An expression is any legal combination of symbols that represents a value. For example, 2.9, a + 5, (3 + 5) / 4.

A statement is a programming instruction that does something i.e. some action takes place. For example:
print("Hello")
a = 15
b = a - 10

Question 7

What all components can a Python program contain?

Answer

A Python program can contain various components like expressions, statements, comments, functions, blocks and indentation.

Question 8

What are variables? How are they important for a program?

Answer

Variables are named labels whose values can be used and processed during program run. Variables are important for a program because they enable a program to process different sets of data.

Question 9(i)

Write the output of the following:

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

Answer

Output
CPU 1
CPU 2
CPU 3
Explanation

The for loop iterates over each character in the string '123' using the in operator, and during each iteration, the variable i takes on the value of each character in the string. The print("CPU", i) statement then prints the string "CPU" followed by the value of i during each iteration of the loop.

Question 9(ii)

Write the output of the following:

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

Answer

Output
100
200
300
Explanation

The for loop iterates over each element in the list [100, 200, 300] using the in operator, and during each iteration, the variable i takes on the value of each element in the list. The print(i) statement then prints the value of i during each iteration of the loop.

Question 9(iii)

Write the output of the following:

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

Answer

Output
20
16
Explanation

The range(10, 6, -2) function creates a range starting from 10 and decrementing by 2 until it reaches 6 (but does not include 6), resulting in the sequence [10, 8]. The for j in range(10, 6, -2): statement sets up a for loop that iterates over each element in the generated sequence [10, 8]. During each iteration of the loop, the print(j*2) statement prints the value of j multiplied by 2.

Question 9(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

The code features two nested for loops. The outer loop iterates over values from 1 to 5 (inclusive) and assigns each to x. The inner loop iterates from 1 to the x + 1 value and assigns each to y. The print(x, ' ', y) statement outputs x and y separated by a space during each iteration. This arrangement generates combinations of (x, y) pairs.

Question 9(v)

Write the output of the following:

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

Answer

Output
15
Explanation

The code sets up a for loop that iterates over a range of numbers from 10 to 19. During each iteration, the variable x takes on these values sequentially. Within the loop, an if statement checks if x is equal to 15. When x reaches 15, the condition is met, and the break statement is executed, immediately exiting the loop. As a result, the loop terminates prematurely, and the value of x at the point of exit, which is 15, is printed.

Question 9(vi)

Write the output of the following:

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

Answer

Output
19
Explanation

In the provided code, a for loop iterates over a range of numbers from 10 to 19. Within the loop, an if statement checks if the current value of x is even (divisible by 2) using the modulo operator '%'. If x is even, the continue statement is executed, causing the loop to skip the rest of the code in that iteration and move to the next iteration. As a result, only odd numbers in the range 10 to 19 will be considered. After the loop completes, the value of x will be the last value of the iteration, which is 19. Therefore, the output of the code will be 19.

Question 10

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
Explanation

The provided code consists of nested conditional statements to determine the output based on the value of the variable x. If x is greater than 10, it checks additional conditions. If x is greater than 25, it prints "ok," and if x is greater than 60, it prints "good." If x is not greater than 10 but is greater than 40, it prints "average." Otherwise, if none of the conditions are met, it prints "no output".

Question 11

What are the various ways of creating a list?

Answer

The various ways of creating a list are :

  1. Using Square Brackets [].
  2. Using the list() constructor.
  3. Using list comprehensions.
  4. Appending Elements.
  5. Using the extend() method.
  6. Using slicing.

Question 12

What are the similarities between strings and lists?

Answer

Both strings and lists are sequential data types, meaning they store elements in a specific order. They support indexing, allowing access to individual elements using square brackets notation '[]'. Additionally, both strings and lists support slicing, enabling us to extract portions of the sequence using the colon (:) operator. They can also be iterated over using loops such as for loops, facilitating access to each element one by one in the sequence. Furthermore, both strings and lists support the in and not in operators, which check for the presence or absence of a particular element in the sequence.

Question 13

Why are lists called a mutable data type?

Answer

Lists are called mutable data types in Python because they allow modifications to be made to their elements after the list is created. This mutability facilitates operations such as adding, removing, or modifying elements within the list even after its initial creation.

Question 14

What is the difference between insert() and append() methods of a list?

Answer

Insert MethodAppend Method
The insert() method is used to add an element at a specific index in the list.The append() method is used to add an element at the end of the list.
The syntax is: list.insert(index, element).The Syntax is: list.append(element).
Example: my_list.insert(2, 'hello') will insert the string 'hello' at index 2 in the list my_list.Example: my_list.append('world') will add the string 'world' at the end of the list my_list.

Question 15

Write a program to calculate the mean of a given list of numbers.

Solution
numbers = eval(input("Enter a list: "))
if len(numbers) == 0:
    print("List is empty, cannot calculate mean.")
else:
    total = sum(numbers)
    n = len(numbers)
    mean = total / n
    print("Mean of the numbers:", mean)
Output
Enter a list: [10, 30, 25, 34, 45, 98]
Mean of the numbers: 40.333333333333336

Question 16

Write a program to calculate the minimum element of a given list of numbers.

Solution
l = eval(input("Enter a list: "))
m = min(l)
print("Minimum element in the list:", m)
Output
Enter a list: [1, 4, 65, 34, 23]
Minimum element in the list: 1

Question 17

Write a code to calculate and display total marks and percentage of a student from a given list storing the marks of a student.

Solution
marks_list = eval(input("Enter list of marks: "))
total_marks = sum(marks_list)
total_subjects = len(marks_list)
maximum_marks_per_subject = 100 
total_marks_possible = maximum_marks_per_subject * total_subjects
percentage = (total_marks / total_marks_possible) * 100

print("Total Marks:", total_marks)
print("Percentage:", percentage)
Output
Enter list of marks: [85, 90, 78, 92, 88]
Total Marks: 433
Percentage: 86.6

Question 18

Write a program to multiply an element by 2 if it is an odd index for a given list containing both numbers and strings.

Solution
mixed = eval(input("Enter the list: "))
for index in range(1, len(mixed), 2):
        mixed[index] *= 2  
print("Modified List:", mixed)
Output
Enter the list: [1, 'apple','banana', 5, 'cherry', 7, 'date', 'cherry'] 
Modified List: [1, 'appleapple', 'banana', 10, 'cherry', 14, 'date', 'cherrycherry']

Question 19

Write a program to count the frequency of an element in a list.

Solution
my_list = eval(input("Enter the list: "))
c = int(input("Enter the element whose frequency is to be checked: "))
frequency = my_list.count(c)
print("The frequency of", c, "in the list is: ", frequency)
Output
Enter the list: [1, 2, 3, 4, 1, 2, 1, 3, 4, 5, 1]
Enter the element whose frequency is to be checked: 1
The frequency of 1 in the list is:  4

Question 20

Write a program to shift elements of a list so that the first element moves to the second index and second index moves to the third index, and so on, and the last element shifts to the first position.

Suppose the list is [10, 20, 30, 40]
After shifting, it should look like: [40, 10, 20, 30]
Solution
l = eval(input("Enter the list: "))
print("Original List")
print(l)

l = l[-1:] + l[:-1]

print("Rotated List")
print(l)
Output
Enter the list: [10, 20, 30, 40]
Original List
[10, 20, 30, 40]
Rotated List
[40, 10, 20, 30]

Question 21

A list Num contains the following elements:

3, 25, 13, 6, 35, 8, 14, 45

Write a program to swap the content with the next value divisible by 5 so that the resultant list will look like:

25, 3, 13, 35, 6, 8, 45, 14
Solution
Num = [3, 25, 13, 6, 35, 8, 14, 45]
for i in range(len(Num) - 1):
    if Num[i] % 5 != 0 and Num[i + 1] % 5 == 0:
        Num[i], Num[i + 1] = Num[i + 1], Num[i]
print("Resultant List:", Num)
Output
Resultant List: [25, 3, 13, 35, 6, 8, 45, 14]

Question 22

Write a program to accept values from a user in a tuple. Add a tuple to it and display its elements one by one. Also display its maximum and minimum value.

Solution
tuple1 = eval(input("Enter a tuple: "))
tuple2 = (10, 20, 30)
combined_tuple = tuple1 + tuple2
print("Elements of the combined tuple:")
for element in combined_tuple:
    print(element)

print("Maximum value:", max(combined_tuple))
print("Minimum value:", min(combined_tuple))
Output
Enter a tuple: (11, 67, 34, 65, 22)
Elements of the combined tuple:
11
67
34
65
22
10
20
30
Maximum value: 67
Minimum value: 10

Question 23

Write a program to input any values for two tuples. Print it, interchange it and then compare them.

Solution
tuple1 = eval(input("Enter the first tuple: "))
tuple2 = eval(input("Enter the second tuple: "))

print("Original Tuples:")
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)

tuple1, tuple2 = tuple2, tuple1

print("\nSwapped Tuples:")
print("Tuple 1 (after swapping):", tuple1)
print("Tuple 2 (after swapping):", tuple2)

if tuple1 == tuple2:
    print("\nThe swapped tuples are equal.")
else:
    print("\nThe swapped tuples are not equal.")
Output
Enter the first tuple: (5, 6, 3, 8, 9)
Enter the second tuple: (77, 33, 55, 66, 11)
Original Tuples:
Tuple 1: (5, 6, 3, 8, 9)
Tuple 2: (77, 33, 55, 66, 11)

Swapped Tuples:
Tuple 1 (after swapping): (77, 33, 55, 66, 11)
Tuple 2 (after swapping): (5, 6, 3, 8, 9)

The swapped tuples are not equal.

Question 24

Write a Python program to input 'n' classes and names of class teachers to store them in a dictionary and display the same. Also accept a particular class from the user and display the name of the class teacher of that class.

Solution
n = int(input("Enter number of classes: "))
data = {}
for i in range(n):
    class_name = input("Enter class name: ")
    teacher_name = input("Enter teacher name: ")
    data[class_name] = teacher_name
print("Class data:", data)
find = input("Enter a class name to find its teacher: ")
if find in data:
    print("Teacher for class", find, "is", data[find])
else:
    print("Class not found in the data.")
Output
Enter number of classes: 4
Enter class name: green
Enter teacher name: Aniket
Enter class name: yellow
Enter teacher name: Pratibha
Enter class name: red
Enter teacher name: Mayuri
Enter class name: blue
Enter teacher name: Prithvi
Class data: {'green': 'Aniket', 'yellow': 'Pratibha', 'red': 'Mayuri', 'blue': 'Prithvi'}
Enter a class name to find its teacher: red
Teacher for class red is Mayuri

Question 25

Write a program to store student names and their percentage in a dictionary and delete a particular student name from the dictionary. Also display the dictionary after deletion.

Solution
n = int(input("Enter number of students: "))
data = {}
for i in range(n):
    stu_name = input("Enter student name: ")
    percentage = input("Enter percentage: ")
    data[stu_name] = percentage
print("Student data:", data)
find = input("Enter a student name to delete: ")
if find in data:
    del data[find]
    print("Updated student data:", data)
else:
    print("Student not found in the data.")
Output
Enter number of students: 4
Enter student name: Megha
Enter percentage: 98
Enter student name: Amit
Enter percentage: 88
Enter student name: Nitin
Enter percentage: 92
Enter student name: Amulya
Enter percentage: 79
Student data: {'Megha': '98', 'Amit': '88', 'Nitin': '92', 'Amulya': '79'}
Enter a student name to delete: Nitin
Updated student data: {'Megha': '98', 'Amit': '88', 'Amulya': '79'}

Question 26

Write a Python program to input names of 'n' customers and their details like items bought, cost and phone number, etc., store them in a dictionary and display all the details in a tabular form.

Solution
n = int(input("Enter the number of customers: "))
customer_data = {}

for i in range(n):
    name = input("Enter customer name: ")
    items_bought = input("Enter items bought: ")
    cost = float(input("Enter cost: "))
    phone_number = int(input("Enter phone number: "))

    customer_data[name] = {
        'Items Bought': items_bought,
        'Cost': cost,
        'Phone Number': phone_number
    }

print("Customer Details:")
print("Name\t\tItems Bought\t\tCost\t\tPhone Number")
for name, details in customer_data.items():
    print(name, "\t\t", details['Items Bought'], "\t\t", details['Cost'], "\t\t", details['Phone Number'])
Output
Enter the number of customers: 4
Enter customer name: Sakshi
Enter items bought: Chocolate, Icecream
Enter cost: 200
Enter phone number: 9876354678
Enter customer name: Shashank
Enter items bought: Biscuits, Maggie, Soup
Enter cost: 450
Enter phone number: 8976346378
Enter customer name: Saanvi
Enter items bought: Veggies, Coffee
Enter cost: 300
Enter phone number: 8794653923
Enter customer name: Shivank
Enter items bought: Door mat, Bottles, Boxes
Enter cost: 600
Enter phone number: 6737486827
Customer Details:
Name            Items Bought            Cost            Phone Number
Sakshi           Chocolate, Icecream             200.0           9876354678
Shashank                 Biscuits, Maggie, Soup                  450.0           8976346378
Saanvi           Veggies, Coffee                 300.0           8794653923
Shivank                  Door mat, Bottles, Boxes                600.0           6737486827

Question 27

Write a Python program to capitalize first and last letters of each word of a given string.

Solution
input_string = input("Enter the string: ")
words = input_string.split()
result = []

for word in words:
    if len(word) > 1:
        modified_word = word[0].upper() + word[1:-1] + word[-1].upper()
    else:
        modified_word = word.upper()
    result.append(modified_word)

capitalized_string = ' '.join(result)
print(capitalized_string)
Output
Enter the string: the quick brown fox jumps over the lazy dog                 
ThE QuicK BrowN FoX JumpS OveR ThE LazY DoG

Question 28

Write a Python program to remove duplicate characters of a given string.

Solution
input_string = input("Enter the string: ")
unique_chars = {}
for char in input_string:
    if char not in unique_chars:
        unique_chars[char] = True
result = ''.join(unique_chars.keys())
print(result)
Output
Enter the string: hello world
helo wrd

Question 29

Write a Python program to compute sum of digits of a given number.

Solution
number = int(input("Enter a number: "))
sum_of_digits = 0
while number > 0:
    digit = number % 10
    sum_of_digits += digit
    number = number // 10

print("Sum of digits:", sum_of_digits)
Output
Enter a number: 4556787
Sum of digits: 42

Question 30

Write a Python program to find the second most repeated word in a given string.

Solution
input_string = input("Enter the string: ")
words = input_string.split()

word_counts = {}
for word in words:
    if word in word_counts:
        word_counts[word] += 1
    else:
        word_counts[word] = 1

max_count = 0
second_max_count = 0
most_repeated_word = None
second_most_repeated_word = None

for word, count in word_counts.items():
    if count > max_count:
        second_max_count = max_count
        max_count = count
        second_most_repeated_word = most_repeated_word
        most_repeated_word = word
    elif count > second_max_count:
        second_max_count = count
        second_most_repeated_word = word

print(second_most_repeated_word)
Output
Enter the string: apple banana cherry banana cherry cherry
banana

Question 31

Write a Python program to change a given string to a new string where the first and last characters have been exchanged.

Solution
input_str = input("Enter the string: ")
first_char = input_str[0]  
last_char = input_str[-1]  
middle_chars = input_str[1:-1]  
new_str = last_char + middle_chars + first_char
print("Original string:", input_str)
print("New string after swapping first and last characters:", new_str)
Output
Enter the string: python
Original string: python
New string after swapping first and last characters: nythop

Question 32

Write a Python program to multiply all the items in a list.

Solution
lst = eval(input("Enter the list: "))
result = 1
for item in lst:
    result *= item
print("Result:", result)
Output
Enter the list: [1, 2, 3, 4, 5, 6]
Result: 720

Question 33

Write a Python program to get the smallest number from a list.

Solution
numbers = eval(input("Enter the list: "))
smallest = min(numbers)
print("Smallest Number:", smallest)
Output
Enter the list: [23, 44, 36, 98, 100, 15]
Smallest Number: 15

Question 34

Write a Python program to append a list to the second list.

Solution
list1 = eval(input("Enter the first list: "))
list2 = eval(input("Enter the second list: "))
list1.extend(list2)
print("Appended List:", list1)
Output
Enter the first list: [22, 44, 66, 88]
Enter the second list: [10, 30, 50, 70, 90]
Appended List: [22, 44, 66, 88, 10, 30, 50, 70, 90]

Question 35

Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).

Solution
squares = []
for num in range(1, 31):
    squares.append(num ** 2)
first_5 = squares[:5]
last_5 = squares[-5:]
combined_list = first_5 + last_5
print("Combined list:", combined_list)
Output
Combined list: [1, 4, 9, 16, 25, 676, 729, 784, 841, 900]

Question 36

Write a Python program to get unique values from a list.

Solution
input_list = eval(input("Enter the list: "))
unique_values = []

for item in input_list:
    if item not in unique_values:
        unique_values.append(item)

print("Unique values from the list:", unique_values)
Output
Enter the list: [1, 2, 3, 3, 4, 5, 5, 6, 6, 7]
Unique values from the list: [1, 2, 3, 4, 5, 6, 7]

Question 37

Write a Python program to convert a string to a list.

Solution
string = input("Enter the string: ")
char_list = list(string)

print("String converted to list:", char_list)
Output
String converted to list: ['P', 'y', 't', 'h', 'o', 'n']

Question 38

Write a Python script to concatenate the following dictionaries to create a new one:

d1 = {'A': 1, 'B': 2, 'C': 3}
d2 = {'D': 4 }

Output should be:

{'A': 1, 'B': 2, 'C': 3, 'D' : 4}
Solution
d1 = {'A': 1, 'B': 2, 'C': 3}
d2 = {'D': 4}
d1.update(d2)
print("Concatenated dictionary: ", d1)
Output
Concatenated dictionary:  {'A': 1, 'B': 2, 'C': 3, 'D': 4}

Question 39

Write a Python script to check if a given key already exists in a dictionary.

Solution
my_dict = eval(input("Enter the dictionary: "))
key_check = input("Enter the key to be checked: ")
if key_check in my_dict:
    print("The key", key_check, "exists in the dictionary.")
else:
    print("The key", key_check, "does not exist in the dictionary.")
Output
Enter the dictionary: {'A': 1, 'B': 2, 'C': 3, 'D' : 4} 
Enter the key to be checked: C
The key C exists in the dictionary.

Enter the dictionary: {'A': 1, 'B': 2, 'C': 3, 'D' : 4}
Enter the key to be checked: E
The key E does not exist in the dictionary.

Question 40

Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys.

Sample Dictionary

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Solution
result_dict = {}
for num in range(1, 16):
    result_dict[num] = num ** 2
print("Resulting dictionary:", result_dict)
Output
Resulting dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}

Question 41

Write a Python script to merge two Python dictionaries.

Solution
dict1 = eval(input("Enter the first dictionary: "))
dict2 = eval(input("Enter the second dictionary: "))
dict1.update(dict2)
print("Merged dictionary:", dict1)
Output
Enter the first dictionary: {1 : "Orange", 2: "Mango", 3 : "Watermelon"}
Enter the second dictionary: {4 : "Pineapple", 5 : "Banana"}
Merged dictionary: {1: 'Orange', 2: 'Mango', 3: 'Watermelon', 4: 'Pineapple', 5: 'Banana'}

Question 42

Write a Python program to sort a dictionary by key.

Solution
def bubble_sort_keys(keys):
    n = len(keys)
    for i in range(n - 1):
        for j in range(0, n - i - 1):
            if keys[j] > keys[j + 1]:
                keys[j], keys[j + 1] = keys[j + 1], keys[j]

my_dict = eval(input("Enter the dictionary: "))
keys_list = list(my_dict.keys())
bubble_sort_keys(keys_list)
sorted_dict = {}
for key in keys_list:
    sorted_dict[key] = my_dict[key]

print("Dictionary sorted by key:", sorted_dict)
Output
Enter the dictionary: {51 : "Orange", 21: "Mango", 13 : "Watermelon"}
Dictionary sorted by key: {13: 'Watermelon', 21: 'Mango', 51: 'Orange'}

Question 43

Write a Python program to combine two dictionaries adding values for common keys.

d1 = {'a': 100, 'b': 200, 'c':300} 
d2 = {'a': 300, 'b': 200, 'd':400}

Sample output:

Counter({'a': 400, 'b': 400, 'c': 300, 'd': 400})
Solution
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
combined_dict = {}
for key, value in d1.items():
    combined_dict[key] = value
for key, value in d2.items():
    if key in combined_dict:
        combined_dict[key] += value
    else:
        combined_dict[key] = value

print("Combined dictionary with added values for common keys:", combined_dict)
Output
Combined dictionary with added values for common keys: {'a': 400, 'b': 400, 'c': 300, 'd': 400}

Question 44

Write a Python program to find the three highest values in a dictionary.

Solution
my_dict = eval(input("Enter the dictionary: "))
highest_values = []
highest_keys = []
for key, value in my_dict.items():
    if not highest_values or value > highest_values[-1]:
        highest_values.append(value)
        highest_keys.append(key)
        if len(highest_values) > 3:
            highest_values.pop(0)
            highest_keys.pop(0)
print("Three highest values in the dictionary:")
for i in range(len(highest_keys)):
    print(highest_keys[i], ":" ,highest_values[i])
Output
Enter the dictionary: {'c': 100, 'b': 200, 'e': 300, 'd': 400, 'a': 500} 
Three highest values in the dictionary:
e : 300
d : 400
a : 500

Question 45

Write a Python program to sort a list alphabetically in a dictionary.

Solution
my_dict = eval(input("Enter the dictionary: "))
for key, value in my_dict.items():
    value.sort()

print("Sorted dictionary:", my_dict)
Output
Enter the dictionary: {'list1': ['banana', 'apple', 'cherry'], 'list2': ['orange', 'grape', 'kiwi'], 'list3': ['pear', 'watermelon', 'mango']}
Sorted dictionary: {'list1': ['apple', 'banana', 'cherry'], 'list2': ['grape', 'kiwi', 'orange'], 'list3': ['mango', 'pear', 'watermelon']}

Question 46

Write a Python program to count number of items in a dictionary value that is a list.

Solution
my_dict = eval(input("Enter the dictionary: "))
total_count = 0
for value in my_dict.values():
    if type(value) is list:
        total_count += len(value)
print("Total number of items in lists within the dictionary:", total_count)
Output
Enter the dictionary: {'l1': [1, 2, 3, 4], 'l2': 'Apple', 'l3': [True, False], 'l4': 'Orange'}         
Total number of items in lists within the dictionary: 6

Question 47

Consider the following unsorted list:
105, 99, 10, 43, 62, 8.
Write the passes of bubble sort for sorting the list in ascending order till the 3rd iteration.

Answer

The unsorted list: [105, 99, 10, 43, 62, 8]

First pass — [99, 10, 43, 62, 8, 105]
Second pass — [10, 43, 62, 8, 99, 105]
Third pass — [10, 43, 8, 62, 99, 105]

Explanation

First pass

[105, 99, 10, 43, 62, 8] → [99, 105, 10, 43, 62, 8] — it will swap since 99 < 105
[99, 105, 10, 43, 62, 8] → [99, 10, 105, 43, 62, 8] — it will swap since 10 < 105
[99, 10, 105, 43, 62, 8] → [99, 10, 43, 105, 62, 8] — it will swap since 43 < 105
[99, 10, 43, 105, 62, 8] → [99, 10, 43, 62, 105, 8] — it will swap since 62 < 105
[99, 10, 43, 62, 105, 8] → [99, 10, 43, 62, 8, 105] — it will swap since 8 < 105

Second pass

[99, 10, 43, 62, 8, 105] → [10, 99, 43, 62, 8, 105] — it will swap since 10 < 99
[10, 99, 43, 62, 8, 105] → [10, 43, 99, 62, 8, 105] — it will swap since 43 < 99
[10, 43, 99, 62, 8, 105] → [10, 43, 62, 99, 8, 105] — it will swap since 62 < 99
[10, 43, 62, 99, 8, 105] → [10, 43, 62, 8, 99, 105] — it will swap since 8 < 99

Third pass

[10, 43, 62, 8, 99, 105] → [10, 43, 62, 8, 99, 105] — no swapping as 43 > 10
[10, 43, 62, 8, 99, 105] → [10, 43, 62, 8, 99, 105] — no swapping as 62 > 43
[10, 43, 62, 8, 99, 105] → [10, 43, 8, 62, 99, 105] — it will swap since 8 < 62

Question 48

What will be the status of the following list after the First, Second and Third pass of the insertion sort method used for arranging the following elements in descending order?

28, 44, 97, 34, 50, 87

Note: Show the status of all the elements after each pass very clearly underlining the changes.

Answer

list = [28, 44, 97, 34, 50, 87]

First pass

[28, 44, 97, 34, 50, 87] → [44, 28, 97, 34, 50, 87] — it will swap since 28 < 44

Second pass

[44, 28, 97, 34, 50, 87] → [44, 97, 28, 34, 50, 87] — it will swap since 28 < 97
[44, 97, 28, 34, 50, 87] → [97, 44, 28, 34, 50, 87] — it will swap since 44 < 97

Third pass

[97, 44, 28, 34, 50, 87] → [97, 44, 34, 28, 50, 87] — it will swap since 28 < 34
[97, 44, 34, 28, 50, 87] → [97, 44, 34, 28, 50, 87] — no swapping as 44 > 34
[97, 44, 34, 28, 50, 87] → [97, 44, 34, 28, 50, 87] — no swapping as 97 > 44

Question 49(a)

Evaluate the following expression:

6 * 3 + 4 ** 2 // 5 - 8

Answer

6 * 3 + 4 ** 2 // 5 - 8
= 6 * 3 + 16 // 5 - 8
= 6 * 3 + 3 - 8
= 18 + 3 - 8
= 21 - 8
= 13

The above expression follows operator precedence rules in Python. First, exponentiation is evaluated, then floor division is performed, followed by multiplication, and finally, addition and subtraction. The result of the expression is 13.

Question 49(b)

Evaluate the following expression:

10 > 5 and 7 > 12 or not 18 > 3

Answer

10 > 5 and 7 > 12 or not 18 > 3
= True and False or not True
= True and False or False
= False or False
= False

The above expression evaluates comparisons (>, <) first, applies the boolean 'not' operator next, evaluates the boolean 'and' operator finally, and evaluates the boolean 'or' operator last.

Question 50

What is type casting?

Answer

The conversion of an operand to a specific data type is called type casting. It is of two types:

  1. Explicit type conversion
  2. Implicit type conversion

Question 51

What are comments in Python? How is a comment different from indentation?

Answer

Comments in Python are additional information provided alongside a statement or a chunk of code to enhance the clarity of the code. They begin with the '#' symbol in Python and extend until the end of the line for single-line comments. For multi-line comments, Python supports using triple quotes (''' or """) to enclose the comment text. They are entirely ignored by the Python interpreter during program execution and are used solely for documentation and explanation purposes.
Indentation, on the other hand, defines the structure and hierarchy of code blocks. It indicates the beginning and end of loops, conditional statements, function definitions, and other blocks of code. Indentation refers to the spaces or tabs placed at the beginning of lines of code to signify blocks. Proper indentation is crucial for the interpreter to comprehend the structure of the code. Incorrect or inconsistent indentation can lead to syntax errors or alter the logic of the program.

PrevNext