0% found this document useful (0 votes)
0 views

Python Unit-3 MCQs

The document contains a series of objective questions and answers related to control flow functions in Python programming. It covers topics such as loops, conditional statements, and string manipulation, providing explanations for each answer. The questions test knowledge on Python syntax and functionality, including the use of keywords and control structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python Unit-3 MCQs

The document contains a series of objective questions and answers related to control flow functions in Python programming. It covers topics such as loops, conditional statements, and string manipulation, providing explanations for each answer. The questions test knowledge on Python syntax and functionality, including the use of keywords and control structures.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

GE8151-PROBLEM SOLVING IN PYTHON PROGRAMMING

UNIT – III (Objective Questions)

CONTROL FLOW FUNCTIONS

1. Which of the following is not used as loop in Python?


a)for loop
b) while loop
c) do-while loop
d)None of the above
Answer
Ans : c
Explanation: do-while loop is not used as loop in Python.

2. Which of the following is false regarding loops in Python?

a) Loops are used to perform certain tasks repeatedly.


b)While loop is used when multiple statements are to executed repeatedly until the given
condition becomes False
c)While loop is used when multiple statements are to executed repeatedly until the given
condition becomes True.
d)for loop can be used to iterate through the elements of lists.

Answer
Ans : b

Explanation:
While loop is used when multiple statements are to executed repeatedly until the given
condition becomes False statement is False regarding loops in Python.
3. Which of the following is True regarding loops in Python?

a)Loops should be ended with keyword "end".


b)No loop can be used to iterate through the elements of strings.
c)Keyword "break" can be used to bring control out of the current loop.
d)Keyword "continue" is used to continue with the remaining statements inside the loop.

Answer
Ans : c
Explanation: Keyword break can be used to bring control out of the current loop
statement is True regarding loops in Python.

4. How many times will the loop run?


i=2
while(i>0):
i=i-1

a) 2
b) 3
c) 1
d) 0
Answer
Ans : a

Explanation: The loop will run 2 times.


5. Which one of the following is a valid Python if statement :

a) if a>=2 :
b)if (a >= 2)
c) if (a => 22)
d) if a >= 22
Answer
Ans : a
Explanation: If statement always ended with colon (:). So, option A is correct.
6. What keyword would you use to add an alternative condition to an if statement?
a)else if
b)elseif
c)elif
d)None of the above

Answer
Ans : c
Explanation: elif is used to add an alternative condition to an if statement. So, option C is
correct.
7. Can we write if/else into one line in python?

a)Yes
b)No
c) if/else not used in python
d)None of the above

Answer
Ans : a
Explanation: Yes, we can write if/else in one line. For eg i = 5 if a > 7 else 0. So, option A is
correct.
8. In a Python program, a control structure:

a) Defines program-specific data structures


b) Directs the order of execution of the statements in the program
c) Dictates what happens before the program starts and after it terminates
d) None of the above
Answer
Ans : b

Explanation: Control structures determine which statements in the program will be executed
and in what order, allowing for statements to be skipped over or executed repeatedly. So, option
B is correct.
9. What will be output of this expression:

'p' + 'q' if '12'.isdigit() else 'r' + 's'

a) pq
b) rs
c) pqrs
d) pq12

Answer
Ans : a
Explanation: If condition is true so pq will be the output. So, option A is correct.
10. Which statement will check if a is equal to b?

a) if a = b:
b) if a == b:
c) if a === c:
d) if a == b

Answer
Ans : b
Explanation: if a == b: statement will check if a is equal to b. So, option B is correct.
11. Does python have switch case statement?

a) True
b) False
c) Python has switch statement but we can not use it.
d) None of the above
Answer
Ans : b
Explanation: Python does not have switch case statement. So, option B is correct.
12. Which of the following Python code will give different output from the others?

a) for i in range(0,5):
print(i)
b) for j in [0,1,2,3,4]:
print(j)
c) for k in [0,1,2,3,4,5]:
print(k)
d) for l in range(0,5,1):
print(l)

Answer
Ans : c
Explanation: Option C python code will give different output from the others.
13. What will be the output of the following Python code?

for i in range(0,2,-1):
print("Hello")

a)Hello
b) Hello Hello
c) No Output
d) Error

