5. Loops - 9 Questions

# 5. Loops

9 Questions
Created by Y. Daniel Liang
Free
##### In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times.
1. How many times will the following code print "Welcome to Python"?

count = 0
while count < 10:
print("Welcome to Python")
count += 1

8
9
10
11

View Answer | Discuss in forum
2. What is the output of the following code?

x = 0
while x < 4:
x = x + 1

print("x is", x)

x is 1
x is 2
x is 3
x is 4

View Answer | Discuss in forum
3. Analyze the following code.

count = 0
while count < 100:
# Point A
print("Welcome to Python!")
count += 1
# Point B

# Point C

count < 100 is always True at Point A
count < 100 is always True at Point B
count < 100 is always False at Point B
count < 100 is always True at Point C

View Answer | Discuss in forum
4. How many times will the following code print "Welcome to Python"?

count = 0
while count < 10:
print("Welcome to Python")

9
10
11
infinite number of times

View Answer | Discuss in forum
5. What will be displayed when the following code is executed?

number = 6
while number > 0:
number -= 3
print(number, end = ' ')

6 3 0
6 3
3 0
3 0 -3

View Answer | Discuss in forum
6. Analyze the following statement:

sum = 0
for d in range(0, 10, 0.1):
sum += sum + d

The program has a syntax error because the range function cannot have three arguments.
The program has a syntax error because the arguments in the range must be integers.
The program runs in an infinite loop.
The program runs fine.

View Answer | Discuss in forum
7. Which of the following loops prints "Welcome to Python" 10 times?

A:
for count in range(1, 10):
print("Welcome to Python")

B:
for count in range(0, 10):
print("Welcome to Python")

C:
for count in range(1, 11):
print("Welcome to Python")

D:
for count in range(1, 12):
print("Welcome to Python")

BD
ABC
AC
BC

View Answer | Discuss in forum
8. The function range(5) return a sequence ______________.

1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
1, 2, 3, 4
0, 1, 2, 3, 4

View Answer | Discuss in forum
9. Which of the following loops correctly computes 1/2 + 2/3 + 3/4 + ... + 99/100?

A:
sum = 0
for i in range(1, 99):
sum += i / (i + 1)

print("Sum is", sum)

B:
sum = 0
for i in range(1, 100):
sum += i / (i + 1)

print("Sum is", sum)

C:
sum = 0
for i in range(1.0, 99.0):
sum += i / (i + 1)

print("Sum is", sum)

D:
sum = 0
for i in range(1.0, 100.0):
sum += i / (i + 1)

print("Sum is", sum)

BCD
ABCD
B
CDE

View Answer | Discuss in forum