Unit 7 Flashcards

In this unit, you will learn how to use loops to efficiently repeat code in your programs. You will also learn how to avoid infinite loops and how to exit a loop using the break command. By the end of this unit, you will be able to Use loops to perform repetitive tasks. Select the correct looping structure to accomplish a specific task. Combine multiple loops and utilise early exit conditions.

1
Q

What is a loop?

A

A loop is a way to perform a repeated action in your program. It allows us to simplify our code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the two different types of loops?

A

For-loops and while loops.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

print(“I love Python!”)
print(“I love Python!”)
print(“I love Python!”)
What is bad about writing this code?

A

It is frustrating to have to write the same code three times in order to get the desired result.
It also increases your chance of making an error when you’re writing your program and it makes it more difficult to follow the logic that you’re using when you’re writing your program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

for count in range(0,3):

What are the words “for”, “count”, “in range” “(0,3)” for?

A

for is the command that we’re using.
“count” is the variable we’re using to keep track of how many times the loop will run.
“in range” tells Python that you want to run your loop in between a range of numbers which in this case is between 0 and 3.

The loop adds one to count each time it runs and the 0 to 3 means that count will start at 0. The loop won’t run anymore when count is equal to 3. It stops immediately.

Always remember to include the colon or your loop won’t work.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What should you code to get this as the output?
I love Python! 0
I love Python! 1
I love Python! 2

A

for count in range(0,3):
print(“I love Python!” + str(count))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

We can use an integer _____ to replace the numbers in the ___ section of the for loop.

A

We can use an integer variable to replace the numbers in the range section of the for loop.
For example:
name = input(“Name:”)
times = int(input(“Number of Times: “))
for count in range (0, times):
print(name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you count by twos or by threes?

A

The range can take a third parameter called “step”. This is how much to add to the counting variable each time the loop runs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you get this as the output using the for loop?
0
2
4
6
8

A

for count in range(0,12,2):
print(count)

This is how much to add to the counting variable each time the loops runs.
Basically for the second number in the parameter, the programme would not print it out. So it will generate a sequence of numbers starting from 0 up to (but not including) 12.
This means it starts at 0 and adds 2 each time until it reaches or exceeds 10.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Is it true that you can loop through words as well as numbers?

A

yes just that the structure is a little different.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What will the output of these lines of code be?
word = input(“Enter a word:”)
for letter in word:
print (letter)

A

It will print out each character of a string on a separate line.

Let’s analyse these lines of code.
The first line of this code asks the user for a word.
The next part is our for statement that prints each letter separately. It tells us that for each character (which we’re temporarily storing in a variable called letter) in a string (which we stored in the variable word), do something.
In this case, the “do something” is print out the contents of the temporary variable letter.

the output will be
P
y
t
h
o
n

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Explain what this code does.

word = input(“Enter a word:”)
letter_to_find = input(“Enter a letter to find: “)
for letter in word:
if letter == letter_to_find:
print(“Found it!”)

A

The first two lines are getting the information from the user: the word to search and what letter to search for.
instead of printing out the letter, we added an if statement to compare the letter to the letter we’re trying to find. If they are the same (if we found the letter), it prints out the statement that “Found it!”

What do you think will happen if the letter we are trying to find appears more than once? It will print out the word Found it for each letter.
For example:
Enter a word: science
Enter a letter to find: c

Output:
Found it!
Found it!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What would the output be for this?
for i in range(0,4):
print(i)

A

0
1
2
3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What would the output be for this?
for i in range(1,5):
print(i)

A

1
2
3
4

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What would the output be for this?
for i in range(1,5):
print(i+1)

A

2
3
4
5

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

When can the while loop be used?

A

It can be used until another piece of code tells it to stop.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Typically, you want to use a _____ when there is a given start and a given end to your loop.

A

For loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

_____ are best used when it will run until something happens inside the loop to tell it not to run anymore.
What do we use to help control that? (Tell it to run until something happens inside the loop to tell it not to run anymore)

A

While loops.

We use a Boolean variable to help control that. Boolean variables can either be “True” or “False”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

To generate random numbers, we first need to import Python’s random module. What is the code for that?

Then we call _________________ to produce random numbers for our needs

A

import random

Then we call different functions in that module to produce random numbers for our needs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Is this statement true?
We can use while loops with variables that are not Boolean values as well.

A

Yes. These can make while loops look like for loops and, sometimes, you can use them interchangeably. It takes practice to learn about the best place to use a for loop and the best place to use a while loop. Remember, a for loop steps through a set number of things whereas a while loop runs until something tells it not to do that.

20
Q

When do we use a for loop and when do we use a while loop?

A

Remember, a for loop steps through a set number of things whereas a while loop runs until something tells it not to do that.

21
Q

What is the output for this?
i=0
while i<4:
print(i)
i = i +1

A

0
1
2
3

22
Q

What is the output for this?
i = 0
while i<4:
i = i + 1
print(i)

A

1
2
3
4

23
Q

What is the output for this?
i = 1
while i<5:
i = i + 1
print(i)

A

2
3
4
5

24
Q

What is the command that stop a program from running?

A

The break command
One particularly useful programming technique with while loops is the break command.

25
Q

Is it true that: instead of using a variable containing true or False, you can set your while loop up to run indefinitely.

A

Yes. Furthermore, when you want to stop the while command from running, you can use the “break” command to exit out of it.

26
Q

What would happen if you did not include the “break” statement in a while loop?

A

The while loop would run forever. This is called an infinite loop and it’s a common programming error.

27
Q

How do you get out of an infinite loop if you find yourself in one?

A

A quick way to get out of it is to press Ctrl and C together. That will force your python program to end.

28
Q

For this program how do we add the break command here?

password = “giggles”
no_password = True
while (no_password):
guess = input(“Password:”)
if (guess == password):
print(“You got it!”)
no_password = false
else:
print(“Try again!”)

A

password = “giggles”
while(True):
guess = input(“Password:”)
if (guess == password):
print(“You got it!”)
break
else:
print(“Try again!”)

29
Q

Code a program that does the following:

Prints out the numbers from 1 to 10.
The program pauses mid-way through and asks the user if they want to continue printing.
If the user answers no, the program quits the loop.

A

Loop to print out numbers
for i in range(0,10):
# Check mid-way through
if i == 5:
response = input(“Do you want to continue?(yes/no) “)
if response == ‘no’:
break
# Print out number
print(i+1)

30
Q

What is the meaning of nesting loops?

A

This means you can place a loop inside of a loop to give you greater control over your programs.

31
Q

Is it true that you can nest a for loop inside a while loop, a for loop inside a for loop or even a while loop inside a while loop?

A

Yes. Just like we put an if statement inside (or nested) our while loop in a previous lecture, you can nest a for loop inside a while loop, a for loop inside a for loop or even a while loop inside a while loop.

32
Q

Analyse this code
factor1 = 5
for factor2 in range (1,13):
print(str(factor1) + “ + “ + str(factor2) + “ = “ +
str(factor1 + factor2) + “\t” + str(factor1) + “ x “ +
str(factor2) + “ = “ + str(factor1 * factor2))

A

The first thing we do is set the first factor to 5, since that’s number we’re doing the addition and multiplication table for. (First line)

Then, we have our for loop that takes turns setting the second factor to the numbers between 1 and 12. (Second line) The range is set from 1 to 13 because remember that it will stop when it hits 13 and not run the loop (but we want it to run the loop for 12).

Then, we have our print statement printing out the addition and multiplication problem.
The “\t” is a tab character. It inserts white space to make our print out look attractive and readable.

33
Q

Unpredictability can be simulated in computer programming using __________. _________ have applications in computer game programming, computer simulations and other areas where producing an unpredictable result is useful.

A

Unpredictability can be stimulated in computer programming using random numbers.

Random number generators have applications in computer game programming, computer simulations and other areas where producing an unpredictable result is useful.

34
Q

What are the three different functions for Functions for Random Integers?

A

1st type

random.randint(a,b) - Returns a random integer in the range of number a to number b.

Random integer from 1 to 10
»>random.randint(1,10)
10

2nd type
random.randrange(stop) - Returns a random integer in the range of 0 to the number given.

Random integer from 0 to 9
»>random.randrange(10)
7

Third type
random.randrange(start,stop,[step]) - Returns a random integer between start (including) and stop (excluding) counting by an optional interval [step].

Random even integer from 0 to 8
»>random.randrange(0,10,2)
6

35
Q

What is the function for random sequence?

A

random.choice(seq) - Returns a random item from a sequential list

> > > random.choice([‘red’,’green’,’yellow’,’pink’])
‘yellow’

36
Q

What are the two different functions for random floats?

A

1st type
random.random() - Returns the next random floating point number in the range of 0 to less than 1.

> > > random.random()
0.42229449745952374

2nd type
random.uniform(a,b) - Returns a random floating point number in the range of number a to number b.

> > > random.uniform(1,10)
6.090785644490166

37
Q

What will be the output of the following code snippet?

def fun():
    print('Python is fun')
    
def learn():
    print('Learning Python')
        
more = True
i = 1
while(more):
    i = i + 1
    if i == 4:
        fun()
    elif i == 7:
        more = False
    else:
        learn() Question 1Select one:

a.
Learning Python
Python is fun
Learning Python
Learning Python
Learning Python

b.
Learning Python
Learning Python
Python is fun
Learning Python
Learning Python

c.
Learning Python
Learning Python
Learning Python
Python is fun
Learning Python

d.
Learning Python
Learning Python
Learning Python
Learning Python
Python is fun

A

b

this is because when i is 2 and then 3, Learning python will be printed twice. Then when i ==4, Python is fun will be printed.
When i == 6 and then i ==7, learning python is again printed twice. Finally, the while loop ends when i == 7

38
Q

When we know the number of times we need to run the loop, the preferred choice of loop construct is the for loop.

Question 2Select one:
True
False

A

True

39
Q

What will be the output after the loops end?

i = 1
j = 1
amount = 0

while i < 4:
    while j < 4:
        amount = amount + 1
        j = j + 1
    i = i + 1

print(amount) Question 3Select one:

a.
This is an infinite loop.

b.
1

c.
3

d.
9

A

c

First round of while loop: i =1, j =1 , amount = 1, j =2 , i =2

Second round of while loop: i =2, j= 2, amount = 2, j = 3 i = 3

Third round of while loop:
i = 3, j =3, amount = 3, j =4 , i =4

While loop stops as i is not smaller than 4

print(amount) = 3

40
Q

How many times will “I love Python!” be printed in the code below?

for count in range(150, 200):
    print("I love Python!") Question 4Select one:

a.
49 times

b.
50 times

c.
51 times

d.
It displays an error message.

A

so for count in range, let’s say for count in range (1, 10)
the for loop will print that statement 1,2,3,4,5,6,7,8,9 which is a total of 9 times (excluding the second number in the parameter)

since 10-1 = 9 (is the number of times it is printed,

then 200-150 = 50 (answer)

41
Q

What will be the output of the code snippet?

for count in range(0,2):
for counter in range(1,3):
print(“Nested Loop”)
Question 5Select one:

a.
Nested Loop
Nested Loop

b.
Nested Loop
Nested Loop
Nested Loop

c.
Nested Loop
Nested Loop
Nested Loop
Nested Loop

d.
Nested Loop
Nested Loop
Nested Loop
Nested Loop
Nested Loop

A

the first for loop shows that it will only loop twice

the second for loop show that it will loop twice.

so for the first time when the for loop runs, it will be loop two times by the second for loop thus nested loop will be printed twice.

Then for the second time the for loop runs, it will again be loop twice by the second for loop and thus nested loop will be printed twice.

So in total nested loop will be printed four times.

Ans: c

42
Q

Fill in the blank to ensure the program ends correctly.

x = 0
while True:
    x = x + 2
    print(x)
    add_more = input("Add more? (Yes or No): ")
    if add_more == "No":
        print("Goodbye!")
        \_\_\_\_\_\_\_\_\_\_ Question 6Select one:

a.
break

b.
stop

c.
continue

d.
exit

A

a

43
Q

Which of the following is true about for loops?

Question 7Select one:

a.
for loops must always use the range() function.

b.
for loops cannot be nested.

c.
for loops are ideal if you know ahead of time how many times you want to execute your code.

d.
for loops are controlled using a True/False (Boolean) condition.

A

Answer: c

a is not true because you can ay something like
for letters in flashcard():
print(letters)

Output:
f
l
a
s
h
c
a
r
d

For option c, it is not true that for loops cannot be nested.

For option d, it is incorrect. while loops are controlled using Boolean conditions. for loops, on the other hand, iterate over a sequence or range of values.

44
Q

What is the output of the following code snippet?

for x in range(1, 2):
    for y in range(1, 9):
        if (x * y % 4 == 0):
            print(x * y) Question 8Select one:

a.
2
6
10
14
18

b.
4
8
12
16

c.
2
4
6
8

d.
4
8

A

The correct answer is:

d. 4 8

Explanation:
Outer Loop:

for x in range(1, 2) means x will only take the value 1 because range(1, 2) generates values starting from 1 up to (but not including) 2.
Inner Loop:

for y in range(1, 9) means y will take values from 1 to 8 (inclusive).
Condition:

The condition if (x * y % 4 == 0) checks if the product of x and y is divisible by 4.
Analysis of Iterations:

For x = 1:
When y = 1, x * y = 1 * 1 = 1, not divisible by 4.
When y = 2, x * y = 1 * 2 = 2, not divisible by 4.
When y = 3, x * y = 1 * 3 = 3, not divisible by 4.
When y = 4, x * y = 1 * 4 = 4, divisible by 4 → Print 4.
When y = 5, x * y = 1 * 5 = 5, not divisible by 4.
When y = 6, x * y = 1 * 6 = 6, not divisible by 4.
When y = 7, x * y = 1 * 7 = 7, not divisible by 4.
When y = 8, x * y = 1 * 8 = 8, divisible by 4 → Print 8.
Output:
The numbers printed are 4 and 8. Hence, the correct answer is:

d.
4
8

45
Q

Which of the following is true about loops?

*Choose all that apply.

Question 9Select one or more:

a.
You can loop through a string like “banana”.

b.
There is only one way to loop in Python.

c.
Loops help us simplify our programs.

d.
Whitespace is not meaningful in loops.

e.
You can program a loop to go on forever.

f.
Loops cannot be nested.

A

The correct answers are:

a. You can loop through a string like “banana”.

Explanation: Yes, you can loop through a string like “banana” in Python. For example, you can iterate over each character in the string using a for loop.
python
Copy code
for char in “banana”:
print(char)
c. Loops help us simplify our programs.

Explanation: Loops help us simplify our programs by automating repetitive tasks, reducing the amount of code we need to write, and making the code more readable and efficient.
e. You can program a loop to go on forever.

Explanation: Yes, a loop can run indefinitely if the condition in a while loop is always True, or if there is no exit condition in a for loop. This is called an infinite loop.
python
Copy code
while True:
print(“This will run forever”)
Incorrect Answers:

b. There is only one way to loop in Python.

Explanation: This is false. Python supports multiple ways to loop, such as for loops and while loops.
d. Whitespace is not meaningful in loops.

Explanation: This is false. In Python, whitespace (indentation) is very important, as it defines blocks of code. Improper indentation will result in errors.
f. Loops cannot be nested.

Explanation: This is false. In Python, loops can be nested, meaning you can have one loop inside another loop.
So, the correct answers are:

a, c, e.

46
Q

What is the output of this code snippet?

i = 1

while i > 0:
    i = i + 1
    while i == 10:
        i = i - 10

print(i) Question 10Select one:

a.
1

b.
10

c.
0

d.
This is an infinite loop.

A

Let’s break down the code step by step:

python
Copy code
i = 1

while i > 0: # The condition i > 0 is True, so the loop will run.
i = i + 1 # i will be incremented by 1 in each iteration.
while i == 10: # When i equals 10, this nested loop will run.
i = i - 10 # This will decrease i by 10.

print(i) # After exiting the loops, print the final value of i.
Analysis:
Initial value of i: i = 1
First iteration of the outer while i > 0:
i = i + 1 → i becomes 2.
The condition i == 10 is False, so the inner loop does not run.
Second iteration of the outer while i > 0:
i = i + 1 → i becomes 3.
The condition i == 10 is False, so the inner loop does not run.
This process continues, incrementing i by 1 until i becomes 10.
When i == 10, the inner loop starts to execute:
i = i - 10 → i becomes 0.
Now i = 0, and since the outer loop’s condition is i > 0, the outer loop terminates.
Final value of i: 0
Thus, the correct answer is:

c. 0