0% found this document useful (0 votes)
141 views86 pages

Assgnments

The document provides examples of common syntax errors in Python like incorrect variable assignment, indentation errors, misspelling variable names, type errors when concatenating different data types, accessing invalid list/dictionary indices, using incorrect list methods, logical errors in functions and more along with their fixes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
141 views86 pages

Assgnments

The document provides examples of common syntax errors in Python like incorrect variable assignment, indentation errors, misspelling variable names, type errors when concatenating different data types, accessing invalid list/dictionary indices, using incorrect list methods, logical errors in functions and more along with their fixes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

Syntax Errors in Python

1Example:

if x = 10:
print("x is equal to 10")
In this example, we are trying to assign the value 10 to the
variable x using the assignment operator (=) inside an if
statement.

But the correct syntax for comparing values in an if statement is


to use the comparison operator (==).

So here's how you fix this one:

if x == 10:
print("x is equal to 10")

2. Indentation Errors in Python


Example:

for i in range(10):
print(i)
In this example, the code inside the for loop is not indented
correctly.

Fix:

for i in range(10):
print(i)

3. Name Errors in Python


Example:

my_variable = 5
print(my_vairable)
In this example, we misspelled the variable name my_variable
as my_vairable.

Fix:

my_variable = 5
print(my_variable)

4. Example:

5. Example:

Example:

x = "5"
y = 10
result = x + y
In this example, we are trying to concatenate a string and an
integer, which is not possible.

Fix:

x = "5"
y = 10
result = int(x) + y
Here, we convert the string to an integer using the int() function
before performing the addition.

6.Example:
my_list = [1, 2, 3, 4]
print(my_list[5])
In this example, we are trying to access an item at index 5,
which is outside the range of the list.

Fix:

my_list = [1, 2, 3, 4]
print(my_list[3])
Here, we access the item at index 3, which is within the range
of the list.

7.Example:

my_dict = {"name": "John", "age": 25}


print(my_dict["gender"])
In this example, we are trying to access the value for the key
"gender", which does not exist in the dictionary.

Fix:

my_dict = {"name": "John", "age": 25}


print(my_dict.get("gender", "Key not found"))
Here, we use the get() method to access the value for the key
"gender". The second argument of the get() method specifies
the default value to return if the key does not exist.

8. Example:

my_list = [1, 2, 3, 4]
my_list.append(5)
my_list.add(6)
In this example, we are trying to add an item to the list using
the add() method, which does not exist for lists.
Fix:

my_list = [1, 2, 3, 4]
my_list.append(5)

9. TypeError:
x= “10”
y= 5
Z=x+y
print(z)

we cannot concatenatea string and an integer using the + operator. To fix


this error, we need to convert the integer y to a string before concatenating it
with x , like so:
x = "10"
y=5
Z = x + str(y)
print(z)

10.
my_string = "Hello, world!"
my_string.reverse()

This error message indicates that we are trying to access an attribute


(reverse) that is not defined for the type of object (str) we are working
with.
To fix this error, we need to use a different method or attribute that is defined
for strings, like [::-1] to reverse the string:
my_string = "Hello, world!"
reversed_string = my_string[::-1]
print(reversed_string)

11. def calculate_factorial(n):

result = 1
for i in range(1, n):
result = result * i
return result

print(calculate_factorial(5))

The reason is a logical error in the code that causes it to produce incorrect
results. The for loop is iterating from 1to n-1instead of from 1 to n , causing
the issue. This means that the factorial is being calculated incorrectly,
resulting in an incorrect output.

o fix this logical error, we need to change the range of the for loop to include
the number n itself. Here's the corrected code:
def calculate_factorial(n):
result = 1
for i in range(1, n+1):
result = result * i
return result

print(calculate_factorial(5))

1.Write a Python program to display the current date and time.


import datetime

now = datetime.datetime.now()

print ("Current date and time : ")

print (now.strftime("%Y-%m-%d %H:%M:%S"))

2,Write a Python program that accepts the user's first and last name and prints
them in reverse order with a space between them.

fname = input("Input your First Name : ")

lname = input("Input your Last Name : ")

print ("Hello " + lname + " " + fname)


3.Write a Python program that accepts the user's first and last name and prints
them in reverse order with a space between them.
color_list = ["Red","Green","White" ,"Black"]
print( "%s %s"%(color_list[0],color_list[-1]))

4.Write a Python program that accepts an integer (n) and computes the value of
n+nn+nnn.

Sample value of n is 5


a = int(input("Input an integer : "))

n1 = int( "%s" % a )

n2 = int( "%s%s" % (a,a) )

n3 = int( "%s%s%s" % (a,a,a) )

print (n1+n2+n3)

5.Write a Python program that prints the calendar for a given month and year.

Note: Use 'calendar' module.


import calendar

y = int(input("Input the year : "))

m = int(input("Input the month : "))

print(calendar.month(y, m))

6.Write a Python program to print the following 'here document'.

Sample string:
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
print("""

a string that you "don't" have to escape

This

is a ....... multi-line

heredoc string --------> example

""")

7.Write a Python program to test whether a passed letter is a vowel or not.

def is_vowel(char):

all_vowels = 'aeiou'

return char in all_vowels

print(is_vowel('c'))

print(is_vowel('e'))

8.Write a Python program to find the least common multiple (LCM) & GCD
GREATEST common divisor of two positive integers.

def lcm(x, y):

if x > y:

z=x

else:

z=y

while(True):

if((z % x == 0) and (z % y == 0)):

lcm = z

break

z += 1
return lcm

print(lcm(4, 6))

print(lcm(15, 17))

gcd

def gcd(x, y):

gcd = 1

if x % y == 0:

return y

for k in range(int(y / 2), 0, -1):

if x % k == 0 and y % k == 0:

gcd = k

break

return gcd

print("GCD of 12 & 17 =",gcd(12, 17))

print("GCD of 4 & 6 =",gcd(4, 6))

print("GCD of 336 & 360 =",gcd(336, 360))

9.Write a Python program to check whether a file exists.

Sample Solution-1:

Python Code:
import os.path

print(os.path.isfile('main.txt'))

print(os.path.isfile('main.py'))
10.Write a Python program to retrieve the path and name of the file currently
being executed.

Sample Solution:-

Python Code:
import os

print("Current File Name : ",os.path.realpath(__file__))

11.Write a Python program to parse a string to float or integer.

Sample Solution-1:

Python Code:
n = "246.2458"

print(float(n))

print(int(float(n)))

Copy
Sample Output:
246.2458
246

12.Write a Python program to list all files in a directory.

Sample Solution:-

Python Code:
from os import listdir

from os.path import isfile, join


files_list = [f for f in listdir('/home/students') if
isfile(join('/home/students', f))]

print(files_list);

13.Write a Python program to get an absolute file path.

Sample Solution-1:

Python Code:
def absolute_file_path(path_fname):

import os

return os.path.abspath('path_fname')

print("Absolute file path: ",absolute_file_path("test.txt"))

Copy
Sample Output:
Absolute file path: /home/students/path_fname

14.Write a Python program to sum the first n positive integers.

Sample Solution-1:

Python Code:
n = int(input("Input a number: "))

sum_num = (n * (n + 1)) / 2

print("Sum of the first", n ,"positive integers:", sum_num)

Copy
Sample Output:
Input a number: 2
Sum of the first 2 positive integers: 3.0

15.Write a Python program to calculate sum of digits of a number.

Python Code:
num = int(input("Input a four digit numbers: "))

x = num //1000

x1 = (num - x*1000)//100

x2 = (num - x*1000 - x1*100)//10

x3 = num - x*1000 - x1*100 - x2*10

print("The sum of digits in the number is", x+x1+x2+x3)

Copy
Sample Output:
Input a four digit numbers: 5245
The sum of digits in the number is 16

16.Write a Python program to sort files by date.

Sample Solution-1:

Python Code:
import glob

import os

files = glob.glob("*.txt")

files.sort(key=os.path.getmtime)

print("\n".join(files))
Copy
Sample Output:
result.txt
temp.txt
myfile.txt
mynewtest.txt
mytest.txt
abc.txt
test.txt
Sample Solution-2:

Python Code:
import os

os.chdir('d:')

