Assgnments
Assgnments
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.
if x == 10:
print("x is equal to 10")
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)
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:
Fix:
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)
10.
my_string = "Hello, world!"
my_string.reverse()
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))
now = datetime.datetime.now()
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.
4.Write a Python program that accepts an integer (n) and computes the value of
n+nn+nnn.
n1 = int( "%s" % a )
print (n1+n2+n3)
5.Write a Python program that prints the calendar for a given month and year.
print(calendar.month(y, m))
Sample string:
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
print("""
This
is a ....... multi-line
""")
def is_vowel(char):
all_vowels = 'aeiou'
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.
if x > y:
z=x
else:
z=y
while(True):
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
print(lcm(15, 17))
gcd
gcd = 1
if x % y == 0:
return y
if x % k == 0 and y % k == 0:
gcd = k
break
return gcd
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
Sample Solution-1:
Python Code:
n = "246.2458"
print(float(n))
print(int(float(n)))
Copy
Sample Output:
246.2458
246
Sample Solution:-
Python Code:
from os import listdir
print(files_list);
Sample Solution-1:
Python Code:
def absolute_file_path(path_fname):
import os
return os.path.abspath('path_fname')
Copy
Sample Output:
Absolute file path: /home/students/path_fname
Sample Solution-1:
Python Code:
n = int(input("Input a number: "))
sum_num = (n * (n + 1)) / 2
Copy
Sample Output:
Input a number: 2
Sum of the first 2 positive integers: 3.0
Python Code:
num = int(input("Input a four digit numbers: "))
x = num //1000
x1 = (num - x*1000)//100
Copy
Sample Output:
Input a four digit numbers: 5245
The sum of digits in the number is 16
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:')
print('\n'.join(map(str, result)))
Python Code:
s = "The quick brown fox jumps over the lazy dog."
print("Original string:")
print(s)
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
Sample Solution:-
Python Code:
import os
path="abc.txt"
if os.path.isdir(path):
print("\nIt is a directory")
elif os.path.isfile(path):
else:
print()
Copy
Sample Output:
It is a normal file
Sample Solution-1:
Python Code:
import os
file_size = os.path.getsize("abc.txt")
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')
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)
1 2
1 2 3
1 2 3 4
1 2 3 4 5
# 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.
# call function
demo("Ben", 25)
Solution 1:
Run
Solution 2:
def calculation(a, b):
return a + b, a - b
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)
30Write a program to accept a number from a user and calculate the sum of all
numbers from 1 to a given number
Run
Solution 2: Using the built-in function sum()
x = sum(range(1, n + 1))
print('Sum is:', x)
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
sample_str = "P@yn2at&#i5ve"
print("total counts of chars, Digits, and symbols \n")
find_digits_chars_symbols(sample_str)
str1 = "Apple"
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)
Given a Python list, write a program to remove all occurrences of item 20.
Given:
Show Solution
# 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]
Run
while 20 in list1:
list1.remove(20)
print(list1)
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" }
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)
# empty dictionary
res_dict = dict()
for i in range(len(keys)):
res_dict.update({keys[i]: values[i]})
print(res_dict)
A. Special purpose
B. General purpose
C. Medium level programming language
D. All of the mentioned above
Explanation:
Explanation:
Python programming was created by Guido van Rossum. It is also called general-
purpose programming language.
A. Web Development
B. Game Development
C. Artificial Intelligence and Machine Learning
D. All of the mentioned above
Explanation:
A. int
B. float
C. complex
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.
A. Sequence Types
B. Binary Types
C. Boolean Types
D. None of the mentioned above
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.
ADVERTISEMENT
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.
A. Mapping Type
B. Boolean Type
C. Binary Types
D. None of the mentioned above
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.
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.
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.
A. TRUE
B. FALSE
Answer: A) TRUE
Explanation:
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
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.
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.
A. Exponentiation
B. Modulus
C. Floor division
D. None of the mentioned above
Answer: A) Exponentiation
Explanation:
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.
A. append()
B. extend()
C. insert()
D. All of the mentioned above
Explanation:
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 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.
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.
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>
}
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:
ADVERTISEMENT
A. Decision-making
B. Array
C. List
D. None of the mentioned above
Answer: A) Decision-making
Explanation:
A. True
B. False
Answer: A) True
Explanation:
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:
A. if a<=100:
B. if (a >= 10)
C. if (a => 200)
D. None of the mentioned above
Answer: A) if a<=100:
Explanation:
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.
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.
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
Explanation:
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
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.
ADVERTISEMENT
x=13
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".
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
Explanation:
A. Block
B. Loop
C. Indentation
D. None of the mentioned above
Answer: C) Indentation
Explanation:
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:
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."
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
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.
Answer: A) True
Explanation:
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
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.
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,
40. If a condition is true the not operator is used to reverse the logical state?
A. True
B. False
Answer: A) True
Explanation:
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.
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 –
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:
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.
45. Amongst which of the following is / are true about the while loop?
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.
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:
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.
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.
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.
50. Amongst which of the following is / are true with reference to loops in
Python?
Explanation:
Following point's shows the importance of loops in Python.
A. Write code
B. Specific task
C. Create executable file
D. None of the mentioned above
Explanation:
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:
def function_name(parameters):
...
Statements
...
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 + ".")
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
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.
def show(id,name):
print("Your id is :",id,"and your name is :",name)
show(12,"deepak")
Explanation:
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
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:
A. Yes
B. No
Answer: A) Yes
Explanation:
def St_list(student):
for x in student:
print(x)
students = ["Anil", "Rex", "Jerry"]
St_list(students)
"""
Output:
Anil
Rex
Jerry
"""
A. True
B. False
Answer: A) True
Explanation:
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.
60. Scope and lifetime of a variable declared in a function exist till the
function exists?
A. True
B. False
Answer: A) True
Explanation:
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.
62. Amongst which of the following is / are the key functions used for file
handling in Python?
Explanation:
A. filename
B. mode
C. Both A and B
D. None of the mentioned above
Explanation:
In most cases, only the filename and mode parameters are required, with the rest
of the parameters implicitly set to their default values.
f = open ("file.txt")
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.
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.
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.
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.
Explanation:
The seek() method is used to position a file object at a specific location within a
file's hierarchy.
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.
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.
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.
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
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.
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
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
A. Alphabets
B. Numbers
C. Special symbols
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.
A. True
B. False
Answer: A) True
Explanation:
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
str[11:16]
str(11:16)
str[11][16]
str[11-16]
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
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
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))
19. How to access value for key “Product” in the following Python
Dictionary:
1
2 mystock = {
3 "Product": "Earphone",
4 "Price": 800,
5 "Quantity": 50,
6 "InStock" : "Yes"
7}
8
mystock[“Product”]
mystock(“Product”)
mystock[Product]
mystock(Product)
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
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])
32. How to swap cases in Python i.e. lowercase to uppercase and vice
versa?
casefold() method
swapcase() method
case() method
title() method
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
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);
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))
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());
59. Can we update Tuples or any of its elements in Python after the
assignment?
Yes
No
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
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)
15 15
FF
ff
fF
Explanation:
test.txt Content:
aaa
bbb
ccc
ddd
eee
fff
ggg
Code:
f = open("test.txt", "r")
print(f.readline(3))
f.close()
bbb
Syntax Error
aaa
aa
Explanation:
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.
r
x
t+
b
5. What will be displayed as an output on the screen
x = float('NaN')
wb+
ab
xr
ab+
7. What is the output of print('[%c]' % 65)
65
A
[A]
Syntax Error
Explanation:
False
True
Explanation:
If you want to accept number input from the user, you need to convert an input
value to the integer type.
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.
11 22 11.22
TypeError
11 ’22’ 11.22
Explanation: