Over 50 Multiple Choice Questions with Answers for Python

Introduction to Python

Python is a high-level programming language that comes with inbuilt data structures and dynamic binding. It is an interpreted, object-oriented programming language. What sets Python apart from other programming languages is its easy-to-write and easy-to-understand syntax, which makes it an excellent choice for beginners and experienced developers alike. Moreover, Python's extensive applicability and library support make it possible to build highly versatile and scalable software or products in real-world scenarios.

Features of Python

Python offers an array of features that make it an ideal language of choice for developers. Here are some of its key features:

  1. Easy to Code: Python is a high-level language, and its considerably easy syntax makes it easy to write large programming projects.
  2. Open-Source: Python is an open-source language, and its source code is freely available to the public without charge.
  3. Object-Oriented Programming: Python supports all paradigms of OOPs, making it highly relevant in modern programming.
  4. High-Level Language: In Python, developers don't have to manage system architecture or memory to code. It is a high-level programming language.
  5. Portable: Python code can run on any platform, be it Windows, Mac, Linux, etc.
  6. Integrated: Python is an integrated language as it can be easily integrated with other programming languages such as C, C++, etc.
  7. Interpreted: Python code is executed line by line during compilation, making it an interpreted language.
  8. Dynamically Typed: In Python, the datatype of a variable is determined dynamically at runtime, and this feature is called dynamically typed.

Conclusion

To sum up, Python is a robust, high-level, interpreted programming language that strongly follows all OOPs principles. It has a simple syntax and various inbuilt modules, making it appealing to both beginners and experienced developers. The extensive collection of libraries and functions makes Python the preferred choice for the development of any software or product.The answer is: "No fixed length is specified."

Output of Python Code Snippet

Code:


print(2**3 + (5 + 6)**(1 + 1))

Output:


129

Explanation:

The code calculates the result of an expression. The expression follows the BEDMAS rule of operator precedence. The parentheses with addition inside (5+6) evaluate to 11, and the exponentiation (1+1) evaluates to 2. The two expressions are then summed, and the result is raised to the power of 2. The final result printed to the console is 129.

Determining Data Types in Python

In the given code snippet, the datatype of the variable `var` changes from `int` to `str` after its value gets updated. Therefore, when we print the type of the variable using the `type()` function, it will output `int` and `str` in that order. So the correct answer is `int and str`.

Indicating Code Blocks in Python

In Python, code blocks are indicated through indentation.


# Example code block
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

In the above example, the code block corresponding to the "if" statement is indented. This indentation informs Python that the two print statements are part of the "if" statement's code block.

Correcting Writing and Style Errors in Code Snippet

Code:

python
a = [1, 2, 3]
a = tuple(a)
a[0] = 2
print(a)

Output:


TypeError: 'tuple' object does not support item assignment

Correction:

The code tries to assign a new value to the first element of the tuple 'a'. However, tuples are immutable in Python, which means that once they are created, we can't modify them. Therefore, trying to change an item in a tuple would result in a 'TypeError'.

A possible corrected version of this code could be:

python
a = [1, 2, 3]
a = tuple(a)
# Attempting to change a tuple would produce an error.
print("Tuple elements:", a)

Output:


Tuple elements: (1, 2, 3)

Comments added to explain the code.

Output of Code Snippet

float and int

The first print statement is performing standard division, which returns a float value. Therefore, the type of the result is float. The second print statement is performing integer division, which returns an integer value. Therefore, the type of the result is int.

Code Output

The output of the given code snippet will be:

15

Because the code initializes a list of numbers from 1 to 5 and then iterates through each element in the list, adds it to the variable "sum" on each iteration. Finally, it prints the value of the variable "sum," which is 15 (1 + 2 + 3 + 4 + 5).

Code output of a while loop printing multiples of 3

The following code will output the multiples of 3 not greater than 15:


count = 0
while True:
    if count % 3 == 0:
        print(count, end=" ")
    if count > 15:
        break
    count += 1

The output will be:

0 3 6 9 12 15

Python Concepts: Pointers