result = sorted(filter(os.path.isfile, os.listdir('.')),


key=os.path.getmtime)

print('\n'.join(map(str, result)))

17.Write a Python program to count the number of occurrences of a specific


character in a string.

Python Code:
s = "The quick brown fox jumps over the lazy dog."

print("Original string:")

print(s)

print("Number of occurrence of 'o' in the said string:")

print(s.count("o"))

Copy
Sample Output:
Original string:
The quick brown fox jumps over the lazy dog.
Number of occurrence of 'o' in the said string:
4

18.Write a Python program to check whether a file path is a file or a directory.

Sample Solution:-

Python Code:
import os

path="abc.txt"

if os.path.isdir(path):

print("\nIt is a directory")

elif os.path.isfile(path):

print("\nIt is a normal file")

else:

print("It is a special file (socket, FIFO, device file)" )

print()

Copy
Sample Output:
It is a normal file

19.Write a Python program to get the size of a file.

Sample Solution-1:

Python Code:
import os

file_size = os.path.getsize("abc.txt")

print("\nThe size of abc.txt is :",file_size,"Bytes")

print()

Copy
Sample Output:
The size of abc.txt is : 0 Bytes
Sample Solution-2:

Python Code:
import os

file_size = os.stat('main.py')

print("\nThe size of abc.txt is :",file_size.st_size,"Bytes")

20.Write a program to display all prime numbers within a


range
start = 25
end = 50
print("Prime numbers between", start, "and", end, "are:")

for num in range(start, end + 1):


# all prime numbers are greater than 1
# if number is less than or equal to 1, it is not prime
if num > 1:
for i in range(2, num):
# check for factors
if (num % i) == 0:
# not a prime number so break inner loop and
# look for next number
break
else:
print(num)
21Reverse a given integer number

num = 76542
reverse_number = 0
print("Given Number ", num)
while num > 0:
reminder = num % 10
reverse_number = (reverse_number * 10) + reminder
num = num // 10
print("Revere Number ", reverse_number)

22Display numbers from a list using loop


numbers = [12, 75, 150, 180, 145, 525, 50]
# iterate each item of a list
for item in numbers:
if item > 500:
break
elif item > 150:
continue
# check if number is divisible by 5
elif item % 5 == 0:
print(item)

23Write a program to print the following number pattern using a loop.

1 2

1 2 3
1 2 3 4

1 2 3 4 5

print("Number Pattern ")

# Decide the row count. (above pattern contains 5 rows)


row = 5
# start: 1
# stop: row+1 (range never include stop number in result)
# step: 1
# run loop 5 times
for i in range(1, row + 1, 1):
# Run inner loop i+1 times
for j in range(1, i + 1):
print(j, end=' ')
# empty line after each row
print("")

24Display numbers divisible by 5 from a list


num_list = [10, 20, 33, 46, 55]
print("Given list:", num_list)
print('Divisible by 5:')
for num in num_list:
if num % 5 == 0:
print(num)

25Write a program to check if the given number is a palindrome number.


def palindrome(number):
print("original number", number)
original_num = number

# reverse the given number


reverse_num = 0
while number > 0:
reminder = number % 10
reverse_num = (reverse_num * 10) + reminder
number = number // 10

# check numbers
if original_num == reverse_num:
print("Given number palindrome")
else:
print("Given number is not palindrome")

palindrome(121)
palindrome(125)

26Write a program to create a function that takes two arguments, name and age,
and print their value.

# demo is the function name


def demo(name, age):
# print value
print(name, age)

# call function
demo("Ben", 25)

27Write a program to create function calculation() such that it can accept two


variables and calculate addition and subtraction. Also, it must return both
addition and subtraction in a single return call.

Solution 1:

def calculation(a, b):


addition = a + b
subtraction = a - b
# return multiple values separated by comma
return addition, subtraction

# get result in tuple format


res = calculation(40, 10)
print(res)

 Run
Solution 2:
def calculation(a, b):
return a + b, a - b

# get result in tuple format


# unpack tuple
add, sub = calculation(40, 10)
print(add, sub)

28Write a program to create a recursive function to calculate the sum of


numbers from 0 to 10.

def addition(num):
if num:
# call same function by reducing number by 1
return num + addition(num - 1)
else:
return 0

res = addition(10)
print(res)

29Print First 10 natural numbers using while loop

program 1: Print first 10 natural numbers


i = 1
while i <= 10:
print(i)
i += 1

30Write a program to accept a number from a user and calculate the sum of all
numbers from 1 to a given number

For example, if the user entered 10 the output should be 55 (1+2+3+4+5+6+7+8+9+10)

Solution 1: Using for loop and range() function


# s: store sum of all numbers
s = 0
n = int(input("Enter number "))
# run loop n times
# stop: n+1 (because range never include stop number in result)
for i in range(1, n + 1, 1):
# add current number to sum variable
s += i
print("\n")
print("Sum is: ", s)

 Run
Solution 2: Using the built-in function sum()

n = int(input("Enter number "))

# pass range of numbers to sum() function

x = sum(range(1, n + 1))

print('Sum is:', x)

31Display numbers from a list using loop

numbers = [12, 75, 150, 180, 145, 525, 50]


# iterate each item of a list
for item in numbers:
if item > 500:
break
elif item > 150:
continue
# check if number is divisible by 5
elif item % 5 == 0:
print(item)
32Count all letters, digits, and special symbols from a
given string

def find_digits_chars_symbols(sample_str):
char_count = 0
digit_count = 0
symbol_count = 0
for char in sample_str:
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1

print("Chars =", char_count, "Digits =", digit_count, "Symbol =",


symbol_count)

sample_str = "P@yn2at&#i5ve"
print("total counts of chars, Digits, and symbols \n")
find_digits_chars_symbols(sample_str)

33Write a program to count occurrences of all characters


within a string

str1 = "Apple"

# create a result dictionary


char_dict = dict()

for char in str1:


count = str1.count(char)
# add / update the count of a character
char_dict[char] = count
print('Result:', char_dict)
34Write a program to find all occurrences of “USA” in a given string ignoring the
case.
str1 = "Welcome to USA. usa awesome, isn't it?"
sub_string = "USA"

# convert string to lowercase


temp_str = str1.lower()

# use count function


count = temp_str.count(sub_string.lower())
print("The USA count is:", count)

35Write a program to add item 7000 after 6000 in the following Python List

list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]

# understand indexing
# list1[0] = 10
# list1[1] = 20
# list1[2] = [300, 400, [5000, 6000], 500]
# list1[2][2] = [5000, 6000]
# list1[2][2][1] = 6000

# solution
list1[2][2].append(7000)
print(list1)

36Remove all occurrences of a specific item from a list.

Given a Python list, write a program to remove all occurrences of item 20.

Given:

list1 = [5, 20, 15, 20, 25, 50, 20]


Expected output:

[5, 15, 25, 50]

Show Solution

Solution 1: Use the list comprehension

list1 = [5, 20, 15, 20, 25, 50, 20]

# list comprehension
# remove specific items and return a new list
def remove_value(sample_list, val):
return [i for i in sample_list if i != val]

res = remove_value(list1, 20)


print(res)

 Run

Solution 2: while loop (slow solution)

list1 = [5, 20, 15, 20, 25, 50, 20]

while 20 in list1:
list1.remove(20)
print(list1)

37Write a Python program to create a new dictionary by extracting the


mentioned keys from the below dictionary.

Given dictionary:

sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}
# Keys to extract
keys = ["name", "salary"]

sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york" }

keys = ["name", "salary"]

newDict = {k: sampleDict[k] for k in keys}


print(newDict)

 Run
Solution 2: Using the update() method and loop

sample_dict = {
"name": "Kelly",
"age": 25,
"salary": 8000,
"city": "New york"}

# keys to extract
keys = ["name", "salary"]

# new dict
res = dict()

for k in keys:
# add current key with its va;ue from sample_dict
res.update({k: sample_dict[k]})
print(res)

 38Convert two lists into a dictionary


keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

# empty dictionary
res_dict = dict()
for i in range(len(keys)):
res_dict.update({keys[i]: values[i]})
print(res_dict)

List of Python MCQs


1. Python is a ___object-oriented programming language.

A. Special purpose
B. General purpose
C. Medium level programming language
D. All of the mentioned above

Answer: B) General purpose

Explanation:

As a General Purpose Object-Oriented Programming Language, Python can


model real-world entities, which makes it a useful tool for data scientists. Because
it performs type checking at runtime, it is also known as dynamically typed code.
Python is a general-purpose programming language, which means that it is
widely used in every domain. This is due to the fact that it is very simple to
understand and scalable, which allows for rapid development.

Discuss this Question

2. Amongst the following, who is the developer of Python programming?


A. Guido van Rossum
B. Denis Ritchie
C. Y.C. Khenderakar
D. None of the mentioned above

Answer: A) Guido van Rossum

Explanation:

Python programming was created by Guido van Rossum. It is also called general-
purpose programming language.

Discuss this Question

3. Amongst which of the following is / are the application areas of Python


programming?

A. Web Development
B. Game Development
C. Artificial Intelligence and Machine Learning
D. All of the mentioned above

Answer: D) All of the mentioned above

Explanation:

Python programming is used in a variety of fields, including web development,


game development, artificial intelligence, and machine learning, among others.
Web Development - Python provides a number of web development frameworks,
including Django, Pyramid, and Flask, among others. Security, flexibility, and
scalability are all attributes of this framework. Development of Video Games -
PySoy and PyGame are two Python libraries that are used in the development of
video games. Artificial Intelligence and Machine Learning - There are a large
number of open-source libraries that can be used when developing AI/ML
applications, and many of these libraries are free.

Discuss this Question


4. Amongst which of the following is / are the Numeric Types of Data
Types?

A. int
B. float
C. complex
D. All of the mentioned above

Answer: D) All of the mentioned above

Explanation:

Numeric data types include int, float, and complex, among others. In information
technology, data types are the classification or categorization of knowledge
items. It represents the type of information that is useful in determining what
operations are frequently performed on specific data. In the Python
programming language, each value is represented by a different python data
type. Known as Data Types, this is the classification of knowledge items or the
placement of the information value into a specific data category. It is beneficial to
be aware of the quiet operations that are frequently performed on a worth.

Discuss this Question

5. list, tuple, and range are the ___ of Data Types.

A. Sequence Types
B. Binary Types
C. Boolean Types
D. None of the mentioned above

Answer: A) Sequence Types

Explanation:
The sequence Types of Data Types are the list, the tuple, and the range. In order
to store multiple values in an organized and efficient manner, we use the concept
of sequences. There are several types of sequences, including strings, Unicode
strings, lists, tuples, bytearrays, and range objects. Strings and Unicode strings are
the most common. Dictionary and set data structures are used to store non-
sequential information.

Discuss this Question

ADVERTISEMENT

6. Float type of data type is represented by the float class.

A. True
B. False

Answer: A) True

Explanation:

The float data type is represented by the float class of data types. A true number
with a floating-point representation is represented by the symbol. It is denoted
by the use of a decimal point. Optionally, the character e or E followed by a
positive or negative integer could be appended to the end of the string to
indicate scientific notation.

Discuss this Question

7. bytes, bytearray, memoryview are type of the ___ data type.

A. Mapping Type
B. Boolean Type
C. Binary Types
D. None of the mentioned above

Answer: C) Binary Types


Explanation:

The Binary type's data type is represented by the bytes, byte array, and memory
view types. Binary data manipulation is accomplished through the use of bytes
and byte array. The memory view makes use of the buffer protocol in order to
access the memory of other binary objects without the need to make a copy of
the data. Bytes objects are immutable sequences of single bytes that can only be
changed. When working with ASCII compatible data, we should only use them
when necessary.

Discuss this Question

8. The type() function can be used to get the data type of any object.

A. True
B. False

Answer: A) True

Explanation:

The type() function can be used to find out what type of data an object contains.
Typing an object passed as an argument to Python's type() function returns the
data type of the object passed as an argument to Python's type() function. This
function is extremely useful during the debugging phase of the process.

Discuss this Question

9. Binary data type is a fixed-width string of length bytes?

A. True
B. False

Answer: A) True

Explanation:
It is a fixed-width string of length bytes, where the length bytes is declared as an
optional specifier to the type, and its width is declared as an integer. If the length
is not specified, the default value is 1. When necessary, values are right-extended
to fill the entire width of the column by using the zero byte as the first byte.

Discuss this Question

10. Varbinary data type returns variable-width string up to a length of max-


length bytes?

A. TRUE
B. FALSE

Answer: A) TRUE

Explanation:

Varbinary - a variable-width string with a length of max-length bytes, where the


maximum number of bytes is declared as an optional specifier to the type, and
where the maximum number of bytes is declared as an optional specifier to the
type. The default attribute size is 80 bytes, and the maximum length is 65000
bytes. The default attribute size is 80 bytes. The range of binary values is not
extended to fill the entire width of the column.

Discuss this Question

ADVERTISEMENT

11. Amongst which of the following is / are the logical operators in Python?

A. and
B. or
C. not
D. All of the mentioned above

Answer: D) All of the mentioned above


Explanation:

Python's logical operators are represented by the terms and, or, and not. In
Python, logical operators are used to perform logical operations on the values of
variables that have been declared. Either true or false is represented by the value.
The truth values provide us with the information we need to figure out the
conditions. In Python, there are three types of logical operators: the logical AND,
the logical OR, and the logical NOT operators. Keywords or special characters are
used to represent operators in a program.

Discuss this Question

12. Is Python supports exception handling?

A. Yes
B. No

Answer: A) Yes

Explanation:

Unexpected events that can occur during a program's execution are referred to
as exceptions, and they can cause the program's normal flow to be interrupted.
Python provides exception handling, which allows us to write less error-prone
code while also testing various scenarios that may result in an exception later on
in the process.

Discuss this Question

13. What is the name of the operator ** in Python?

A. Exponentiation
B. Modulus
C. Floor division
D. None of the mentioned above
Answer: A) Exponentiation

Explanation:

The ** is an exponentiation operator in the Python programming language. In


Python, the ** operator is used to raise the number on the left to the power of
the exponent on the right, which is represented by the symbol **. In other words,
in the expression 2 ** 3, 2 is raised to the third power, which is a positive number.
In mathematics, we frequently see this expression written as 23, but what is really
happening is that the numbers 2 and 3 are being multiplied by themselves three
times. In Python, we would get the same result of 8 by running either 2 ** 3 or 2 *
2 * 2.

Discuss this Question

14. The % operator returns the ___.

A. Quotient
B. Divisor
C. Remainder
D. None of the mentioned above

Answer: C) Remainder

Explanation:

The % operator (it is an arithmetic operator) returns the amount that was left
over. This is useful for determining the number of times a given number is
multiplied by itself.

Discuss this Question

15. Amongst which of the following is / are the method of list?

A. append()
B. extend()
C. insert()
D. All of the mentioned above

Answer: D) All of the mentioned above

Explanation:

list.append(x), list.extend(iterable), list.insert(i, x) are the methods of


list. list.append(x) - add an item to the end of the
list. list.extend(iterable) - extend the list by appending all the items from the
iterable. list.insert(i, x) Insert an item at a given position.

Discuss this Question

ADVERTISEMENT

16. The list.pop ([i]) removes the item at the given position in the list?

A. True
B. False

Answer: A) True

Explanation:

The external is not a valid variable scope in PHP.

Discuss this Question

17. The list.index(x[, start[, end]]) is used to ___.

A. Return zero-based index in the list


B. Raises a ValueError if there is no such item
C. Both A and B
D. None of the mentioned above

Answer: C) Both A and B


Explanation:

The index(x[, start[, end]]) is used to return the zero-based index in the list of the
first item whose value is equal to x. index() is used to return the zero-based index
in the list of the first item whose value is equal to x. If there is no such item, the
method raises a ValueError. The optional arguments start and end are interpreted
in the same way as in the slice notation and are used to restrict the search to a
specific subsequence of the list of elements. Instead of using the start argument
to calculate the index, the returned index is computed relative to the beginning
of the full sequence.

Discuss this Question

18. Python Dictionary is used to store the data in a ___ format.

A. Key value pair


B. Group value pair
C. Select value pair
D. None of the mentioned above

Answer: A) Key value pair

Explanation:

Python Dictionary is used to store the data in a key-value pair format, which is
similar to that of a database. The dictionary data type in Python is capable of
simulating the real-world data arrangement in which a specific value exists for a
specific key when the key is specified. It is the data-structure that can be
changed. Each element of the dictionary is defined as follows: keys and values.

Discuss this Question

19. The following is used to define a ___.

d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}

A. Group
B. List
C. Dictionary
D. All of the mentioned above

Answer: C) Dictionary

Explanation:

With the help of curly braces (), we can define a dictionary that contains a list of
key-value pairs that are separated by commas. Each key and its associated value
are separated by a colon (:). For example:

d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}

Discuss this Question

20. Python Literals is used to define the data that is given in a variable or
constant?

A. True
B. False

Answer: A) True
Explanation:

It is possible to define literals in Python as data that is provided in a variable or


constant. Literal collections are supported in Python as well as String and
Numeric literals, Boolean and Boolean expressions, Special literals, and Special
expressions.

Discuss this Question

ADVERTISEMENT

21. Conditional statements are also known as ___ statements.

A. Decision-making
B. Array
C. List
D. None of the mentioned above

Answer: A) Decision-making

Explanation:

Conditional statements, also known as decision-making statements, are used to


make decisions. In programming, we want to be able to control the flow of
execution of our program, and we want to be able to execute a specific set of
statements only if a specific condition is met, and a different set of statements
only if the condition is not met. As a result, we use conditional statements to
determine whether or not a specific block of code should be executed based on a
given condition.

Discuss this Question

22. The if statement is the most fundamental decision-making statement?

A. True
B. False
Answer: A) True

Explanation:

The if statement is the most fundamental decision-making statement, and it


determines whether or not the code should be executed based on whether or not
the condition is met. If the condition in the if statement is met, a code body is
executed, and the code body is not otherwise executed. The statement can be as
simple as a single line of code or as complex as a block of code.

Discuss this Question

23. Amongst which of the following if syntax is true?

A. if condition:
B. #Will executes this block if the condition is true
C.
D. if condition
E. {
F. #Will executes this block if the condition is true
G. }
H.
I. if(condition)
J. #Will executes this block if the condition is true
K.
L. None of the mentioned above

Answer: A)

if condition:
#Will executes this block if the condition is true

Explanation:

If is a keyword which works with specified condition. If statement in Python has


the subsequent syntax:
if condition:
#Will executes this block if the condition is true

Discuss this Question

24. Amongst which of the following is / are the conditional statement in


Python code?

A. if a<=100:
B. if (a >= 10)
C. if (a => 200)
D. None of the mentioned above

Answer: A) if a<=100:

Explanation:

The if statement in Python is used to make decisions in various situations. It


contains a body of code that is only executed when the condition specified in the
if statement is true; if the condition is not met, the optional else statement is
executed, which contains code that is executed when the else condition is met.

Discuss this Question

25. Which of the following is not used as conditional statement in Python?

A. switch
B. if...else
C. elif
D. None of the mentioned above

Answer: A) switch

Explanation:
Python does not have a switch or case statement like other programming
languages. Because Python lacks switch statement functionality in comparison to
other programming languages, it is not recommended for beginners. As a result,
we use other alternatives that can replace the functionality of the switch case
statement and make programming easier and faster. We employ dictionary
mapping to get around this limitation.

Discuss this Question

26. Which of the following is false regarding conditional statement in


Python?

A. If-elif is the shortcut for the if-else chain


B. We use the dictionary to replace the Switch case statement
C. We cannot use python classes to implement the switch case statement
D. None of the mentioned above

Answer: C) We cannot use python classes to implement the switch case


statement

Explanation:

It is possible to shorten the if-else chain by using the if-elif construct. Use the if-
elif statement and include an else statement at the end, which will be executed if
none of the if-elif statements in the previous section are true. As a replacement
for the Switch case statement, we use the dictionary data type, whose key values
function similarly to those of the cases in a switch statement. When
implementing the switch case statement in Python, we can make use of Python
classes. A class is a type of object function Object() { [native code] } that can be
extended with properties and methods. So, let's look at an example of how to
perform a switch case using a class by creating a switch method within the
Python switch class and then calling it.

Discuss this Question


27. In Python, an else statement comes right after the block after 'if'?

A. True
B. False

Answer: A) True

Explanation:

After the 'if' condition, an else statement is placed immediately after the block. if-
else statements are used in programming in the same way that they are used in
the English language. The following is the syntax for the if-else statement:

if(condition):
Indented statement block for when condition is TRUE
else:
Indented statement block for when condition is FALSE

Discuss this Question

28. In a Python program, Nested if Statements denotes?

A. if statement inside another if statement


B. if statement outside the another if statement
C. Both A and B
D. None of the mentioned above

Answer: A) if statement inside another if statement

Explanation:

Nesting an if statement within another if statement is referred to as nesting in the


programming community. It is not always necessary to use a simple if statement;
instead, you can combine the concepts of if, if-else, and even if-elif-else
statements to create a more complex structure.

Discuss this Question


29. What will be the output of the following Python code?

a=7
if a>4: print("Greater")

A. Greater
B. 7
C. 4
D. None of the mentioned above

Answer: A) Greater

Explanation:

When only one statement needs to be executed within an if block, the short hand
if statement is used to accomplish this. This statement can be included in the
same line as the if statement, if necessary. When using Python's Short Hand if
statement, the following syntax is used:

if condition: statement

Discuss this Question

30. What will be the output of the following Python code?

x,y = 12,14

if(x+y==26):
print("true")
else:
print("false")

A. true
B. false

Answer: A) true
Explanation:

In this code the value of x = 12 and y = 14, when we add x and y the value will be
26 so x+y= =26. Hence, the given condition will be true.

Discuss this Question

ADVERTISEMENT

31. What will be the output of the following Python code?

x=13

if x>12 or x<15 and x==16:


print("Given condition matched")
else:
print("Given condition did not match")

A. Given condition matched


B. Given condition did not match
C. Both A and B
D. None of the mentioned above

Answer: A) Given condition matched

Explanation:

In this code the value of x = 13, and the condition 13>12 or 13<15 is true but
13==16 becomes falls. So, the if part will not execute and program control will
switch to the else part of the program and output will be "Given condition did
not match".

Discuss this Question

32. Consider the following code segment and identify what will be the
output of given Python code?
a = int(input("Enter an integer: "))
b = int(input("Enter an integer: "))

if a <= 0:
b = b +1
else:
a = a + 1

A. if inputted number is a negative integer then b = b +1


B. if inputted number is a positive integer then a = a +1
C. Both A and B
D. None of the mentioned above

Answer: C) Both A and B

Explanation:

In above code, if inputted number is a negative integer, then b = b +1 and if


inputted number is a positive integer, then a = a +1. Hence, the output will be
depending on inputted number.

Discuss this Question

33. In Python, ___ defines a block of statements.

A. Block
B. Loop
C. Indentation
D. None of the mentioned above

Answer: C) Indentation

Explanation:

Python's concept of indentation is extremely important because, if the Python


code is not properly indented, we will encounter an Indentation Error and the
code will not be able to be successfully compiled. In Python, to indicate a block of
code, we must indent each line of the block by the same amount on each line of
the block. As a result, indentation denotes the beginning of a block of
statements.

Discuss this Question

34. An ___ statement has less number of conditional checks than two
successive ifs.

A. if else if
B. if elif
C. if-else
D. None of the mentioned above

Answer: C) if-else

Explanation:

A single if-else statement requires fewer conditional checks than two


consecutives if statements. If the condition is true, the if-else statement is used to
execute both the true and false parts of the condition in question. The condition
is met, and therefore the if block code is executed, and if the condition is not
met, the otherwise block code is executed.

Discuss this Question

35. In Python, the break and continue statements, together are called ___
statement.

A. Jump
B. goto
C. compound
D. None of the mentioned above

Answer: B) goto

Explanation:
With the goto statement in Python, we are basically telling the interpreter to skip
over the current line of code and directly execute another one instead of the
current line of code. You must place a check mark next to the line of code that
you want the interpreter to execute at this time in the section labelled "target."

Discuss this Question

36. What will be the output of the following Python code?

num = 10

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

A. Positive number
B. Negative number
C. Real number
D. None of the mentioned above

Answer: A) Positive number

Explanation:

In this case, the If condition is evaluated first and then the else condition. If it is
true, the elif statement will be executed. If it is false, nothing will happen. elif is an
abbreviation for else if. It enables us to check for multiple expressions at the
same time. Similarly, if the condition for if is False, the condition for the next elif
block is checked, and so on. If all of the conditions are met, the body of the else
statement is run.

Discuss this Question

37. The elif statement allows us to check multiple expressions.


A. True
B. False

Answer: A) True

Explanation:

It is possible to check multiple expressions for TRUE and to execute a block of


code as soon as one of the conditions evaluates to TRUE using the elif statement.
The elif statement is optional in the same way that the else statement is. The
difference between elif and else is that, unlike else, where there can only be one
statement, elif statements can be followed by an arbitrary number of statements.

Discuss this Question

38. What will be the output of the following Python code?

i=5
if i>11 : print ("i is greater than 11")

A. No output
B. Abnormal termination of program
C. Both A and B
D. None of the mentioned above

Answer: C) Both A and B

Explanation:

In the above code, the assign value of i = 5 and as mentioned in the condition if
5 > 11: print ("i is greater than 11"), here 5 is not greater than 11 so condition
becomes false and there will not be any output and program will be abnormally
terminated.

Discuss this Question


39. What will be the output of the following Python code?

a = 13
b = 15
print("A is greater") if a > b else print("=") if a == b else
print("B is greater")

A. A is greater
B. B is greater
C. Both A and B
D. None of the mentioned above

Answer: B) B is greater

Explanation:

In the above code, the assign value for a = 13 and b = 15. There are three
conditions mentioned in the code,

1. print("A is greater") if a > b , here 13 is not greater than 15 so condition


becomes false
2. print("=") if a == b , here 13 is not equal to 15 so condition becomes false
3. else print("B is greater"), condition 1 and 2 will not be true so program
control will switch to else part and output will be "B is greater".

Discuss this Question

40. If a condition is true the not operator is used to reverse the logical state?

A. True
B. False

Answer: A) True

Explanation:

In order to make an if statement test whether or not something occurred, we


must place the word not in front of our condition. When the not operator is used
before something that is false, it returns true as a result. And when something
that is true comes before something that is false, we get False. That is how we
determine whether or not something did not occur as claimed. In other words,
the truth value of not is the inverse of the truth value of yes. So, while it may not
appear to be abstract, this operator simply returns the inverse of the Boolean
value.

Discuss this Question

41. Loops are known as ___ in programming.

A. Control flow statements


B. Conditional statements
C. Data structure statements
D. None of the mentioned above

Answer: A) Control flow statements

Explanation:

The control flow of a program refers to the sequence in which the program's
code is executed. Conditional statements, loops, and function calls all play a role
in controlling the flow of a Python program's execution.

Discuss this Question

42. The for loop in Python is used to ___ over a sequence or other iterable
objects.

A. Jump
B. Iterate
C. Switch
D. All of the mentioned above

Answer: B) Iterate
Explanation:

It is possible to iterate over a sequence or other iterable objects using the for
loop in Python. The process of iterating over a sequence is referred to as
traversal. Following syntax can be follow to use for loop in Python Program –

for val in sequence:


...
loop body
...

For loop does not require an indexing variable to set beforehand.

Discuss this Question

43. With the break statement we can stop the loop before it has looped
through all the items?

A. True
B. False

Answer: A) True

Explanation:

In Python, the word break refers to a loop control statement. It serves to control


the sequence of events within the loop. If you want to end a loop and move on to
the next code after the loop; the break command can be used to do so. When an
external condition causes the loop to terminate, it represents the common
scenario in which the break function is used in Python.

Discuss this Question

44. The continue keyword is used to ___ the current iteration in a loop.

A. Initiate
B. Start
C. End
D. None of the mentioned above

Answer: C) End

Explanation:

The continue keyword is used to terminate the current iteration of a for loop (or a
while loop) and proceed to the next iteration of the for loop (or while loop). With
the continue statement, you have the option of skipping over the portion of a
loop where an external condition is triggered, but continuing on to complete the
remainder of the loop. As a result, the current iteration of the loop will be
interrupted, but the program will continue to the beginning of the loop. The
continue statement will be found within the block of code that is contained
within the loop statement, and is typically found after a conditional if statement.

Discuss this Question

45. Amongst which of the following is / are true about the while loop?

A. It continually executes the statements as long as the given condition is true


B. It first checks the condition and then jumps into the instructions
C. The loop stops running when the condition becomes fail, and control will
move to the next line of code.
D. All of the mentioned above

Answer: D) All of the mentioned above

Explanation:

While loops are used to execute statements repeatedly as long as the condition is
met, they are also used to execute statements once. It begins by determining the
condition and then proceeds to execute the instructions. Within the while loop,
we can include any number of statements that we want. The condition can be
anything we want it to be depending on our needs. When the condition fails, the
loop comes to an end, and the execution moves on to the next line of code in the
program.

Discuss this Question

46. The ___ is a built-in function that returns a range object that consists
series of integer numbers, which we can iterate using a for loop.

A. range()
B. set()
C. dictionary{}
D. None of the mentioned above

Answer: A) range()

Explanation:

This type represents an immutable sequence of numbers and is commonly used


in for loops to repeat a specific number of times a given sequence of numbers.
The range() function in Python generates an immutable sequence of numbers
beginning with the given start integer and ending with the given stop integer. For
loops, we can use the range() built-in function to return an object that contains a
series of integer numbers, which we can then iterate through using a for loop.

Discuss this Question

47. What will be the output of the following Python code?

for i in range(6):
print(i)

A. 0
1
2
3
4
5
B. 0
1
2
3
C. 1
2
3
4
5
D. None of the mentioned above

Answer: A)
0
1
2
3
4
5

Explanation:

The range(6) is define as function. Loop will print the number from 0.

Discuss this Question

48. The looping reduces the complexity of the problems to the ease of the
problems?

A. True
B. False

Answer: A) True

Explanation:
The looping simplifies the complex problems into the easy ones. It enables us to
alter the flow of the program so that instead of writing the same code again and
again, we can repeat the same code for a finite number of times.

Discuss this Question

49. The while loop is intended to be used in situations where we do not


know how many iterations will be required in advance?

A. True
B. False

Answer: A) True

Explanation:

The while loop is intended to be used in situations where we do not know how
many iterations will be required in advance. When a while loop is used, the block
of statements within it is executed until the condition specified within the while
loop is satisfied. It is referred to as a pre-tested loop in some circles.

Discuss this Question

50. Amongst which of the following is / are true with reference to loops in
Python?

A. It allows for code reusability to be achieved.


B. By utilizing loops, we avoid having to write the same code over and over
again.
C. We can traverse through the elements of data structures by utilizing
looping.
D. All of the mentioned above

Answer: D) All of the mentioned above

Explanation:
Following point's shows the importance of loops in Python.

 It allows for code reusability to be achieved.


 By utilizing loops, we avoid having to write the same code over and over
again.
 We can traverse through the elements of data structures by utilizing
looping.

Discuss this Question

51. A function is a group of related statements which designed specifically


to perform a ___.

A. Write code
B. Specific task
C. Create executable file
D. None of the mentioned above

Answer: B) Specific task

Explanation:

A function is a group of related statements designed specifically to perform a


specific task. Functions make programming easier to decompose a large problem
into smaller parts. The function allows programmers to develop an application in
a modular way. As our program grows larger and larger, functions make it more
organized and manageable.

Discuss this Question

52. Amongst which of the following is a proper syntax to create a function


in Python?

A. def function_name(parameters):
B. ...
C. Statements
D. ...
E.
F. def function function_name:
G. ...
H. Statements
I. ...
J.
K. def function function_name(parameters):
L. ...
M. Statements
N. ...
O.
P. None of the mentioned above

Answer: A)

def function_name(parameters):
...
Statements
...

Explanation:

To define a function we follow the syntax mentioned in the answer section. def


