Exam4Training

Python Institute PCEP-30-01 Certified Entry-Level Python Programmer Online Training

Question #1

What are the four fundamental elements that make a language?

  • A . An alphabet, phonetics, phonology, and semantics
  • B . An alphabet, a lexis, phonetics, and semantics
  • C . An alphabet, morphology, phonetics, and semantics
  • D . An alphabet, a lexis, a syntax, and semantics

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topics: language alphabet lexis syntax semantics

We can say that each language (machine or natural, it doesn’t matter)

consists of the following elements:

An alphabet:

a set of symbols used to build words of a certain language (e.g., the Latin alphabet for English,

the Cyrillic alphabet for Russian, Kanji for Japanese, and so on)

A lexis:

(aka a dictionary) a set of words the language offers its users

(e.g., the word "computer" comes from the English language dictionary, while "cmoptrue" doesn’t;

the word "chat" is present both in English and French dictionaries,

but their meanings are different)

A syntax:

a set of rules (formal or informal, written or felt intuitively)

used to determine if a certain string of words forms a valid sentence

(e.g., "I am a python" is a syntactically correct phrase, while "I a python am" isn’t)

Semantics:

a set of rules determining if a certain phrase makes sense

(e.g., "I ate a doughnut" makes sense, but "A doughnut ate me" doesn’t)

Question #2

What will be the output of the following code snippet?

x = 1

y = 2

z = x

x = y

y = z

print (x, y)

  • A . 1 2
  • B . 2 1
  • C . 1 1
  • D . 2 2

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topic: copying an immutable object by assigning

Try it yourself:

x = 1

y = 2

z = x

print(z) # 1

x = y

print(x) # 2

y = z

print(y) # 1

print(x, y) # 2 1

Integer is an immutable data type.

The values get copied from one variable to another.

In the end x and y changed their values.

Question #3

Python is an example of:

  • A . a machine language
  • B . a high-level programming language
  • C . a natural language

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topic: high-level programming language

https://en.wikipedia.org/wiki/Python_(programming_language)

Question #4

What will be the output of the following code snippet?

print(3 / 5)

  • A . 6/10
  • B . 0.6
  • C . 0
  • D . None of the above.

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topic: division operator

Try it yourself:

print(3 / 5) # 0.6

print(4 / 2) # 2.0

The division operator does its normal job.

And remember the division operator ALWAYS returns a float.

Question #5