Answer
Ans : c
Explanation: There will be no output of the following python code.
14. Which of the following is a valid for loop in Python?

a)for(i=0; i < n; i++)


b) for i in range(0,5):
c) for i in range(0,5)
d) for i in range(5)

Answer
Ans : b
Explanation: For statement always ended with colon (:). So, option B is correct.
15. Which of the following sequences would be generated by the given line of code?
range (5, 0, -2)
a) 5 4 3 2 1 0 -1
b) 5 4 3 2 1 0
c) 5 3 1
d) None of the above

Answer
Ans : c

Explanation: The initial value is 5 which is decreased by 2 till 0 so we get 5, then 2 is decreased
so we get 3 then the same thing repeated we get 1 and now when 2 is decreased we get -1 which
is less than 0 so we stop and hence we get 5 3 1. So, option C is correct.

16. A while loop in Python is used for what type of iteration?

a) indefinite
b) discriminant
c) definite
d) indeterminate

Answer
Ans : a
Explanation: A while loop implements indefinite iteration, where the number of times the loop
will be executed is not specified explicitly in advance. So, option A is correct.
17. When does the else statement written after loop executes?

a) When break statement is executed in the loop


b) When loop condition becomes false
c) Else statement is always executed
d) None of the above

Answer
Ans : b

Explanation: Else statement after loop will be executed only when the loop condition becomes
false. So, option B is correct.
18. What will be the output of the following code?

x = "abcd"

for i in range(len(x)):

print(i)

a) abcd
b) 0 1 2 3
c) 1 2 3 4
d) a b c d

Answer
Ans : b
Explanation: len(x) will give 4 and the loop will run for 4 times starting from 0. Hence output
will be 0 1 2 3. So, option B is correct.
19. What will be the output of the following code?

x = 12

for i in x:

print(i)

a) 12
b) 1 2
c) Error
d) None of the above

Answer
Ans : c

Explanation: Objects of type int are not iterable. So, option C is correct.

20. Which of the following is the use of function in python?


a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity for your application
c) you can’t also create your own functions
d) All of the mentioned

Answer: a
Explanation: Functions are reusable pieces of programs. They allow you to give a name to a
block of statements, allowing you to run that block using the specified name anywhere in your
program and any number of times.

21. Which keyword is used for function?


a) Fun
b) Define
c) Def
d) Function

Answer: c
Explanation: None.

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


a) Hello World!

Hello World!

b) 'Hello World!'

'Hello World!'

c) Hello

Hello

d) None of the mentioned

Answer: a

Explanation: Functions are defined using the def keyword. After this keyword comes an
identifier name for the function, followed by a pair of parentheses which may enclose some
names of variables, and by the final colon that ends the line. Next follows the block of statements
that are part of this function.

23. In a Python program, a control structure:

a) Dictates what happens before the program starts and after it terminates

b) Directs the order of execution of the statements in the program

c) Manages the input and output of control characters


d) Defines program-specific data structures

Answer-b

Explaination
Control structures determine which statements in the program will be executed and in what
order, allowing for statements to be skipped over or executed repeatedly.if, if/else,
and if/elif/else statements are all examples of control structures that allow for statements to be
skipped over or executed conditionally:

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

x = ['ab', 'cd']
for i in x:
i.upper()
print(x)
a) [‘ab’, ‘cd’]
b) [‘AB’, ‘CD’]
c) [None, None]
d) none of the mentioned

Answer: a
Explanation: The function upper() does not modify a string in place, it returns a new string
which isn’t being stored anywhere.

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

x = ['ab', 'cd']
for i in x:
x.append(i.upper())
print(x)
a) [‘AB’, ‘CD’]
b) [‘ab’, ‘cd’, ‘AB’, ‘CD’]
c) [‘ab’, ‘cd’]
d) none of the mentioned

Answer: d
Explanation: The loop does not terminate as new elements are being added to the list in each
iteration.

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

i=1
while True:
if i%3 == 0:
break
print(i)

i+=1
a) 1 2
b) 1 2 3
c) error
d) none of the mentioned

Answer: c
Explanation: SyntaxError, there shouldn’t be a space between + and = in +=.

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


i=1
while True:
if i%0O7 == 0:
break
print(i)
i += 1
a) 1 2 3 4 5 6
b) 1 2 3 4 5 6 7
c) error
d) none of the mentioned