keyword marks the start of the function header. We start from the def keyword
and write the name of the function along with function parameters. Function
naming follows the naming rules to write identifiers in Python. Arguments or
parameters are passed as function arguments. Function arguments are optional.
A colon (:) denotes the end of the function header.

def function_name(parameters):
...
Statements
...

Discuss this Question

53. Once we have defined a function, we can call it?


A. True
B. False

Answer: A) True

Explanation:

Once a function has been defined, it can be called from another function, a
program, or even from the Python prompt itself. To call a function, we simply
type the name of the function followed by the appropriate parameters into the
command line.

For example-

def user_name(name):
# This function greets to user
# to put name
print("Hello, " + name + ".")

user_name("Amit") # Amit passed as function argument

# Output: Hello, Amit.

Discuss this Question

54. Amongst which of the following shows the types of function calls in
Python?

A. Call by value
B. Call by reference
C. Both A and B
D. None of the mentioned above

Answer: C) Both A and B

Explanation:

Call by value and Call by reference are the types of function calls in Python.
 Call by value - When, we call a function with the values i.e. to pass the
variables (not their references), the values of the passing arguments cannot
be changed inside the function.
 Call by reference - When, we call a function with the reference/object, the
values of the passing arguments can be changed inside the function.

Discuss this Question

55. What will be the output of the following Python code?

def show(id,name):
print("Your id is :",id,"and your name is :",name)

show(12,"deepak")

A. Your id is: 12 and your name is: deepak


B. Your id is: 11 and your name is: Deepak
C. Your id is: 13 and your name is: Deepak
D. None of the mentioned above

Answer: A) Your id is: 12 and your name is: deepak

Explanation:

If we define a function in Python with parameters, and at the time of calling


function it requires parameters. In above code passing arguments are 12, and
Deepak. So, Output will be Your id is: 12 and your name is: deepak

Discuss this Question

56. Amongst which of the following is a function which does not have any
name?

A. Del function
B. Show function
C. Lambda function
D. None of the mentioned above

Answer: C) Lambda function

Explanation:

Lambda function is an anonymous function, which means that it does not have a
name, as opposed to other functions. Unlike other programming languages,
Python allows us to declare functions without using the def keyword, which is
what we would normally do to declare a function. As an alternative, the lambda
keyword is used to declare the anonymous functions that will be used
throughout the program. When compared to other functions, lambda functions
can accept any number of arguments, but they can only return a single value,
which is represented by an expression.

Syntax:

lambda arguments: expression

Discuss this Question

57. Can we pass List as an argument in Python function?

A. Yes
B. No

Answer: A) Yes

Explanation:

In a function, we can pass any data type as an argument, such as a string or a


number or a list or a dictionary, and it will be treated as if it were of that data
type inside the function. The following code exemplifies this –

def St_list(student):
for x in student:
print(x)
students = ["Anil", "Rex", "Jerry"]
St_list(students)

"""
Output:
Anil
Rex
Jerry
"""

Discuss this Question

58. A method refers to a function which is part of a class?

A. True
B. False

Answer: A) True

Explanation:

A method is a function that is a part of a class that has been defined. It is


accessed through the use of an instance or object of the class. A function, on the
other hand, is not restricted in this way: it simply refers to a standalone function.
This implies that all methods are functions, but that not all functions are methods
in the same sense.

Discuss this Question

59. The return statement is used to exit a function?

A. True
B. False

Answer: A) True

Explanation:
The return statement is used to exit a function and go back to the place from
where it was called.

Syntax of return:

return [expression_list]

In this statement, you can include an expression that will be evaluated and the
resulting value will be returned. A function will return the None object if there is
no expression in the statement or if the return statement itself is not present
within a function's body.

Discuss this Question

60. Scope and lifetime of a variable declared in a function exist till the
function exists?

A. True
B. False

Answer: A) True

Explanation:

It is the portion of a program where a variable is recognized that is referred to as


its scope. It is not possible to see the parameters and variables defined within a
function from outside of the function. As a result, they are limited in their
application. The lifetime of a variable is the period of time during which the
variable is stored in the memory of the computer. The lifetime of variables
contained within a function is equal to the length of time the function is in
operation. When we return from the function, they are completely destroyed. As
a result, a function does not retain the value of a variable from previous calls to
the function.

Discuss this Question


61. File handling in Python refers the feature for reading data from the file
and writing data into a file?

A. True
B. False

Answer: A) True

Explanation:

File handling is the capability of reading data from and writing it into a file in
Python. Python includes functions for creating and manipulating files, whether
they are flat files or text documents. We will not need to import any external
libraries in order to perform general IO operations because the IO module is the
default module for accessing files.

Discuss this Question

62. Amongst which of the following is / are the key functions used for file
handling in Python?

A. open() and close()


B. read() and write()
C. append()
D. All of the mentioned above

Answer: D) All of the mentioned above

Explanation:

The key functions used for file handling in Python


are: open(), close(), read(), write(), and append(). the open() function is used to
open an existing file, close() function is used to close a file which opened, read()
function is used when we want to read the contents from an existing file, write()
function is used to write the contents in a file and append() function is used when
we want to append the text or contents to a specific position in an existing file.

Discuss this Question


63. Amongst which of the following is / are needed to open an existing file?

A. filename
B. mode
C. Both A and B
D. None of the mentioned above

Answer: C) Both A and B

Explanation:

In most cases, only the filename and mode parameters are required, with the rest
of the parameters implicitly set to their default values.

Following code demonstrates the example of how to open a file -

f = open ("file.txt")

Discuss this Question

64. Binary files are stored in the form of 0s and 1s?

A. True
B. False

Answer: A) True

Explanation:

Binary files are also stored in terms of bytes (0s and 1s), but, unlike text files,
these bytes do not represent the ASCII values of the characters that are contained
within them. A binary file is a sequence of bytes that is stored in a computer's
memory. Even a single bit change can corrupt a file, rendering it unreadable by
the application that is attempting to read it. In addition, because the binary file's
contents are not human readable, it is difficult to correct any errors that may
occur in the binary file.

Discuss this Question

65. The function file_object.close() is used to ___.

A. To open the existing file


B. To append in an opened file
C. To close an opened file
D. None of the mentioned above

Answer: C) To close an opened file

Explanation:

To close a file that has been opened, use the file object.close() function. To
accomplish this, the Python language provides the close() method. When a file is
closed, the system releases the memory that was allocated to it.

Discuss this Question

66. Python always makes sure that any unwritten or unsaved data is written
to the file before it is closed?

A. True
B. False

Answer: A) True

Explanation:

Whenever a file is closed, Python ensures that any unwritten or unsaved data is
flushed out or written to the file's header before the file is closed. As a result, it is
always recommended that we close the file once our work is completed.
Additionally, if the file object is reassigned to a different file, the previous file is
automatically closed as well.

Discuss this Question

67. The write() method takes a string as an argument and ___.

A. writes it to the text file


B. read from the text file
C. append in a text file
D. None of the mentioned above

Answer: A) writes it to the text file

Explanation:

The write() method accepts a string as an argument and writes it to the text file
specified by the filename parameter. The write() method returns the number of
characters that were written during a single execution of the write() function. A
newline character (n) must also be added at the end of every sentence to indicate
the end of a line.

Discuss this Question

68. The seek() method is used to ___.

A. Saves the file in secondary storage


B. Position the file object at a particular position in a file
C. Deletes the file form secondary storage
D. None of the mentioned above

Answer: B) Position the file object at a particular position in a file

Explanation:
The seek() method is used to position a file object at a specific location within a
file's hierarchy.

Discuss this Question

69. Amongst which of the following function is / are used to create a file
and writing data?

A. append()
B. open()
C. close()
D. None of the mentioned above

Answer: B) open()

Explanation:

To create a text file, we call the open() method and pass it the filename and the
mode parameters to the function. If a file with the same name already exists, the
open() function will behave differently depending on whether the write or
append mode is used to open the file. Write mode (w) will cause all of the
existing contents of the file to be lost, and a new file with the same name will be
created with the same contents as the existing file.

Discuss this Question

70. The readline() is used to read the data line by line from the text file.

A. True
B. False

Answer: A) True