In Python, the concept of pointers is not used or required as it is a high-level language that utilizes dynamic memory allocation and garbage collection. Therefore, option D "All of the above" is not correct, since loops and dynamic typing are indeed part of Python.

# Example of a simple Python loop for i in range(10): print(i)

# Example of dynamic typing in Python example_variable = 5 print(example_variable) example_variable = "Now I'm a string" print(example_variable)

Recursively Finding the GCD of 2 Numbers

The output of the code snippet will be:

10

The function

solve()

calculates the GCD of two numbers recursively. In this case, it calculates the GCD of 20 and 50. The recursive call passes the remainder of the division of the larger number (50) by the smaller number (20) as the first argument (a), and the smaller number (20) as the second argument (b). This is done until the smaller number (a) becomes 0. At this point, the GCD becomes the second argument (b) which is 10 in this case. Therefore, the output is 10.

Python Code Output

The output of the code snippet will be: [2, 4, 6], [2, 4, 6].

This is because, in the code, the variable “a” is first assigned to [2, 4, 6]. Then, the function “solve()” is called with the argument “a”. In the function, “a” is assigned a new value [1, 3, 5]. However, this does not change the value of the original variable “a” which is still [2, 4, 6]. Therefore, the second print statement outputs the original value of “a”.

This is due to the fact that Python follows the concept of “Pass by Object Reference”. So, when a variable is passed as an argument to a function, its reference is passed, and not its value. Any changes made to the reference inside the function also affect the original variable.


def solve(a):
   a = [1, 3, 5]
a = [2, 4, 6]
print(a)
solve(a)
print(a)


Predicting the Output of a Code Snippet in Python

Code:


def func():
   global value
   value = "Local"

value = "Global"
func()
print(value)

Output: `Local`

Explanation:

The initial value of `value` is set to `"Global"`. When `func()` is called, the `global` keyword is used to specify that the `value` variable within the function should reference the global `value` variable, rather than creating a new local variable. The value of the global `value` variable is then changed to `"Local"`.

When `print(value)` is called outside of the function, it refers to the global `value` variable, which has been changed to `"Local"`. Therefore, the output of this program is `"Local"`.

Exception Handling in Python

In Python, the following statements are used for Exception Handling:

try

The

try

block is used to enclose the code that might raise exceptions.

except

The

except

block is used to handle the raised exceptions. It catches the exception and executes the code inside the block.

finally

The

finally

block is used to execute the code regardless of whether an exception was raised or not.

Therefore, the correct answer is All of the above.

H3. Swapping Two Numbers in Python

The output of the code will be:

3 1 1 3

This is because the variables a and b are initially assigned the values 3 and 1 respectively and are then printed. They are then swapped using the Pythonic way of variable assignment, i.e., a, b = b, a. Finally, the values of a and b are printed and they come out to be 1 and 3 respectively after the swapping is done.

Python Loops

In Python, the following types of loops are supported:

  • for loop
  • while loop

However, do-while loops are not explicitly supported in Python.

Checking for Element in a List in Python

In Python, we can use the `in` operator to check if a particular element is present in a list or not. The proper syntax for this is:

if element in my_list:

This will return `True` if the `element` is present in the `my_list`.

Similarly, we can also check if an element is not present in a list using the `not in` operator. The proper syntax for this is:

if element not in my_list:

This will return `True` if the `element` is not present in the `my_list`.

Example:


fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
  print("Yes, banana is in the fruits list")
  
if "orange" not in fruits:
  print("Yes, orange is not in the fruits list")

Output:

Yes, banana is in the fruits list
Yes, orange is not in the fruits list


Code Output Explanation

The output of the given code will be:
five neither thrive three
five neither three thrive
three three three three
five neither five neither

The given code defines a function called `thrive` that takes an argument `n`. The function checks if the number is a multiple of 15 and prints "thrive" if it is. If the number is not a multiple of 15, it checks if the number is a multiple of 3 or 5 or neither. If the number is neither a multiple of 3 nor 5, it prints "neither". If the number is a multiple of 3, it prints "three". If the number is a multiple of 5, it prints "five". The function is called with the arguments 35, 56, 15 and 39, which results in the given output.H3. Code Output Question

The output of the code will be:

Even

This is because the given number passed to the check function is 12, which is an even number. Therefore, the condition "a % 2 == 0" is True, and "Even" is printed to the console.The output of the code snippet will be: ['Monday', 'Tuesday']H3. Code Output Explanation

The output of the code snippet will be:

[1, 2, 1, 2, 1, 2]

The * operator, when used with lists in Python, performs the replication operation which replicates the elements of the list for the number of times mentioned.

In this case, list "a" has two elements [1,2]. So when we use the * operator with it and mention 3, it replicates the same list 3 times which results in [1,2,1,2,1,2].

Therefore, the output of the code snippet is [1, 2, 1, 2, 1, 2].The output of the code snippet will be:

['Sunday', 'Monday', 'Wednesday']

This is because the code snippet first creates a list `example` and initializes it with four string elements. Then, it uses the `del` keyword to delete the element at index 2 (which is the third element in the list). As a result, the element "Tuesday" is removed from the list, and the remaining elements are printed, which are "Sunday", "Monday", and "Wednesday".The type of the variable sorted_numbers will be list.

Answer:

The output of the following code snippet will be:

<class 'filter'>

The filter function returns an object of type “filter”.

H3. Code Output Explanation

The output of the above code will be:


[7, 19, 45, 89]

This is because the code first sorts the original tuple `numbers` in ascending order and stores the sorted result in `sorted_numbers`. Then, it creates a new list called `odd_numbers` that contains only the odd numbers from `sorted_numbers`. Finally, it prints the `odd_numbers` list, which contains the odd numbers from `numbers` in sorted order.The output of the code snippet will be:

54 is an even number

This is because the function is_even takes a number as an argument, checks if it's even or odd using the modulus operator, and returns a message stating whether the number is even or odd. In this case, the input number is 54, which is even, so the return message is "54 is an even number". The print statement then outputs this message to the console.## Updating Dictionary in Python using update() function

The `update()` function in python merges the contents of 2 dictionaries and stores them in the invoking dictionary. If there are any common keys, then the corresponding value from the parameter dictionary is used.

python
dict1 = {'first' : 'sunday', 'second' : 'monday'}
dict2 = {1: 3, 2: 4}
dict1.update(dict2)
print(dict1)

**Output:**

`{'first': 'sunday', 'second': 'monday', 1: 3, 2: 4}`

In the given code snippet, `dict1` and `dict2` are 2 different dictionaries containing different key-value pairs. The `update()` function is used to merge the contents of `dict2` dictionary into the `dict1`. Since both dictionaries do not have any common keys, the resulting dictionary contains all key-value pairs from both dictionaries. Hence the output of the above code snippet will be `{'first': 'sunday', 'second': 'monday', 1: 3, 2: 4}`.The output of the following code snippet will be:

{1, 2, 3, 4, 5}

Explanation:

The set s contains some elements which are repeated. However, when we print the set, only unique elements are displayed and all the duplicates are removed. Therefore, the output only contains the unique elements in the set s, which are {1, 2, 3, 4, 5}.The output of the following code snippet will be: {'World': 'Hello', 1: 'First'}.

Python's strptime() Function for Converting Dates to Time

The function in Python that converts a date to its corresponding time is strptime(). This function takes a date string and returns it as a time object. With strptime(), you can specify a format string that describes how to parse the input date string. This function is used to convert a date string to a datetime.datetime object in Python.

Code:

python
from datetime import datetime

# date string to be converted to corresponding time
date_str = '2022-10-25 15:42:12'

# specify format of date
format_str = '%Y-%m-%d %H:%M:%S'

# use strptime to convert date string to datetime object
converted_date = datetime.strptime(date_str, format_str)

# print the result
print(converted_date)

Output:


2022-10-25 15:42:12

In this example, a date string was provided and a format string was specified that matches the format of the input date string. The strptime() function was then used to convert the date string to a datetime object. Finally, the converted date object was printed to the console.

Therefore, the answer to the question is A. The function strptime() in Python is used to convert a date to its corresponding time.The expected output of the code snippet is:

pYtHoN PrOgRaMmInG

Explanation:

We have a string named "word" with the value "Python Programming". We obtain the length of the string using the len() function and assign it to the variable "n". We create two new strings, "word1" and "word2", derived from the original string using the upper() and lower() methods.

We then create an empty string named "converted_word" and iterate over every character in the string using the range() function with the length of the string as the argument. We use an if-else statement to check if the index of the character is even or odd. If it is even, we append the uppercase version of the character from "word2" to the "converted_word" string. If it is odd, we append the lowercase version of the character from "word1" to the "converted_word" string.

Finally, we print the modified string "converted_word".

Output of Code Snippet

The output of the following code snippet will be:


20

Explanation:

The given string `"4, 5"` is split into a list of two strings `['4', '5']` using the `.split()` method, which separates the string using the comma as a separator. These strings are then unpacked into two separate variables `x` and `y` (which are assigned string values `'4'` and `'5'` respectively).

The variables `x` and `y` are then converted into integers using the `int()` function and then multiplied together, which gives us the resulting product of `20`.

Therefore, the code will output `20`.H3. Lambda Function to Generate Perfect Squares of Numbers

The output of the given code snippet will be:

[0, 1, 4, 9, 16]

The code defines a lambda function "square" that takes an argument "x" and returns its square. Then it initializes an empty list "a". In the for loop, the range is 0-4 and "square" is called with each value to compute the square and append the result to the list "a". Finally, the list "a" is printed.

Thus, the output of the code will be a list of 5 perfect squares starting from 0 i.e [0, 1, 4, 9, 16].The output of the code snippet will be:

Sunday Monday Tuesday Wednesday

The function tester() accepts a variable number of arguments using the *argv syntax, which allows it to accept any number of positional arguments. In this case, it is called with four arguments - 'Sunday', 'Monday', 'Tuesday', and 'Wednesday'. When we iterate over the arguments in the function with the for loop, each argument is printed out with a space as the separator using the end parameter of the print() function. Therefore, the output of the function will be all the arguments passed during the function call, separated by spaces.

Python Function Arguments

When *args is used in a function definition, it allows the function to accept an arbitrary number of positional arguments. The arguments are stored in a tuple, which can be accessed using indexing.

Therefore, the answer is: Tuple.


    def my_function(*args):
        for arg in args:
            print(arg)

The output of the code snippet will be:

Sunday 1 Monday 2 Tuesday 3 Wednesday 4

Explanation: The function `tester()` takes keyword arguments using `**kwargs` which allows us to pass multiple keyword arguments. In this case, we are passing four keyword arguments (Sunday=1, Monday=2, Tuesday=3, Wednesday=4) to the function. In the for loop, we are iterating over the `kwargs` dictionary and printing the `key` and `value` of each argument with a space in between. Therefore, the output will be "Sunday 1 Monday 2 Tuesday 3 Wednesday 4".

Data type for *kwargs in a Python function

In Python, the *kwargs parameter allows a variable number of keyword arguments to be passed into a function. These keyword arguments are stored as a dictionary data type within the function. Thus, the correct answer is:

Dictionary.

Execution of Finally Block in Python

In Python, the

finally

block is used along with the

try

and

except

blocks. The main use of the finally block in Python is to close resources or file handles that were opened in the try block. It is executed whether an exception was raised or not in the try block.

To answer the question, the finally block will always be executed in a program whether an exception is encountered or not.

Here's an example below:


try:<br>
    f = open('sample.txt', 'r')<br>
    print(f.readline())<br>
except FileNotFoundError:<br>
    print('File not found')<br>
finally:<br>
    print('Finally block executed')<br>

In the code above, the

try

block is used to open the file

sample.txt

and read the first line. If the file is not found, the

except

block will be executed and print "File not found". The

finally

block will always be executed and print "Finally block executed", whether or not the

try

block raises an exception.

H3. Python code to understand math library functions

Code:

python
from math import *

# initialize variables a, b, and c
a = 2.19
b = 3.999999
c = -3.30

# apply math library functions and print the output
print(int(a), floor(b), ceil(c), fabs(c))

