Quiz

Study the code below
a = 3
b = 20
if b > a:
print("hey")
What is the output from the above statement

hey Error Nothing a[-6] Indentation error as print statement should be indented

What is the output of the given code?
while true:
  print('a')
  break

Error a Infinite loop true is not same as True. In Python boolean value is True with the uppercase T

What is the output of the given code?
a = 10
b = 40
if a = b:
  print ('equal')
else:
  print('not equal')

Error not equal equal Equality operator is == which returns True or False based on its evaluation. Single = is an assignment operator

What is the output of the given code?
while True:
  print('a')
break

Error a Infinite loop break is not inside the while block and you get an infinite loop. As such you cannot have a 'break' outside of a loop. However even before the interpreter can find out about this problem, it is busy looping endlessly through the while loop which comes before the break

What is the output of the given code?
a = 10
b = 40
if (a != b):
  print (a)
else:
  print(b)

Error as there is parenthesis after if 10 a Parenthesis is not required. However if you have a parenthesis it does not hurt as long as the boolean expression evaulates to True/False or any number other than 0.

What is the output of the given code?
a = 10
if a:
  print (a)
else:
  print('a')

Error as there is no boolean expression 10 a Python considers any literal value other than None and 0 as True. So 10 is treated as True.

What is the output of the given code?
a = 0
while a < 10:
   a + 2
print(a)

10 12 Infinite Loop a+2 is not saved back to 'a'. So a's value never changed. If you replace a = a + 2 or a += 2 then it prints 10

What is the output of the given code?
x = 20
message = ''
if (x%2 == 0):
   message += 'Nay'
if (x%5 == 0):
  message += "dah!"
if (x%2 == 0 and x%5 == 0):
  message += "Yay"
print(message)

Nay dah! Yay Naydah!Yay Since there is no elif or else, all the if blocks will be executed in an order

How would you change the code to print only 'Yay' if the number 'x' is a multiple of 2 and 5 and 'Nay' when it is multiple of only 2 and 'dah!' when it is a mutiple of only 5?

Change the given number x Add else before each if block Move the last if block which tests multiple of 2 and 5 as the first if block of the chain and change all other if blocks to elif

Exercise

results matching ""

    No results matching ""