Strings in Python are delimited with:

  • A . backslashes (i.e., )
  • B . double quotes (i.e., ") or single quotes (i.e., ‘)
  • C . asterisks (i.e., *)
  • D . dollar symbol (i.e., $)

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topics: strings quotes

Try it yourself:

print("Hello") # Hello

print(‘World’) # World

Unlike in other programming languages, in Python double quotes and single quotes are synonyms for each other.

You can use either one or the other.

The result is the same.

Question #6

What will happen when you attempt to run the following code?

print(Hello, World!)

  • A . The code will raise the SyntaxError exception.
  • B . The code will raise the TypeError exception.
  • C . The code will raise the ValueError exception.
  • D . The code will print Hello, World! to the console.
  • E . The code will raise the AttributeError exception.

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topics: print() SyntaxError

Try it yourself:

# print(Hello, World!)

# SyntaxError: invalid syntax

The exclamation mark makes it a syntax error.

Question #7

A function definition starts with the keyword:

  • A . def
  • B . function
  • C . fun

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topic: def

Try it yourself:

def my_first_function():

print(‘Hello’)

my_first_function() # Hello

https://www.w3schools.com/python/python_functions.asp

Question #8

Assuming that the tuple is a correctly created tuple,

the fact that tuples are immutable means that the following instruction:

my_tuple[1] = my_tuple[1] + my_tuple[0]

  • A . can be executed if and only if the tuple contains at least two elements
  • B . is illegal
  • C . may be illegal if the tuple contains strings
  • D . is fully correct

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topics: dictionary

Try it yourself:

my_tuple = (1, 2, 3)

my_tuple[1] = my_tuple[1] + my_tuple[0]

# TypeError: ‘tuple’ object does not support item assignment

A tuple is immutable and therefore you cannot

assign a new value to one of its indexes.

Question #9

What is the expected output of the following code?

def func(x):

return 1 if x % 2 != 0 else 2

print(func(func(1)))

  • A . The code is erroneous.
  • B . None
  • C . 2
  • D . 1

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topics: def conditional expression (if else) modulus operator

not equal to operator

Try it yourself:

def func(x):

return 1 if x % 2 != 0 else 2

print(func(func(1))) # 1

print(1 % 2) # 1

print(1 % 2 != 0) # True

This is a conditional expression.

1 % 2 is 1 and therefore not equal to 0

The condition is True and the inner func() function call returns 1 That 1 is passed to the outer function which will also return 1

Question #10

Take a look at the snippet, and choose the true statements: (Select two answers)

nums = [1, 2, 3]

vals = nums

del vals[1:2]

  • A . nums is longer than vals
  • B . nums and vals refer to the same list
  • C . vals is longer than nums
  • D . nums and vals are of the same length

Reveal Solution Hide Solution

Correct Answer: B,D
B,D

Explanation:

Topics: list referencing list slicing del

Try it yourself:

nums = [1, 2, 3]

vals = nums

del vals[1:2]

print(nums) # [1, 3]

print(vals) # [1, 3]

A list is a mutable data type.

Assigning a mutable data type creates a reference to the same object.

vals and nums will point to the same object in the memory

and when you change one you automatically change the other, too.

Question #11

What is the output of the following code?

a = 1

b = 0

x = a or b

y = not(a and b)

print(x + y)

  • A . The program will cause an error
  • B . 1
  • C . The output cannot be predicted
  • D . 2

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topics: logical operators booleans addition operator

implicit type casting

Try it yourself:

a = 1

b = 0

x = a or b

print(x) # 1

print(1 or 0) # 1

y = not(a and b)

print(y) # True

print(1 and 0) # 0

print(not 0) # True

print(x + y) # 2

print(1 + True) # 2

If you calculate with a boolean True becomes the integer 1 and therefore 1 + True is 2

Question #12

What is the output of the following snippet?

dct = {}

dct[‘1’] = (1, 2)

dct[‘2’] = (2, 1)

for x in dct.keys():

print(dct[x][1], end=”)

  • A . 21
  • B . (2,1)
  • C . (1,2)
  • D . 12

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topics: dictionary tuple indexing for dict.keys() print()

Try it yourself:

dct = {}

dct[‘1’] = (1, 2)

dct[‘2’] = (2, 1)

print(dct) # {‘1’: (1, 2), ‘2’: (2, 1)}

for x in dct.keys():

print(dct[x][1], end=”) # 21

print()

print(dct[‘1’][1]) # 2

print(dct[‘2’][1]) # 1

dct.keys() are the keys ‘1’ and ‘2’

dct[‘1’][1] is 2 and

dct[‘2’][1] is 1

Question #13

What would you insert instead of so that the program checks for even numbers?

if ???:

print(‘x is an even number’)

  • A . x % x == 0
  • B . x % 1 == 2
  • C . x % 2 == 0
  • D . x % ‘even’ == True
  • E . x % 2 == 1

Reveal Solution Hide Solution

Correct Answer: C
C

Explanation:

Topics: if modulus operator equal to operator

Try it yourself:

x = 4

if x % 2 == 0:

print(‘x is an even number’) # x is an even number

Every number that divided by two does not leave a rest is even.

Question #14

What is the expected output of the following code?

x = [0, 1, 2]

x.insert(0, 1)

del x[1]

print(sum(x))

  • A . 3
  • B . 2
  • C . 4
  • D . 5

Reveal Solution Hide Solution

Correct Answer: C
C

Explanation:

Topics: insert() del sum() list

Try it yourself:

x = [0, 1, 2]

x.insert(0, 1)

print(x) # [1, 0, 1, 2]

del x[1]

print(x) # [1, 1, 2]

print(sum(x)) # 4

insert() inserts an item at a given position.

The first argument is the index of the element before which to insert.

insert(0, 1) inserts 1 before index 0 (at the front of the list).

The del keyword deletes the given object.

In this case x[1]

The sum() function adds the items of a list (or a different iterable) and returns the sum.

Question #15

The digraph written as #! is used to:

  • A . tell a Unix or Unix-like OS how to execute the contents of a Python file.
  • B . create a docstring.
  • C . make a particular module entity a private one.
  • D . tell an MS Windows OS how to execute the contents of a Python file.

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topics: #! shebang

This is a general UNIX topic.

Best read about it here:

https://en.wikipedia.org/wiki/Shebang_(Unix)

Question #16

What is the expected output of the following code?

data = [‘Peter’, 404, 3.03, ‘Wellert’, 33.3]

print(data[1:3])

  • A . None of the above.
  • B . [‘Peter’, 404, 3.03, ‘Wellert’, 33.3]
  • C . [‘Peter’, ‘Wellert’]
  • D . [404, 3.03]

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topic: list indexing

Try it yourself:

data = [‘Peter’, 404, 3.03, ‘Wellert’, 33.3]

print(data[1:3]) # [404, 3.03]

You have a list of five elements of various data types.

[1:3] slices inclusive the first index and exclusive the third index.

Meaning it slices the first and second index.

Question #17

What will be the output of the following code snippet?

d = {}

d[1] = 1

d[‘1’] = 2

d[1] += 1

sum = 0

for k in d:

sum += d[k]

print(sum)

  • A . 3
  • B . 4
  • C . 1
  • D . 2

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topics: for dictionary indexes add and assign operator

Try it yourself:

d = {}

print(d) # {}

d[1] = 1

print(d) # {1: 1}

d[‘1’] = 2

print(d) # {1: 1, ‘1’: 2}

d[1] += 1

print(d) # {1: 2, ‘1’: 2}

sum = 0

for k in d:

sum += d[k]

print("key: ", k, " – value: ", d[k])

# key: 1 – value: 2

print(sum) # 4

sum = 0

for k in d.keys():

sum += d[k]

print("key: ", k, " – value: ", d[k])

# key: 1 – value: 2

print(sum) # 4

The knowledge you need here is that a dictionary

can have indexes of different data types.

Therefore d[1] is a different index than d[‘1’]

and they can both exist in the same dictionary.

To iterate through a dictionary is the same as

iterating through dict.keys()

In k will be the keys of the dictionary.

In this case 1 and ‘1’

The value of the first key will be 2

and the value of the other key will also be 2

and therefore (the) sum is 4

Question #18

How many stars will the following snippet print to the monitor?

i = 4

while i > 0:

i -= 2

print(‘*’)

if i == 2:

break

else:

print(‘*’)

The snippet will enter an infinite loop.

  • A . 0
  • B . 2
  • C . 1

Reveal Solution Hide Solution

Correct Answer: C
C

Explanation:

Topics: if while break else (nobreak)

Try it yourself:

i = 4

while i > 0: # i is 4

i -= 2 # i is 2

print(‘*’) # *

if i == 2: # Yip, i is 2

break # Leave the loop directly

else: # Does not apply, because the break got triggered

print(‘*’)

In the first iteration the break gets directly triggered.

Therefore there will be only one star.

The else would only apply, if the break does NOT get triggered.

Question #19

What is CPython?

  • A . It’ a programming language that is a superset of the C language,
  • B . designed to produce Python-like performance with code written in C
  • C . It’ a programming language that is a superset of the Python,
  • D . designed to produce C-like performance with code written in Python
  • E . It’s a default, reference implementation of the C language, written in Python
  • F . It’s a default, reference implementation of the Python language, written in C

Reveal Solution Hide Solution

Correct Answer: F
F

Explanation:

Topic: CPython

Guido van Rossum used the "C" programming language to implement the very first version of his language and this decision is still in force.

All Pythons coming from the PSF (Python Software Foundation)

are written in the "C" language.

There are many reasons for this approach.

One of them (probably the most important) is that thanks to it, Python may be easily ported and migrated to all platforms with the ability to compile and run "C" language programs (virtually all platforms have this feature,

which opens up many expansion opportunities for Python).

This is why the PSF implementation is often referred to as CPython. This is the most influential Python among all the Pythons in the world. https://en.wikipedia.org/wiki/CPython

Question #20

What is the expected output of the following code?

def func(p1, p2):

p1 = 1

p2[0] = 42

x = 3

y = [1, 2, 3]

func(x, y)

print(x, y[0])

  • A . 3 1
  • B . The code is erroneous.
  • C . 1 42
  • D . 3 42
  • E . 1 1

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topics: def list argument passing mutable vs. immutable

Try it yourself:

def func(p1, p2):

p1 = 1

p2[0] = 42

x = 3

y = [1, 2, 3]

func(x, y)

print(x, y[0]) # 3 42

This question is about argument passing.

It is a big difference, whether you pass a mutable or an immutable data type.

The immutable integer in x gets copied to p1

and the change of p1 does not effect x

The mutable list in y gets referenced to p2

and the change of p2 effect y

Question #21

What is the expected output of the following code?

def func(data):

for d in data[::2]:

yield d

for x in func(‘abcdef’):

print(x, end=”)

  • A . bdf
  • B . An empty line.
  • C . abcdef
  • D . ace

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topics: def yield for print() with end parameter list slicing

Try it yourself:

def func(data):

for d in data[::2]:

yield d

for x in func(‘abcdef’):

print(x, end=”) # ace

The generator function will return every second element of the passed data.

Question #22

You develop a Python application for your company.

You have the following code.

def main(a, b, c, d):

value = a + b * c – d

return value

Which of the following expressions is equivalent to the expression in the function?

  • A . (a + b) * (c – d)
  • B . a + ((b * c) – d)
  • C . None of the above.
  • D . (a + (b * c)) – d

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topics: addition operator multiplication operator

subtraction operator operator precedence

Try it yourself:

def main(a, b, c, d):

value = a + b * c – d # 3

# value = (a + (b * c)) – d # 3

# value = (a + b) * (c – d) # -3

# value = a + ((b * c) – d) # 3

return value

print(main(1, 2, 3, 4)) # 3

This question is about operator precedence

The multiplication operator has the highest precedence and is therefore executed first.

That leaves the addition operator and the subtraction operator

They both are from the same group and therefore have the same precedence.

That group has a left-to-right associativity.

The addition operator is on the left and is therefore executed next.

And the last one to be executed is the subtraction operator

Question #23

What is the expected behavior of the following program?

try:

print(5/0)

break

except:

print("Sorry, something went wrong…")

except (ValueError, ZeroDivisionError):

print("Too bad…")

  • A . The program will cause a SyntaxError exception.
  • B . The program will cause a ValueError exception and output the following message: Too bad…
  • C . The program will cause a ValueError exception and output a default error message.
  • D . The program will raise an exception handled by the first except block.
  • E . The program will cause a ZeroDivisionError exception and output a default error message.

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topics: try except break SyntaxError ValueError

ZeroDivisionError

Try it yourself:

try:

print(5/0)

# break except:

print("Sorry, something went wrong…")

# except (ValueError, ZeroDivisionError):

# print("Too bad…")

There are two syntax errors:

break can not be used outside of a loop,

and the default except must be last.

Question #24

Which of the following variable names are illegal? (Select two answers)

  • A . TRUE
  • B . True
  • C . true
  • D . and

Reveal Solution Hide Solution

Correct Answer: B, D
B, D

Explanation:

Topics: variable names keywords True and

Try it yourself:

TRUE = 23

true = 42

# True = 7  # SyntaxError: cannot assign to True

# and = 7   # SyntaxError: invalid syntax

You cannot use keywords as variable names.

Question #25

What is the expected output of the following code?

z = y = x = 1

print(x, y, z, sep=’*’)

  • A . x*y*z
  • B . 111*
  • C . x y z
  • D . 1*1*1
  • E . 1 1 1
  • F . The code is erroneous.

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topic: multiple assignment print() with sep parameter

Try it yourself:

z = y = x = 1

print(x, y, z, sep=’*’) # 1*1*1

print(x, y, z, sep=’ ‘) # 1 1 1

print(x, y, z) # 1 1 1

The print() function has a sep parameter which stands for separator.

The default value of the sep parameter is a space character.

You can change it to anything you want.

Question #26

What is the expected output of the following code?

def func(text, num):

while num > 0:

print(text)

num = num – 1

func(‘Hello’, 3)

  • A . An infinite loop.
  • B . Hello
    Hello
    Hello
  • C . Hello
    Hello
    Hello
    Hello
  • D . Hello
    Hello

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topics: def while indentation

Try it yourself:

def func(text, num):

while num > 0:

print(text)

num = num – 1

func(‘Hello’, 3) # An infinite loop

The incrementation of num needs to be inside of the while loop.

Otherwise the condition num > 0 will never be False

It should look like this:

def func(text, num):

while num > 0:

print(text)

num = num – 1

func(‘Hello’, 3)

"""

Hello

Hello

Hello

"""

Question #27

What is the expected output of the following code?

x = True

y = False

z = False

if not x or y:

print(1)

elif not x or not y and z:

print(2)

elif not x or y or not y and x:

print(3)

else:

print(4)

  • A . 4
  • B . 3
  • C . 2
  • D . 1

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topics: if elif else not and or operator precedence

Try it yourself:

x = True

y = False

z = False

# if not x or y:

# if (not True) or False:

# if False or False:

if False:

print(1)

# elif not x or not y and z:

# elif (not True) or (not False) and False:

# elif False or True and False:

# elif False or (True and False):

# elif False or False:

elif False:

print(2)

# elif not x or y or not y and x:

# elif (not True) or False or (not False) and True:

# elif False or False or True and True:

# elif False or False or (True and True):

# elif False or False or True:

# elif (False or False) or True:

# elif False or True:

elif True:

print(3) # 3

else:

print(4)

There are three operators at work here.

Of them the not operator has the highest precedence, followed by the and operator.

The or operator has the lowest precedence.

Question #28

What is the expected output of the following code?

x = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

def func(data):

res = data[0][0]

for da in data:

for d in da:

if res < d:

res = d

return res

print(func(x[0]))

  • A . The code is erroneous.
  • B . 8
  • C . 6
  • D . 2
  • E . 4

Reveal Solution Hide Solution

Correct Answer: E
E

Explanation:

Topics: def for if list

Try it yourself:

x = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

def func(data):

print(‘data:’, data) # [[1, 2], [3, 4]]

res = data[0][0] # 1

print(‘res:’, res)

for da in data:

print(‘da:’, da) # [1, 2] -> [3, 4]

for d in da:

print(‘d:’, d) # 1 -> 2 -> 3 -> 4

if res < d:

res = d

return res

print(func(x[0])) # 4

print(func([[1, 7], [3, 4]])) # 7

This function looks for the highest element

in a two dimensional list (or another iterable).

In the beginning the first number data[0][0] gets taken as possible result.

In the inner for loop every number is compared to the possible result.

If one number is higher it becomes the new possible result.

And in the end the result is the highest number.

Question #29

Which of the following for loops would output the below number pattern?

11111

22222

33333

44444

55555

  • A . for i in range(0, 5):
    print(str(i) * 5)
  • B . for i in range(1, 6):
    print(str(i) * 5)
  • C . for i in range(1, 6):
    print(i, i, i, i, i)
  • D . for i in range(1, 5):
    print(str(i) * 5)

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topics: for range() str() multiply operator string concatenation

Try it yourself:

for i in range(1, 6):

print(str(i) * 5)

"""

11111

22222

33333

44444

55555

"""

print(‘———-‘)

for i in range(0, 5):

print(str(i) * 5)

"""

00000

11111

22222

33333

44444

"""

print(‘———-‘)

for i in range(1, 6):

print(i, i, i, i, i)

"""

1 1 1 1 1

2 2 2 2 2

3 3 3 3 3

4 4 4 4 4

5 5 5 5 5

"""

print(‘———-‘)

for i in range(1, 5):

print(str(i) * 5)

"""

11111

22222

33333

44444

"""

You need range (1, 6)

because the start value 1 is inclusive and the end value 6 is exclusive. To get the same numbers next to each other (without a space between them) you need to make a string and then use the multiply operator string concatenation

The standard separator of the print() function is one space. print(i, i, i, i, i) gives you one space between each number. It would work with print(i, i, i, i, i, sep=”) but that answer is not offered here.

Question #30

What is the output of the following snippet?

def fun(x, y, z):

return x + 2 * y + 3 * z

print(fun(0, z=1, y=3))

  • A . the snippet is erroneous
  • B . 9
  • C . 0
  • D . 3

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topics: positional parameter keyword parameter operator precedence

Try it yourself:

def fun(x, y, z):

return x + 2 * y + 3 * z

print(fun(0, z=1, y=3)) # 9

print(0 + 2 * 3 + 3 * 1) # 9

print(0 + (2 * 3) + (3 * 1)) # 9

print(0 + 6 + (3 * 1)) # 9

print(0 + 6 + 3) # 9

print(6 + 3) # 9

print(9) # 9

The function here works fine.

The keyword arguments do not have to be in the correct order among themselves as long as they are all listed after all positional arguments.

And because multiplication precedes addition 9 gets returned and printed.

Question #31

The value thirty point eleven times ten raised to the power of nine should be written as:

  • A . 30.11E9
  • B . 30E11.9
  • C . 30.11E9.0
  • D . 30.11*10^9

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topic: scientific notation

Try it yourself:

print(30.11E9) # 30110000000.0

# print(30E11.9) # SyntaxError: invalid syntax

# print(30.11E9.0) # SyntaxError: invalid syntax

# print(30.11*10^9) # TypeError: unsupported operand …

print(30.11 * 10 ** 9) # 30110000000.0

You could replace the E by * 10 **

Question #32

The ABC organics company needs a simple program that their call center will use to enter survey data for a new coffee variety. The program must accept input and return the average rating based on a five-star scale.

The output must be rounded to two decimal places.

You need to complete the code to meet the requirements.

sum = count = done = 0

average = 0.0

while done != -1:

rating = XXX

if rating == -1:

break

sum += rating

count += 1

average = float(sum / count)

YYY + ZZZ

What should you insert instead of XXX, YYY and ZZZ?

  • A . XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
    YYY -> print(‘The average star rating for the new coffee is: ‘
    ZZZ -> format(average, ‘.2d’))
  • B . XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
    YYY -> printline(‘The average star rating for the new coffee is: ‘
    ZZZ -> format(average, ‘.2f’))
  • C . XXX -> print(input(‘Enter next rating (1-5), -1 for done’))
    YYY -> print(‘The average star rating for the new coffee is: ‘
    ZZZ -> format(average, ‘.2f’))
  • D . XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
    YYY -> output(‘The average star rating for the new coffee is: ‘
    ZZZ -> format(average, ‘.2d’))
  • E . XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
    YYY -> print(‘The average star rating for the new coffee is: ‘
    ZZZ -> format(average, ‘.2f’))
  • F . XXX -> input(‘Enter next rating (1-5), -1 for done’)
    YYY -> print(‘The average star rating for the new coffee is: ‘
    ZZZ -> format(average, ‘.2d’))

Reveal Solution Hide Solution

Correct Answer: E
E

Explanation:

Topics: while not equal to operator if

add and assign operator float()

division operator format()

plus operator string concatenation

Try it yourself:

sum = count = done = 0

average = 0.0

while done != -1:

rating = float(input(‘Enter next rating (1-5), -1 for done’))

if rating == -1:

break

sum += rating

count += 1

average = float(sum / count)

print(‘The average star rating for the new coffee is: ‘ + format(average, ‘.2f’))

# format(average, ‘.2d’) -> ValueError: …

The input() function always returns a string

You need to cast that string to a float with the float() function.

The function to print something to the monitor is called print()

And if you want to round a float to two decimal places,

you need the format string ‘.2f’

Question #33

Consider the following code snippet:

w = bool(23)

x = bool(”)

y = bool(‘ ‘)

z = bool([False])

Which of the variables will contain False?

  • A . z
  • B . x
  • C . y
  • D . w

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topic: type casting with bool()

Try it yourself:

print(bool(23)) # True

print(bool(”)) # False

print(bool(‘ ‘)) # True

print(bool([False])) # True

The list with the value False is not empty and therefore it becomes True

The string with the space also contain one character

and therefore it also becomes True

The values that become False in Python are the following:

print(bool(”)) # False

print(bool(0)) # False

print(bool(0.0)) # False

print(bool(0j)) # False

print(bool(None)) # False

print(bool([])) # False

print(bool(())) # False

print(bool({})) # False

print(bool(set())) # False

print(bool(range(0))) # False

Question #34

What is the expected output of the following code?

def func(num):

res = ‘*’

for _ in range(num):

res += res

return res

for x in func(2):

print(x, end=”)

  • A . **
  • B . The code is erroneous.
  • C . *
  • D . ****

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topics: def return for

Try it yourself:

def func(num):

res = ‘*’

for _ in range(num):

res += res

return res

for x in func(2):

print(x, end=”) # ****

# print(x, end=’-‘) # *-*-*-*-

print()

print(func(2)) # ****

The for loop inside of the function will iterate twice.

Before the loop res has one star.

In the first iteration a second star is added.

res then has two stars.

In the second iteration two more stars are added to those two star and res will end up with four stars.

The for loop outside of the function will just iterate through the string and print every single star.

You could get that easier by just printing the whole return value.

Question #35

What is the expected output of the following code?

num = 1

def func():

num = num + 3

print(num)

func()

print(num)

  • A . 4 1
  • B . 4 4
  • C . The code is erroneous.
  • D . 1 4
  • E . 1 1

Reveal Solution Hide Solution

Correct Answer: C
C

Explanation:

Topics: def shadowing

Try it yourself:

num = 1

def func():

# num = num + 3  # UnboundLocalError: …

print(num)

func()

print(num)

print(‘———-‘)

num2 = 1

def func2():

x = num2 + 3

print(x) # 4

func2()

print(‘———-‘)

num3 = 1

def func3():

num3 = 3 # Shadows num3 from outer scope

print(num3) # 3

func3()

A variable name shadows into a function.

You can use it in an expression like in func2()

or you can assign a new value to it like in func3()

BUT you can not do both at the same time like in func()

There is going to be the new variable num

and you can not use it in an expression before its first assignment.

Question #36

The result of the following addition:

123 + 0.0

  • A . cannot be evaluated
  • B . is equal to 123.0
  • C . is equal to 123

Reveal Solution Hide Solution

Correct Answer: B
B

Explanation:

Topics: addition operator integer float

Try it yourself:

print(123 + 0.0) # 123.0

If you have an arithmetic operation with a float,

the result will also be a float.

Question #37

What is the expected output of the following code?

print(list(‘hello’))

  • A . None of the above.
  • B . hello
  • C . [h, e, l, l, o]
  • D . [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
  • E . [‘h’ ‘e’ ‘l’ ‘l’ ‘o’]

Reveal Solution Hide Solution

Correct Answer: D
D

Explanation:

Topic: list()

Try it yourself:

print(list(‘hello’)) # [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

A string is a sequence of characters

and works very fine with the list() function.

The result is a list of strings, in which every character is a string of its own.

Question #38

What is the default return value for a function

that does not explicitly return any value?

  • A . int
  • B . void
  • C . None
  • D . Null
  • E . public

Reveal Solution Hide Solution

Correct Answer: C
C

Explanation:

Topic: return

Try it yourself:

def func1():

pass

print(func1()) # None

def func2():

return

print(func2()) # None

If a function does not have the keyword return the function will return the value None

The same happens if there is no value after the keyword return

Question #39

Which of the following lines correctly invoke the function defined below:

def fun(a, b, c=0):

# Body of the function.

(Select two answers)

  • A . fun(0, 1, 2)
  • B . fun(b=0, a=0)
  • C . fun(b=1)
  • D . fun()

Reveal Solution Hide Solution

Correct Answer: A,B
A,B

Explanation:

Topics: functions positional parameters keyword parameters

Try it yourself:

def fun(a, b, c=0):

# Body of the function.

pass

fun(b=0, a=0)

fun(0, 1, 2)

# fun() # TypeError: fun() missing 2 required

# positional arguments: ‘a’ and ‘b’

# fun(b=1) # TypeError: fun() missing 1 required

# positional argument: ‘a’

Only the parameter c has a default value.

Therefore you need at least two arguments.

Question #40

What is the expected output of the following code?

x = ”’

print(len(x))

  • A . 1
  • B . 2
  • C . The code is erroneous.
  • D . 0

Reveal Solution Hide Solution

Correct Answer: A
A

Explanation:

Topics: len() escaping

Try it yourself:

print(len(”’)) # 1

The backslash is the character to escape another character.

Here the backslash escapes the following single quote character.

Together they are one character.

Exit mobile version