Answer: a
Explanation: Control exits the loop when i becomes 7.

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


True = False
while True:
print(True)
break
a) True
b) False
c) None
d) none of the mentioned

Answer: d
Explanation: SyntaxError, True is a keyword and it’s value cannot be changed.

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

>>>”a”+”bc”
a) a
b) bc
c) bca
d) abc

Answer: d
Explanation: + operator is concatenation operator.

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

>>>”abcd”[2:]
a) a
b) ab
c) cd
d) dc

Answer: c
Explanation: Slice operation is performed on string.

31. The output of executing string.ascii_letters can also be achieved by:


a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_uppercase
c) string.letters
d) string.lowercase_string.uppercase

Answer: b
Explanation: Execute in shell and check.

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

>>> str1 = ‘hello’


>>> str2 = ‘,’
>>> str3 = ‘world’
>>> str1[-1:]
a) olleh
b) hello
c) h
d) o

Answer: d
Explanation: -1 corresponds to the last index.

33.What arithmetic operators cannot be used with strings?

a) +
b) *
c) –
d) All of the mentioned

Answer: c
Explanation: + is used to concatenate and * is used to multiply strings.

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


>>>print (r”\nhello”)
a) a new line and hello
b) \nhello
c) the letter r and then hello
d) error
Answer: b
Explanation: When prefixed with the letter ‘r’ or ‘R’ a string literal becomes a raw string
and the
escape sequences such as \n are not converted.

35.What will be the output of the following Python statement?

>>>print(‘new’ ‘line’)
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line

Answer: c
Explanation: String literal separated by whitespace are allowed. They are concatenated.

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


>>>str1=”helloworld”
>>>str1[::-1]

a) dlrowolleh
b) hello
c) world
d) helloworld

Answer: a
Explanation: Execute in shell to verify.

37. What arithmetic operators cannot be used with strings?


a) +
b) *
c) –
d) All of the mentioned

Answer: c
Explanation: + is used to concatenate and * is used to multiply strings.

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

>>>print (r"\nhello")

a) a new line and hello


b) \nhello
c) the letter r and then hello
d) error
Answer: b
Explanation: When prefixed with the letter ‘r’ or ‘R’ a string literal becomes a raw string and
the escape sequences such as \n are not converted.

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

>>>print('new' 'line')
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line

Answer: c
Explanation: String literal separated by whitespace are allowed. They are concatenated.

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

>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld

Answer: a
Explanation: Execute in shell to verify.

41. Which of the following is False?


A. String is immutable.
B. capitalize() function in string is used to return a string by converting the whole given string
into uppercase.
C. lower() function in string is used to return a string by converting the whole given string into
lowercase.
D. None of these.

Ans : B

Explanation: capitalize() function in string gives the output by converting only the first
character of the string into uppercase and rest characters into lowercase.However, upper()
function is used to return the whole string into uppercase.

42. What will be the output of below Python code?


str1="Information"
print(str1[2:8])

A. format
B. formatio
C. orma
D. ormat

Ans : A

Explanation: Concept of slicing is used in this question. In string slicing,the output is the
substring starting from the first given index position i.e 2 to one less than the second given index
position i.e.(8-1=7) of the given string str1. Hence, the output will be "format".
43.What will be the output of below Python code?
str1="Aplication"

str2=str1.replace('a','A')

print(str2)

A. application
B. Application
C. ApplicAtion
D. applicAtion

Ans : C

Explanation: replace() function in string is used here to replace all the existing "a" by "A" in the
given string.
44.What will be the output of below Python code?

str1="poWer"

str1.upper()

print(str1)

A. POWER
B. Power
C. power
D. poWer

Ans : D

Explanation: str1.upper() returns the uppercase of whole string str1. However,it doesnot change
the string str1. So, output will be the original str1.
45.What will the below Python code will return?
If str1="save paper,save plants"

str1.find("save")

A. It returns the first index position of the first occurance of "save" in the given string str1.
B. It returns the last index position of the last occurance of "save" in the given string str1.
C. It returns the last index position of the first occurance of "save" in the given string str1.
D. It returns the first index position of the first occurance of "save" in the given string str1.

Ans : A

Explanation: It returns the first index position of the first occurance of "save" in the given string
str1.
46.What will following Python code return?