Output:


2 3 -3 3.3

The code uses the math library which contains mathematical functions to work with numbers. The `int()` function is used to convert `a` to an integer, `floor()` function returns the largest integer less than or equal to `b`. `ceil()` function returns the smallest integer greater than or equal to `c`. `fabs()` function returns the absolute value of `c`. The output of the code snippet will be `2 3 -3 3.3`.Code:

python
set1 = {1, 3, 5}
set2 = {2, 4, 6}
print(len(set1.union(set2)))

Output:


6

Code Output Explanation

The given code will give an error message as the `+` operator is not overloaded for Python sets. Instead, we can use the `union()` method to combine two sets into one. The `len()` function is then used to get the length of the set. In this case, the `union()` of both sets gives a set with elements `{1, 2, 3, 4, 5, 6}`. The `len()` of this set would be 6. Therefore, the output of the code is 6.

Python Exception Handling

The `raise` keyword is used in Python to manually raise exceptions. It is usually followed by the type of exception to be raised. Here is an example:

python
x = -1

if x < 0:
    raise ValueError("x cannot be negative")

In the example above, the `raise` keyword is used to manually raise a `ValueError` exception if `x` is negative. This allows for better control of program flow and error handling. It is often used in combination with the `try` and `except` keywords for handling exceptions.The output of the following code snippet will be:

{1, 3, 5, 6}

Explanation:

The ^ operator in sets returns a set containing elements that are in either of the sets, but not in both.

s1 = {1, 2, 3, 4, 5}

s2 = {2, 4, 6}

s1^s2 will return {1, 3, 5, 6} since 1, 3, and 5 belong to s1 but not to s2, and 6 belongs to s2 but not to s1. The elements 2 and 4 are common to both sets and are excluded from the output.

Python Set Operations

In Python, following are the valid set operations:

Union<br>Intersection<br>Difference

Therefore, the answer is: None of the above.

The output of the code snippet will be:

[1, 2]

Valid Escape Sequences in Python

The following are valid escape sequences in Python:

  • \n
  • \t
  • \\

Therefore, the correct answer is:

All of the above are valid escape sequences in Python.


Valid String Manipulation Functions in Python

All of the following functions are valid string manipulation functions in Python:

count()
upper()
strip()

You can use these functions to manipulate and transform strings in various ways, like:

  • count() - returns the number of occurrences of a substring in a string
  • upper() - returns the uppercase version of a string
  • strip() - removes whitespace from the beginning and end of a string

Python provides many other string manipulation functions, depending on your specific needs and use-case.

Module Import for Date Time Computations in Python

To handle date time computations in Python, we need to import the datetime module.

import datetime

Other modules like date, time and timedate are incorrect and can't handle all types of date time computations.

Disabling Assertions in Python

In Python, assertions can be disabled by passing the -O option when running the code. This can be done by running the code through the command line with the -O flag.

For example:


python -O my_script.py

By default, assertions are enabled in Python. However, if the -O flag is set, Python will optimize the code and remove all assertions.

Note that it is generally not recommended to disable assertions, as they can be useful for catching logical errors during development.H3. Understanding filter() function in Python

The output of the given code snippet will be:

['abc', [0], 1]

The filter() function applies a given function to each item of an iterable (list, tuple, etc.) and returns a new iterable containing only the items for which the function returns True.

Here, the bool function is passed to the filter function. The bool function returns True for any non-empty string, list, or non-zero value.

Thus, the filter function returns only the items in list a for which the bool function returns True. The resulting list is ['abc', [0], 1].

Python's Programming Language

Python's programming language is primarily written in C language. Though, some modules of Python's standard library are also written in other languages such as C++ and Java.

Evaluating an Expression in Python

The result of the following expression in Python `"2 ** 3 + 5 ** 2"` will be 33. The expression will be evaluated as 2 to the power of 3 plus 5 to the power of 2 which is equal to 8 plus 25. Therefore, the answer is 33.

Code:

python
result = 2 ** 3 + 5 ** 2 # Evaluate the expression
print(result) # print the result

Output:


33

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.