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

21ec643 Python MDR Quiz Questions

Hhgffyvbbcbdn

Uploaded by

DARSHAN DARSH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

21ec643 Python MDR Quiz Questions

Hhgffyvbbcbdn

Uploaded by

DARSHAN DARSH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

KALPATARU VIDYA SAMSTHE®

KALPATARU INSTITUTE OF TECHNOLOGY-TIPTUR


Department of Electronics & Communication Engg.
EVEN SEM 2024
VI Semester
Subject: PYTHON PROGRAMMING Subject code: 21EC643
Name of the Faculty: RUDRESH M D
QUIZ-1 QUESTIONS WITH ANSWERS (MODULE-123)
MODULE-1
1. What is the best way to think about a "Syntax Error" while programming?

The computer is overheating and just wants you to stop to let it cool down

The computer has used GPS to find your location and hates everyone from your town

The computer needs to have its software upgraded

The computer did not understand the statement that you entered
2. What will the following program print out:

>>> x = 15
>>> x = x + 5
>>> print(x)

"print x"

x+5

15

20
3. Python scripts (files) have names that end with:

.doc

.png

.exe

.py
4. Which of these words is a reserved word in Python ?

pizza

while

payroll
names
5. Which of these words are reserved words in Python ?

break

concat

machine

if

todo

6. What is the proper way to say “good-bye” to Python?

// stop

quit()
7. Which of the parts of a computer actually executes the program instructions?

Secondary Memory

Main Memory

Input/Output Devices

Central Processing Unit


8. What is "code" in the context of this course?

A password we use to unlock Python features

A sequence of instructions in a programming language

A way to encrypt data during World War II

A set of rules that govern the style of programs


9. A USB memory stick is an example of which of the following components of computer architecture?

Main Memory

Central Processing Unit

Secondary Memory

Output Device
Variables, expressions and statements

1. In the following code,

print(98.6)

What is "98.6"?

A conditional statement

A variable

An iteration / loop statement

A constant

2. Which of the following is a comment in Python?

// This is a test

# This is a test

/* This is a test */

* This is a test
3. What does the following code print out?

print("123" + "abc")

123+abc

123abc

This is a syntax error because you cannot add strings

hello world
4. In the following code,

x = 42

What is "x"?

A Central Processing Unit

A constant

A function

A variable
5. Which of the following is a bad Python variable name?

23spam

SPAM23

Spam

_spam
6. Which of the following variables is the "most mnemonic"?

variable_173

hours

x1q3z9ocd

7. Which of the following is not a Python reserved word?

for

if

speed

else
8. Which of the following is not a Python reserved word?

continue

iterate

else

break
9. Assume the variable x has been initialized to an integer value (e.g., x = 3). What does the following
statement do?

x = x + 2

This would fail as it is a syntax error

Create a function called "x" and put the value 2 in the function

Retrieve the current value for x, add two to it and put the sum back into x

Produce the value "false" because "x" can never equal "x+2"
10. Which of the following elements of a mathematical expression in Python is evaluated first?

Parentheses ( )

Subtraction -
Multiplication *

Addition +
11. What is the value of the following expression

42 % 10

Hint - the "%" is the remainder operator

10

420

1042
12. What will be the value of x after the following statement executes:

x = 1 + 2 * 3 - 8 / 4

5.0

15

3.0

13. What will be the value of x when the following statement is executed:

x = int(98.6)

98

99

100
14. What does the Python input() function do?

Pause the program and read data from the user

Read the memory of the running program

Connect to the network and retrieve a web page.

Take a screen shot from an area of the screen


CONDITIONAL EXECUTION
1. What do we do to a Python statement that is immediately after an if statement to indicate that the statement
is to be executed only when the if statement is true?

Indent the line below the if statement

Underline all of the conditional code

Start the statement with a "#" character

