Nesting Practice
Let’s try some simple practice problems. These problems are not graded - they are just for you to practice before doing the real exercises in the lab itself. You can find the answers below each question by clicking the button below each question.
5.7 Reading Code
Consider the following Python program:
x = int(input("Enter a positive integer: "))
while x <= 0:
print("Invalid input!")
x = int(input("Enter a positive integer: "))
n = x
for i in range(n - 1):
for j in range(n - i - 1):
print(" ", end="")
for j in range(i + 1):
print("* ", end="")
print("")
for i in range(n):
for j in range(n):
print("* ", end="")
print("")
Describe the shape that will be printed when this program is executed. Try to do so without running the code directly, but feel free to check your answer after guessing.
5.8 Debugging Code
Consider the following Python program:
x = 3
y = 5
while x => 0:
for i in range(y):
print("* ")
print("")
x = x + 1
This code is supposed to print a rectangle of asterisks that is x
rows tall and y
columns wide. However, it contains multiple syntax and logic errors preventing it from working correctly. Describe how to fix the errors in the given code to produce the desired output.
5.9 Writing Code
Write a complete Python program in that file that meets the specification below.
Write a program that will print a Parallelogram of asterisks that is m
rows tall and n
columns wide, where the topmost row is furthest toward the left. The values m
and n
should be provided by the user as input. If the user inputs a value that is
$ 0 $ or negative, the program should print an error and prompt for input again.
For example, if the user inputs $ 3 $ and $ 5 $, the program should provide the following output:
* * * * *
* * * * *
* * * * *
Notice that each asterisk is separated by a space, and each successive row of the parallelogram begins one space to the right of the previous row.