Skip to main content

Section 5.11 Write Code Questions

Warning 5.11.1.

Be careful not to create infinite loops, as they will cause the page to freeze.
In these exercises, you will be asked to create a variable using the + as the concatenation operator to join strings together. As a refresher, if both the operands of + are strings, there’s no problem: "door" + "bell" gives the string "doorbell".
If one of the operands is a number, though, you must use the str function to convert it to a string. Let’s say you have a variable named count that has the value 3, and you want to add the string " pages" to the end of it. You can not do this:
count = 3
result_string = count + " pages"
Instead, you must convert the number to a string:
count = 3
result_string = str(count) + " pages"

Checkpoint 5.11.2.

Fix the errors in the code below so that answer contains a countdown of the numbers from 10 to 0, including 0.
Solution.
counter = 10
answer = ""

# Keep running loop until counter equals 0 (use >=)
# Use correct variable name (counter is lowercase)
while counter >= 0:
    answer = answer + str(counter) + " "

    # Decrement to lower the counter
    counter = counter - 1

print(answer)

Checkpoint 5.11.3.

The following code will loop way too many times. Change one line to make the loop only have five iterations.

Checkpoint 5.11.4.

Make changes to the code below to correctly print a count up from -10 to 0, including 0.
Solution.
output = ""
# Start x at -11 so it stays under 0
x = -11

# First line of a loop ends with a colon (:)
while x < 0:

    # Since the iteration variable is negative, increase the count
    x = x + 1

    # Output reassignment is within the loop
    output = output + str(x) + " "

# Close print parentheses
print(output)

Checkpoint 5.11.5.

Finish lines 1 and 5 so that the following code correctly prints every integer from -5 to -1, including -1.

Checkpoint 5.11.6.

Complete the code on lines 4 and 6 so that it prints the number 6.
Solution.
x = 3
i = 0
while i < 3:
    # Increase x by 1 for each run of the loop
    x = x + 1
    i = i + 1
# Print the x variable
print(x)

Checkpoint 5.11.7.

This function currently takes a start and stop argument and uses a for loop to find the sum of all the numbers between them (inclusive). Change the for loop to a while loop while still using the same parameters.
Solution.
This function currently takes a start and stop argument and uses a for loop to find the sum of all the numbers between them (inclusive). Change the for loop to a while loop while still using the same parameters.
def sumFunc(start, stop):
    sum = 0
    # Create an iteration variable, initialized to the start argument
    num = start
    # Use while loop until iteration variable is less than
    # or equal to stop argument
    while num <= stop:
        # Add number to sum
        sum = sum + num
        # Increase iteration variable
        num += 1
    # Return the sum
    return sum

print(sumFunc(1,10))