Begin the statement with a curly brace {


2. Which of these operators is not a comparison / logical operator?

!=

==

>=

>

3. What is true about the following code segment:

if x == 5 :
print('Is 5')
print('Is Still 5')
print('Third 5')

Depending on the value of x, either all three of the print statements will execute or none of the
statements will execute

Only two of the three print statements will print out if the value of x is less than zero.

The string 'Is 5' will always print out regardless of the value for x.

The string 'Is 5' will never print out regardless of the value for x.
4. When you have multiple lines in an if block, how do you indicate the end of the if block?

You use a curly brace { after the last line of the if block

You de-indent the next line past the if block to the same level of indent as the original if statement

You capitalize the first letter of the line following the end of the if block

You omit the semicolon ; on the last line of the if block


5. You look at the following text:

if x == 6 :
print('Is 6')

print('Is Still 6')


print('Third 6')

It looks perfect but Python is giving you an 'Indentation Error' on the second print statement. What is the
most likely reason?

Python thinks 'Still' is a mis-spelled word in the string

Python has reached its limit on the largest Python program that can be run

You have mixed tabs and spaces in the file

In order to make humans feel inadequate, Python randomly emits 'Indentation Errors' on perfectly
good code - after about an hour the error will just go away without any changes to your program
6. What is the Python reserved word that we use in two-way if tests to indicate the block of code that is to be
executed if the logical test is false?

otherwise

A closing curly brace followed by an open curly brace like this }{

else

iterate

7. What will the following code print out?

x = 0
if x < 2 :
print('Small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')

Small Medium LARGE All done

Small

Medium All done

Small All done


8. For the following code,

if x < 2 :
print('Below 2')
elif x >= 2 :
print('Two or more')
else :
print('Something else')

What value of 'x' will cause 'Something else' to print out?

x = 2.0
This code will never print 'Something else' regardless of the value for 'x'

x = -2

x=2
9. In the following code (numbers added) - which will be the last line to execute successfully?

(1) astr = 'Hello Bob'


(2) istr = int(astr)
(3) print('First', istr)
(4) astr = '123'
(5) istr = int(astr)
(6) print('Second', istr)

1
10. For the following code:

astr = 'Hello Bob'


istr = 0
try:
istr = int(astr)
except:
istr = -1

What will the value be for istr after this code executes?

The istr variable will not have a value

-1

It will be the 'Not a number' value (i.e. NaN)

FUNCTIONS
1. Which Python keyword indicates the start of a function definition?

break
def

sweet

help
2. In Python, how do you indicate the end of the block of code that makes up the function?

You put a

You add the matching curly brace that was used to start the function

You de-indent a line of code to the same indent level as the def keyword

You put the "END" keyword in column 7 of the line which is to be the last line of the function
3. In Python what is the input() feature best described as?

A user-defined function

A conditional statement

A built-in function

The central processing unit


4. What does the following code print out?

def thing():
print('Hello')
print('There')

defthing

Hello

There

thingHelloThere
5. In the following Python code, which of the following is an "argument" to a function?

x = 'banana'
y = max(x)
print(y)

'banana'

print

x and y

max
6. What will the following Python code print out?

def func(x) :
print(x)
func(10)
func(20)

funcfunc

x20

x10x20

1020
7. Which line of the following Python program will never execute?

def stuff():
print('Hello')
return
print('World')
stuff()

stuff()

def stuff():

return

print ('World')

print('Hello')

8. What will the following Python program print out?


def greet(lang):
if lang == 'es':
return 'Hola'
elif lang == 'fr':
return 'Bonjour'
else:
return 'Hello'

print(greet('fr'),'Michael')

defHolaBonjourHelloMichael

Hola Michael

HolaBonjourHelloMichael

Bonjour Michael
9. What is the most important benefit of writing your own functions?

Following the rule that no function can have more than 10 statements in it

Avoiding writing the same non-trivial code more than once in your program
To avoid having more than 10 lines of sequential code without an indent or de-indent

Following the rule that whenever a program is more than 10 lines you must use a function

LOOPS AND ITERATIONS

1. What is wrong with this Python loop:

n = 5
while n > 0 :
print(n)
print('All done')

This loop will run forever

The print('All done') statement should be indented four spaces

There should be no colon on the while statement

while is not a Python reserved word


2. What does the break statement do?

Exits the currently executing loop

Resets the iteration variable to its initial value

Jumps to the "top" of the loop and starts the next iteration

Exits the program

3. What does the continue statement do?

Resets the iteration variable to its initial value

Exits the currently executing loop

Exits the program

Jumps to the "top" of the loop and starts the next iteration

4. What does the following Python program print out?

tot = 0
for i in [5, 4, 3, 2, 1] :
tot = tot + 1
print(tot)

5
15

10

5. What is the iteration variable in the following Python code:

friends = ['Joseph', 'Glenn', 'Sally']


for friend in friends :
print('Happy New Year:', friend)
print('Done!')

friend

Joseph

Glenn

Sally
6. What is a good description of the following bit of Python code?

zork = 0
for thing in [9, 41, 12, 3, 74, 15] :
zork = zork + thing
print('After', zork)

Compute the average of the elements in a list

Find the smallest item in a list

Count all of the elements in a list

Sum all the elements of a list

7. What will the following code print out?

smallest_so_far = -1
for the_num in [9, 41, 12, 3, 74, 15] :
if the_num < smallest_so_far :
smallest_so_far = the_num
print(smallest_so_far)

Hint: This is a trick question and most would say this code has a bug - so read carefully

42

-1
3

74
8. What is a good statement to describe the is operator as used in the following if statement:

if smallest is None :
smallest = value

Is true if the smallest variable has a value of -1

Looks up 'None' in the smallest variable if it is a string

matches both type and value

The if statement is a syntax error


9. Which reserved word indicates the start of an "indefinite" loop in Python?

def

for

break

indef

while
10. How many times will the body of the following loop be executed?

n = 0
while n > 0 :
print('Lather')
print('Rinse')
print('Dry off!')

This is an infinite loop

MODULE-2
STRINGS
1. What does the following Python Program print out?

str1 = "Hello"
str2 = 'there'
bob = str1 + str2
print(bob)

Hello

Hellothere

Hello there
2. What does the following Python program print out?

x = '40'
y = int(x) + 2
print(y)

x2

402

int402

42
3. How would you use the index operator [] to print out the letter q from the following string?

x = 'From [email protected]'

print(x[7])

print(x[8])

print(x[q])

print(x[9])

print x[-1]
4. How would you use string slicing [:] to print out 'uct' from the following string?

x = 'From [email protected]'

print(x[15:3])

print(x[14+17])

print(x[14:17])

print(x[14/17])

print(x[15:18])

print(x[14:3])
5. What is the iteration variable in the following Python code?

for letter in 'banana' :


print(letter)

in

letter

print

for

'banana'
6. What does the following Python code print out?

print(len('banana')*7)

banana7

42

bananabananabananabananabananabananabanana
7. How would you print out the following variable in all upper case in Python?

greet = 'Hello Bob'

print(uc($greet));

console.log(greet.toUpperCase());

puts(greet.ucase);

print(greet.upper())
8. Which of the following is not a valid string method in Python?

startswith()

join()

split()

shout()

9. What will the following Python code print out?

data = 'From [email protected] Sat Jan 5 09:14:16 2008'

pos = data.find('.')
print(data[pos:pos+3])

uct
mar

Sat

.ma
10. Which of the following string methods removes whitespace from both the beginning and end of a string?

strip()

strtrunc()

wsrem()

rltrim()
LISTS
1. How are "collection" variables different from normal variables?

Collection variables merge streams of output into a single stream

Collection variables can only store a single value

Collection variables can store multiple values in a single variable

Collection variables pull multiple network documents together


2. What are the Python keywords used to construct a loop to iterate through a list?

for / in

def / return

foreach / in

try / except
3. For the following list, how would you print out 'Sally'?

friends = [ 'Joseph', 'Glenn', 'Sally' ]

print(friends[2:1])

print(friends[2])

print friends[3]

print(friends['Sally'])
4. What would the following Python code print out?

fruit = 'Banana'
fruit[0] = 'b'
print(fruit)

banana
Nothing would print - the program fails with a traceback error

Banana

[0]
5. Which of the following Python statements would print out the length of a list stored in the variable data?

print(data.Len)

print(data.length())

print(len(data))

print(data.length)

print(length(data))

print(strlen(data))
6. What type of data is produced when you call the range() function?

x = list(range(5))

A string

A list of characters

A list of integers

A boolean (true/false) value

A list of words
7. What does the following Python code print out?

a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(len(c))

[4, 5, 6]

15

[1, 2, 3]

[1, 2, 3, 4, 5, 6]

21
8. Which of the following slicing operations will produce the list [12, 3]?

t = [9, 41, 12, 3, 74, 15]

t[:]

t[1:3]

t[12:3]

t[2:4]

t[2:2]
9. What list method adds a new item to the end of an existing list?

pop()

append()

forward()

index()

add()

push()
10. What will the following Python code print out?

friends = [ 'Joseph', 'Glenn', 'Sally' ]


friends.sort()
print(friends[0])

Sally

Glenn

Joseph

friends

TUPLES
1. What is the difference between a Python tuple and Python list?

Tuples can be expanded after they are created and lists cannot

Lists are indexed by integers and tuples are indexed by strings


Lists maintain the order of the items and tuples do not maintain order

Lists are mutable and tuples are not mutable


2. Which of the following methods are available for both Python lists and Python tuples?

pop()

append()

reverse()

index()

sort()

3. What will end up in the variable y after this code is executed?

x , y = 3, 4

A dictionary with the key 3 mapped to the value 4

A two item list

A two item tuple


4. In the following Python code, what will end up in the variable y?

x = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}


y = x.items()

A list of integers

A list of strings

A tuple with three integers

A list of tuples
5. Which of the following tuples is greater than x in the following Python sequence?

x = (5, 1, 3)
if ??? > x :
...

(6, 0, 0)

(4, 100, 200)

(0, 1000, 2000)


(5, 0, 300)
6. What does the following Python code accomplish, assuming the c is a non-empty dictionary?

tmp = list()
for k, v in c.items() :
tmp.append( (v, k) )

It computes the largest of all of the values in the dictionary

It computes the average of all of the values in the dictionary

It sorts the dictionary based on its key values

It creates a list of tuples where each tuple is a value, key pair


7. If the variable data is a Python list, how do we sort it in reverse order?

data.sort(reverse=True)

data = sortrev(data)

data = data.sort(-1)

data.sort.reverse()
8. Using the following tuple, how would you print 'Wed'?

days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')

print(days[1])

print(days{2})

print(days[2])

print(days(2))

print[days(2)]

print(days.get(1,-1))

9. In the following Python loop, why are there two iteration variables (k and v)?

c = {'a':10, 'b':1, 'c':22}


for k, v in c.items() :
...

Because the items() method in dictionaries returns a list of tuples


Because there are two items in the dictionary

Because for each item we want the previous and current key

Because the keys for the dictionary are strings


10. Given that Python lists and Python tuples are quite similar - when might you prefer to use a tuple over a
list?

For a list of items that want to use strings as key values instead of integers

For a list of items that will be extended as new items are found

For a list of items you intend to sort in place

For a temporary variable that you will use and discard without modifying

DICTIONARIES
1. How are Python dictionaries different from Python lists?

Python lists maintain order and dictionaries do not maintain order

Python dictionaries are a collection and lists are not a collection

Python lists can store strings and dictionaries can only store words

Python lists store multiple values and dictionaries store a single value
2. How are Python dictionaries different from Python lists?

Python lists can store strings and dictionaries can only store words

Python lists store multiple values and dictionaries store a single value

Python dictionaries are a collection and lists are not a collection

Python lists are indexed using integers and dictionaries can use strings as indexes
3. What is a term commonly used to describe the Python dictionary feature in other programming languages?

Sequences

Lambdas

Associative arrays

Closures

4. What would the following Python code print out?

stuff = dict()
print(stuff['candy'])

-1

0
The program would fail with a traceback

candy

5. What would the following Python code print out?

stuff = dict()
print(stuff.get('candy',-1))

'candy'

The program would fail with a traceback

-1
6. (T/F) When you add items to a dictionary they remain in the order in which you added them.

True

False
7. What is a common use of Python dictionaries in a program?

Sorting a list of names into alphabetical order

Computing an average of a set of numbers

Splitting a line of input into words using a space as a delimiter

Building a histogram counting the occurrences of various strings in a file


8. Which of the following lines of Python is equivalent to the following sequence of statements assuming that
counts is a dictionary?

if key in counts:
counts[key] = counts[key] + 1
else:
counts[key] = 1

counts[key] = counts.get(key,-1) + 1

counts[key] = counts.get(key,0) + 1

counts[key] = (counts[key] * 1) + 1

counts[key] = key + 1

counts[key] = (key in counts) + 1

9. In the following Python, what does the for loop iterate through?

x = dict()
...
for y in x :
...

It loops through all of the dictionaries in the program

It loops through the values in the dictionary

It loops through the integers in the range from zero through the length of the dictionary

It loops through the keys in the dictionary


10. Which method in a dictionary object gives you a list of the values in the dictionary?

values()

all()

keys()

items()

each()
11. What is the purpose of the second parameter of the get() method for Python dictionaries?

An alternate key to use if the first key cannot be found

The value to retrieve

The key to retrieve

To provide a default value if the key is not found

MODULE-3
FILES
1. Given the architecture and terminology we introduced in Chapter 1, where are files stored?

Secondary memory
Machine Language

Main Memory

Motherboard
2. What is stored in a "file handle" that is returned from a successful open() call?

The handle is a connection to the file's data

The handle has a list of all of the files in a particular folder on the hard drive

All the data from the file is read into memory and stored in the handle

The handle contains the first 10 lines of a file


3. What do we use the second parameter of the open() call to indicate?

How large we expect the file to be

Whether we want to read data from the file or write data to the file

The list of folders to be searched to find the file we want to open

What disk drive the file is stored on


4. What Python function would you use if you wanted to prompt the user for a file name to open?

alert()

file_input()

input()

gets()
5. What is the purpose of the newline character in text files?

It enables random movement throughout the file

It allows us to open more than one files and read them in a synchronized manner

It indicates the end of one line of text and the beginning of another line of text

It adds a new network connection to retrieve files from the network

6. If we open a file as follows:


xfile = open('mbox.txt')

What statement would we use to read the file one line at a time?

while line = xfile.gets

for line in xfile:

while ((line = xfile.readLine()) != null) {

while (<xfile>) {
7. What is the purpose of the following Python code?

8. fhand = open('mbox.txt')
9. x = 0
10. for line in fhand:
11. x = x + 1
12. print(x)

Count the lines in the file 'mbox.txt'

Reverse the order of the lines in mbox.txt

Remove the leading and trailing spaces from each line in mbox.txt

Convert the lines in mbox.txt to lower case


13. If you write a Python program to read a text file and you see extra blank lines in the output that are not
present in the file input as shown below, what Python string function will likely solve the problem?

From: [email protected]

From: [email protected]

From: [email protected]

From: [email protected]

rstrip()

trim()

ljust()

startswith()
14. The following code sequence fails with a traceback when the user enters a file that does not exist. How
would you avoid the traceback and make it so you could print out your own error message when a bad file
name was entered?

fname = input('Enter the file name: ')


fhand = open(fname)

try / catch / finally

try / except

setjmp / longjmp

signal handlers
15. What does the following Python code do?

fhand = open('mbox-short.txt')
inp = fhand.read()

Reads the entire file into the variable inp as a string

Checks to see if the file exists and can be written

Prompts the user for a file name

Turns the text in the file into a graphic image like a PNG or JPG

REGULAR EXPRESSIONS
1. What character do you add to the "+" or "*" to indicate that the match is to be done in a non-greedy
manner?

++

**
2. What will the '$' regular expression match?

A dollar sign

The beginning of a line

A new line at the end of a line


The end of a line

An empty line

3. What would the following mean in a regular expression? [a-z0-9]

Match anything but a lowercase letter or digit

Match any text that is surrounded by square braces

Match an entire line as long as it is lowercase letters or digits

Match a lowercase letter or a digit

Match any number of lowercase letters followed by any number of digits


4. What is the type of the return value of the re.findall() method?

An integer

A boolean

A single character

A list of strings

A string
5. What is the "wild card" character in a regular expression (i.e., the character that matches any character)?

?
6. What is the difference between the "+" and "*" character in regular expressions?

The "+" matches at least one character and the "*" matches zero or more characters

The "+" matches the beginning of a line and the "*" matches the end of a line

The "+" indicates "start of extraction" and the "*" indicates the "end of extraction"

The "+" matches the actual plus character and the "*" matches any character

The "+" matches upper case characters and the "*" matches lowercase characters
7. What does the "[0-9]+" match in a regular expression?

Zero or more digits


Several digits followed by a plus sign

Any mathematical expression

One or more digits

Any number of digits at the beginning of a line

8. What does the following Python sequence print out?

x = 'From: Using the : character'


y = re.findall('^F.+:', x)
print(y)

['From: Using the :']

['From:']

^F.+:

From:

You might also like