In: Computer Science
What is the output of the following code:
x = 0
a = 1
b = -3
if a > 0:
if b < 0:
x = x + 5
elif a > 5:
x = x + 4
else:
x = x + 3
else:
x = x + 2
print(x)
4 |
||
2 |
||
5 |
||
3 |
Consider the following code segment:
sum = 0.0
while True:
number = input(“Enter a
number: “)
if number ==
“”:
break
sum +=
float(number)
How many iterations does this loop perform?
zero or more |
||
none |
||
ten |
||
at least one |
Which expression below will check to see if someone is 18 years old or older? Assume you have their age in a variable named age:
not age < 18 |
||
age > 18 |
||
age >> 18 |
||
age == 18 and age > 18 |
PART 1 -
ANSWER -
3rd option i.e. 5 is the correct answer
EXPLANATION -
In the program, the value of a is greater than 0 and that of b is less than 0. So, the statement
x = x + 5
gets executed. The starting value of x is 0. So, after execution of above statement, the value of x becomes 5. So, after execution of the last statement of the program i.e.
print(x)
5 gets printed.
PART 2 -
ANSWER -
4th option i.e. at least one is the correct answer
EXPLANATION -
while True is an infiite loop. It runs until it gets forcefully exited from inside the loop. In the program, when the first iteration is performed, if user did not enter anything, then the condition inside the if statement becomes true and the break statement executes and we come out of loop.
But if user enters a number, then the condition inside the if statement becomes false and so the loop continues to the next iteration after executing the last statement inside the loop.
So, we can clearly state that the loop performs at least one iteration. Exactly how many number of iterations it will perform will depends on the user input in each iteration
PART 3 -
ANSWER -
1st option i.e. not age < 18 is the correct answer
EXPLANATION -
1st option indicates that age is not less than 18 which simply means that either the age is equal to 18 or the age is greater than 18. So, the first option is correct.
2nd option indicates that age is greater than 18. It implies that age cannot be equal to or less than 18. But we need to check if someone is either 18 years old or older which cannot be determined by the expression in the 2nd option because it will not evaluate to true if someone is 18 years old. So, 2nd option is wrong.
3rd option is a right shift operator. So, it cannot be used to compare two values. So, 3rd option is wrong.
4th option evaluates to true only when someone is 18 years old and older which can never be true. So, 4th option is also wrong.
If you have any doubt regarding the solution, then do
comment.
Do upvote.