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 Indentation error as print statement should be indented

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 and is invalid as a conditional expression and hence will throw a Syntax Error

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 evaluates 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?
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 above 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 multiple 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

What is the output when the below program is run?
a = 5; b = 2; c = 20; d = 5
if c / a > b:
  b = b + c
else:
   b = b + a
c = c * a - b / 2
if (b < c and d < a):
   d = d / 2
else:
   a = c - 3
if d % b == 0:
   d = c + a
if (c / 2 > b or d - a == b):
   d = d - 3
print(a, b, c, d)

86.0 22 89.0 2 86 22 89 2 86.0 2 89.0 2 86.0 22 89.0 5 Remeber to apply PEMDAS rules. It does not hurt to write down the variable values on a piece of paper in a tabular form, after every statement to keep track of how they all are changing or not after every statement is executed.

Exercise

results matching ""

    No results matching ""