str1="Stack of books"

print(len(str1))

A. 13
B. 14
C. 15
D. 16

Ans : B

Explanation: len() returns the length of the given string str1, including spaces and considering "
" as a single character.

47. ________ is used to end the current loop and instruct python to execute the statement after
the loop.
a. break
b. continue
c.pass
d. none

Ans:
a) break

48. _____ change the execution from normal sequence.

a) Control statements
b) Execution
c) Iteration
d) None
Ans
a) Control statements

49. ___________causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating
a) break
b) continue
c) pass
d) none

Ans:
b) Continue

50. _______ statement in python is used when a statement required syntactically but we do not
want any command or code to execute.

a) break
b) continue
c) pass
d) none

Ans:
c) Pass

51. The __________ function returns the absolute value of the specified number.
a) abs()
b) float()
c) int()
d)None
Ans :
a) abs

STRINGS CONCEPTS

Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
>>>a=”HELLO” Positive indexing helps in accessing
indexing >>>print(a[0]) the string from the beginning
>>>H Negative subscript helps in accessing
>>>print(a[-1]) the string from the end.
>>>O

Print[0:4] – HELL The Slice[start : stop] operator extracts


Slicing: Print[ :3] – HEL sub string from the strings.
Print[0: ]- HELLO A segment of a string is called a slice.

a=”save” The + operator joins the text on both


Concatenation b=”earth” sides of the operator.
>>>print(a+b)
Save earth

a=”panimalar ” The * operator repeats the string on the


Repetitions: >>>print(3*a) left hand side times the value on right
hand side.

panimalarpanimalar
panimalar

Membership: >>> s="good morning" Using membership operators to check a


>>>"m" in s particular character is in string or not.
True Returns true if present

>>> "a" not in s


True

String built in functions and methods:


A method is a function that “belongs to” an object.

Syntax to access the

methodStringname.method()
a=”happy birthday”
here, a is the string name.
syntax example description
1 a.capitalize() >>> a.capitalize() capitalize only the first letter
' Happy birthday’ in a string
2 a.upper() >>> a.upper() change string to upper case
'HAPPY BIRTHDAY’
3 a.lower() >>> a.lower() change string to lower case
' happy birthday’
4 a.title() >>> a.title() change string to title case i.e.
' Happy Birthday ' first characters of all the
words are capitalized.
5 a.swapcase() >>> a.swapcase() change lowercase characters
'HAPPY BIRTHDAY' to uppercase and vice versa
6 a.split() >>> a.split() returns a list of words
['happy', 'birthday'] separated by space
7 a.center(width,”fillchar >>>a.center(19,”*”) pads the string with the
”) '***happy birthday***' specified “fillchar” till the
length is equal to “width”
8 a.count(substring) >>> a.count('happy') returns the number of
1 occurences of substring
9 a.replace(old,new) >>>a.replace('happy', replace all old substrings
'wishyou happy') with new substrings
'wishyou happy
birthday'
10 a.join(b) >>> b="happy" returns a string concatenated
>>> a="-" with the elements of an
>>> a.join(b) iterable. (Here “a” is the
'h-a-p-p-y' iterable)
11 a.isupper() >>> a.isupper() checks whether all the case-
False based characters (letters) of
the string are uppercase.
12 a.islower() >>> a.islower() checks whether all the case-
True based characters (letters) of
the string are lowercase.
13 a.isalpha() >>> a.isalpha() checks whether the string
False consists of alphabetic
characters only.
Escape sequences in string
Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"")
(") "
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)

Array Methods

Syntax example Description

1 array(data type, array(‘i’,[2,3,4,5]) This function is used to create


value list) an array with data type and
value list specified in its
arguments.

2 append() >>>a.append(6) This method is used to add the


[2,3,4,5,6] at the end of the array.

3 insert(index,element >>>a.insert(2,10) This method is used to add the


) [2,3,10,5,6] value at the position specified in
its argument.

4 pop(index) >>>a.pop(1) This function removes the


[2,10,5,6] element at the position
mentioned in its argument, and
returns it.
5 index(element) >>>a.index(2) This function returns the index
0 of value

6 reverse() >>>a.reverse() This function reverses the


[6,5,10,2] array.

7 count() a.count() This is used to count number of

You might also like