Explanation:
It is necessary to use readline() in order to read the data from a text file line by
line. The lines are displayed by employing the print() command. When the
readline() function reaches the end of the file, it will return an empty string.

Discuss this Question

71. The module Pickle is used to ___.

A. Serializing Python object structure


B. De-serializing Python object structure
C. Both A and B
D. None of the mentioned above

Answer: C) Both A and B

Explanation:

Pickle is a Python module that allows you to save any object structure along with
its associated data. Pickle is a Python module that can be used to serialize and
de-serialize any type of Python object structure. Serialization is the process of
converting data or an object stored in memory to a stream of bytes known as
byte streams, which is a type of data stream. These byte streams, which are
contained within a binary file, can then be stored on a disc, in a database, or
transmitted over a network. Pickling is another term for the serialization process.
De-serialization, also known as unpickling, is the inverse of the pickling process,
in which a byte stream is converted back to a Python object through the pickling
process.

Discuss this Question

72. Amongst which of the following is / are the method of convert Python
objects for writing data in a binary file?

A. set() method
B. dump() method
C. load() method
D. None of the mentioned above

Answer: B) dump() method

Explanation:

The dump() method is used to convert Python objects into binary data that can
be written to a binary file. The file into which the data is to be written must be
opened in binary write mode before the data can be written. To make use of the
dump() method, we can call this function with the parameters data object and file
object. There are two objects in this case: data object and file object. The data
object object is the object that needs to be dumped to the file with the file
handle named file_ object.

Discuss this Question

73. Amongst which of the following is / are the method used to unpickling
data from a binary file?

A. load()
B. set() method
C. dump() method
D. None of the mentioned above

Answer: B) set() method

Explanation:

The load() method is used to unpickle data from a binary file that has been
compressed. The binary read (rb) mode is used to load the file that is to be
loaded. If we want to use the load() method, we can write Store object = load(file
object) in our program. The pickled Python object is loaded from a file with a file
handle named file object and stored in a new file handle named store object. The
pickled Python object is loaded from a file with a file handle named file object
and stored in a new file handle named store object.
Discuss this Question

74. A text file contains only textual information consisting of ___.

A. Alphabets
B. Numbers
C. Special symbols
D. All of the mentioned above

Answer: D) All of the mentioned above

Explanation:

Unlike other types of files, text files contain only textual information, which can
be represented by alphabets, numbers, and other special symbols. These types of
files are saved with extensions such as.txt,.py,.c,.csv,.html, and so on. Each byte in
a text file corresponds to one character in the text.

Discuss this Question

75. The writelines() method is used to write multiple strings to a file?

A. True
B. False

Answer: A) True

Explanation:

In order to write multiple strings to a file, the writelines() method is used. The


writelines() method requires an iterable object, such as a list, tuple, or other
collection of strings, to be passed to it.

1. Do we need to compile a program before execution in Python?


 Yes
 No

2. How to output the string “May the odds favor you” in Python?
 print(“May the odds favor you”)
 echo(“May the odds favor you”)
 System.out(“May the odds favor you”)
 printf(“May the odds favor you”)

3. How to create a variable in Python with a value 22.6?


 int a = 22.6
 a = 22.6
 Integer a = 22.6
  None of the above

4. How to add a single-line comment in Python?


 /* This is a comment */
 !! This is a comment
 // This is a comment
 # This is a comment

5. How to represent 261500000 as a floating number in Python?


 2.615E8
 261500000
 261.5E8
 2.6

6. Select the correct example of the complex datatype in Python


 3 + 2j
 -100j
 5j
 All of the above are correct
7. What is the correct way of creating a multi-line string in Python?
 str = “”My name is Kevin and I
live in New York””
 str = “””My name is Kevin and I
live in New York”””
 str = “My name is Kevin and I
live in New York”
 All of the above

8. How to convert the uppercase letters in the string to lowercase in


Python?
 lowercase()
 capitalize()
 lower()
 toLower()

9. How to access substring “Kevin” from the following string


declaration in Python:

2 str = "My name is Kevin"

 str[11:16]
 str(11:16)
 str[11][16]
 str[11-16]

10. Which of the following is the correct way to access a specific


character? Let’s say we need to access the character “K” from the
following string in Python.

2 str = "My name is Kevin"


 str(11)
 str[11]
 str:9
 None of the above

11. Which Python module is used to parse dates in almost any string
format?
 datetime module
 time module
 calendar module
 dateutil module

12. Which of the following is the correct way to indicate Hexadecimal


Notation in Python?
 str = ‘\62’
 str = ’62’
 str = “62”
 str = ‘\x62’

13. To begin slicing from the end of the string, which of the following is
used in Python?
 Indexing
 Negative Indexing
 Begin with the 0th index
 Escape Characters

14. How to fetch characters from a given range in Python?


 [:]
 in operator
 []
 None of the above
15. How to capitalize only the first letter of a sentence in Python?
 uppercase() method
 capitalize() method
 upper() method
 None of the above

16. What is the correct way to get the maximum value from Tuple in
Python?
 print (max(mytuple));
 print (maximum(mytuple));
 print (mytuple.max());
 print (mytuple.maximum);

17. How to fetch and display only the keys of a Dictionary in Python?
 print(mystock.keys())
 print(mystock.key())
 print(keys(mystock))
 print(key(mystock))

18. How to align a string centrally in Python?


 align() method
 center() method
 fill() method
 None of the above

19. How to access value for key “Product” in the following Python
Dictionary:

2 mystock = {

3 "Product": "Earphone",

4 "Price": 800,
5 "Quantity": 50,

6 "InStock" : "Yes"

7}

 mystock[“Product”]
 mystock(“Product”)
 mystock[Product]
 mystock(Product)

20. How to set the tab size to 6 in Python Strings?


 expandtabs(6)
 tabs(6)
 expand(6)
 None of the above

21. ___________ uses square brackets for comma-separated values


in Python? Fill in the blanks with a Python collection.
 Lists
 Dictionary
 Tuples
 None of the above

22. Are Python Tuples faster than Lists?


 TRUE
 FALSE

23. How to find the index of the first occurrence of a specific value “i”,
from the string “This is my website”?
 str.find(“i”)
 str.find(i)
 str.index()
 str.index(“i”)
24. How to display whether the date is AM/PM in Python?
 Use the %H format code
 Use the %p format code
 Use the %y format code
 Use the %I format code

25. Which of the following is the correct way to access a specific


element from a Multi-Dimensional List?
 list[row_size:column_size]
 list[row_size][column_size]
 list[(row_size)(column_size)]
 None of the above

26. Which of the following Bitwise operators in Python shifts the left
operand value to the right, by the number of bits in the right operand?
The rightmost bits while shifting fall off.
 Bitwise XOR Operator
 Bitwise Right Shift Operator
 Bitwise Left Shift Operator
 None of the Above

27. How to specify range of index in Python Tuples? Let’s say our
tuple name is “mytuple”
 print(mytuple[1:4])
 print(mytuple[1 to 4])
 print(mytuple[1-4])
 print(mytuple[].slice[1:4])

28. How to correctly create a function in Python?


 demoFunction()
 def demoFunction()
 function demoFunction()
 void demoFunction()

29. Which one of the following is a valid identifier declaration in


Python?
 str = “demo666”
 str = “666”
 str = “demo demo2”
 str = “$$$666”

30. How to check whether all the characters in a string is printable?


 print() method
 printable() method
 isprintable() method
 echo() method

31. How to delete an element in a Dictionary with a specific key. Let’s


say we need to delete the key “Price”
 del dict[‘Price’]
 del.dict[‘Price’]
 del dict(‘Price’)
 del.dict[‘Price’]

32. How to swap cases in Python i.e. lowercase to uppercase and vice
versa?
 casefold() method
 swapcase() method
 case() method
 title() method

33. The def keyword is used in Python to _______?


 Define a function name
 Define a list
 Define an array
 Define a Dictionary

34. Which of the following is used to empty the Dictionary in Python?


Let’s say our dictionary name is “mystock”.
 mystock.del()
 clear mystock
 del mystock
 mystock.clear()

35. How to display only the day number of years in Python?


 date.strftime(“%j”)
 date.strftime(“%H”)
 date.strftime(“%I”)
 date.strftime(“%p”)

36. What is used in Python functions, if you have no idea about the
number of arguments to be passed?
 Keyword Arguments
 Default Arguments
 Required Arguments
 Arbitrary Arguments

37. What is the correct way to create a Dictionary in Python?


 mystock = {“Product”: “Earphone”, “Price”: 800, “Quantity”: 50}
 mystock = {“Product”- “Earphone”, “Price”-800, “Quantity”-50}
 mystock = {Product[Earphone], Price[800], Quantity[50]}
 None of the above
38. In Python Functions, what is to be used to skip arguments or even
pass them in any order while calling a function?
 Keyword arguments
 Default Arguments
 Required Arguments
 Arbitrary Arguments

39. How to get the total length of a Tuple in Python?


 count() method
 length() method
 len() method
 None of the above

40. How to access a value in Tuple?


 mytuple(1)
 mytuple{1}
 mytuple[1]
 None of the above

41. What is to be used to create a Dictionary of arguments in a Python


function?
 Arbitrary arguments in Python (*args)
 Arbitrary keyword arguments in Python (**args)
 Keyword Arguments
 Default Arguments

42. How to convert the lowercase letters in the string to uppercase in


Python?
 upper()
 uppercase()
 capitalize()
 toUpper()
43. What is the correct way to get the minimum value from a List in
Python?
 print (minimum(mylist));
 print (min(mylist));
 print (mylist.min());
 print (mylist.minimum());

44. Is using a return statement optional in a Python Function?


 Yes
 No

45. Which of the following correctly convert int to float in Python?


 res = float(10)
 res = convertToFloat(10)
 None of the above

46. How to get the type of a variable in Python?


 print(typeOf(a))
 print(typeof(a))
 print(type(a))
 None of the above

47. How to compare two operands in Python and check for equality?
Which operator is to be used?
 =
 in operator
 is operator
 == (Answer)
48. What is the correct way to get minimum value from Tuple?
 print (min(mytuple));
 print (minimum(mytuple));
 print (mytuple.min());
 print (mytuple.minimum);

49. How to display only the current month’s number in Python?


 date.strftime(“%H”)
 date.strftime(“%I”)
 date.strftime(“%p”)
 date.strftime(“%m”)

50. How to compare two objects and check whether they have the
same memory locations?
 is operator
 in operator
 **
 Bitwise operators

51. How to fetch and display only the values of a Dictionary in Python?
 print(mystock.value())
 print(mystock.values())
 print(values(mystock))
 print(value(mystock))

52. Which operator is used in Python to raise numbers to the power?


 Bitwise Operators
 Exponentiation Operator (**)
 Identity Operator (is)
 Membership Operators (in)
53. Can we create a Tuple in Python without parenthesis?
 TRUE
 FALSE

54. ____________ represents key-value pair in Python?


 Tuples
 Lists
 Dictionary
 All the Above

55. Which of the following Bitwise operators sets each bit to 1, if only
one of them is 1, i.e. if only one of the two operands is 1?
 Bitwise XOR
 Bitwise OR
 Bitwise AND
 Bitwise NOT

56. What is the correct way to get the maximum value from a List in
Python?
 print (maximum(mylist));
 print (mylist.max());
 print (max(mylist));
 print (mylist.maximum());

57. An example to correctly begin searching from the end range of


index in Python Tuples. Let’s say our Python Tuple has 4 elements
 print(mytuple[-3 to -1])
 print(mytuple[3-1])
 print(mytuple[].slice[-3:-1])
 print(mytuple[-3:-1])
58. Which of the following Bitwise operators in Python shifts the left
operand value to the left, by the number of bits in the right operand?
The leftmost bits while shifting fall off.
 Bitwise XOR Operator
 Bitwise Right Shift Operator
 Bitwise Left Shift Operator
 None of the Above

59. Can we update Tuples or any of its elements in Python after the
assignment?
 Yes
 No

60. How to display only the current month’s name in Python?


 date.strftime(“%H”)
 date.strftime(“%B”)
 date.strftime(“%m”)
 date.strftime(“%d”)

61. ___________ uses Parenthesis for comma-separated values in


Python? Fill in the blanks with a Python collection?
 List
 Tuples
 None of the above

62. How to create an empty Tuple in Python?


 mytuple = ()
 mytuple = (0)
 mytuple = 0
 mytuple =
63. Can we have duplicate keys in the Python Dictionary?
 TRUE
 FALSE

64. Lists in Python are Immutable?


 TRUE
 FALSE

65. What is the correct way to create a list with type float?
 mylist = [5.7, 8.2, 3.8, 2.9]
 mylist = (5.7, 8.2, 3.8, 2.9)
 mylist = {5.7, 8.2, 3.8, 2.9}
 None of the above

66. How to display only the day number of years in Python?


 date.strftime(“%j”)
 date.strftime(“%H”)
 date.strftime(“%I”)
 date.strftime(“%p”)

67. Delete multiple elements in a range from a Python List


 del mylist[2:4]
 del mylist(2:4)
 del mylist[2 to 4]
 del mylist(2 to 4)

68. How to fetch the last element from a Python List with negative
indexing?
 print(“Last element = “,mylist[0])
 print(“Last element = “,mylist[])
 print(“Last element = “,mylist[-1])
 None of the above
69. What is the correct way to get the length of a List in Python?
 mylist.count()
 count(mylist)
 len(mylist)
 length(mylist)

70. To get today’s date, which Python module is to be imported?


 calendar module
 datetime module
 dateutil module
 None of the above

1. What is the output of  print('%x, %X' % (15, 15))

 15 15
 FF
 ff
 fF
Explanation:

In output formatting, We use type %x and %X to convert decimal number to


hexadecimal number on the screen. %x produces lowercase output,
and %X produces uppercase output.

2. Use the following file to predict the output of the code

test.txt Content:

aaa

bbb
ccc

ddd

eee

fff

ggg

Code:

f = open("test.txt", "r")

print(f.readline(3))

f.close()

Hint: Read file in Python.

 bbb
 Syntax Error
 aaa
 aa
Explanation:

fileObject.readline(size). Here size is the number of bytes to be read from the


file.

3. In Python 3, which functions are used to accept input from the user
 input()
 raw_input()
 rawinput()
 string()

Explanation:
In Python3, we use input() function to accept input from the user.
Theraw_input() function is removed from Python 3 and onwards.

4. Which of the following is incorrect file handling mode in Python.

Hint: File handling in Python.

 r
 x
 t+
 b
5. What will be displayed as an output on the screen

x = float('NaN')

print('%f, %e, %F, %E' % (x, x, x, x))

 nan, nan, NAN, NAN


 nan, NaN, nan, NaN
 NaN, NaN, NaN, NaN,
Explanation:

%f, %e produces lowercase output, and %F, %E produces uppercase output.

6. Which of the following is incorrect file handling mode in Python

 wb+
 ab
 xr
 ab+
7. What is the output of print('[%c]' % 65)

 65
 A
 [A]
 Syntax Error
Explanation:

The c conversion type supports character conversion from ASCII code to the


character. It also works for the Unicode

8. What is true for file mode x

Hint: Create File in Python

 create a file if the specified file does not exist


 Create a file, returns an error if the file exists
 Create a file if it doesn’t exists else Truncate the existed file
9. In Python3, Whatever you enter as input, the input() function converts
it into a string

 False
 True
Explanation:

If you want to accept number input from the user, you need to convert an input
value to the integer type.

10. What is the output of the following print() function


print(sep='--', 'Ben', 25, 'California')

 Syntax Error
 Ben–25–California
 Ben 25 California
 Ben–25 California
Explanation:
sep iskeyword argument Any keyword arguments passed to print() function must
come at the end, after the objects to display. Otherwise, you will get a Syntax
Error positional argument that follows the keyword argument.

The correct way is print('Ben', 25, 'California', sep='--')

12. What is the output of the following print() function


print('%d %d %.2f' % (11, '22', 11.22))

 11 22 11.22
 TypeError
 11 ’22’ 11.22
Explanation:

when we mention %d in print() function to read string value we will get TypeError:


%d format: a number is required, not str

It Should be like this print('%d %s %.2f' % (11, '22', 11.22))

You might also like