In: Computer Science
Using PyCharm, create a new Project lab8. Under lab8 create a new Directory exercise, then create a Python file called nested.py, type the following:
Test your code by putting the following at the bottom of the file: make_table_of_stars(2,3) (as shown in the code above). Run the file by right clicking in the code area of Pycharm, then choosing “Run nested”. Your output should be:
***
***
(2 rows with 3 columns of stars). Reverse the 2 and 3. What happens? Make a new function, make_table_of_digits that prints the digits 1..row*column instead. So nested.make_table_of_digits(2,3) would print:
123
456
To do this, change the '*' to a number. This is a little tricky. Start by just getting the first row correct. Change the printed '*' to print the value of j yields:
012
012
when make_table_of_digits(2,3) is called. Since you want to start with 1, not 0, change number being printed to (j+1) instead of j. Then, make_table_of_digits(2,3) should print
123
123
Much better. The whole first row is correct. To increase the numbers after the first row, multiply row number (i) times the total number of columns. Then, add that value to (j+1), and print. Then make_table_of_digits(2,3) prints:
123
456
That works well until you try make_table_of_digits(5,3), which prints:
123
456
789
101112
131415
make_table_of_digits only works well with 1 digit numbers. Create a new function, make_table_of_numbers, which makes each number take up 3 spaces using string.format. For example,
n = 3
print("{:3}".format(n), end=" ")
would print --3, where ‘-’ is a space. make_table_of_numbers(5,3) should print:
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
Test your solution and submit.
The code is well commented to understand the initial flow and has carried out steps as mentioned in the question.
def make_table_of_stars(rows, cols):
# using for loop to iterate over rows
for i in range(rows):
# using for loop to iterate over cols
for j in range(cols):
print("*", end="")
# print() to go to next line
print()
print()
make_table_of_stars(2,3)
make_table_of_stars(3,2)
def make_table_of_digits(rows, cols):
for i in range(rows):
for j in range(cols):
print(i*cols + (j+1), end="")
print()
print()
make_table_of_digits(2,3)
make_table_of_digits(5,3)
def make_table_of_numbers(rows, cols):
for i in range(rows):
for j in range(cols):
print("{:3}".format(i*cols + (j+1)), end=" ")
print()
print()
make_table_of_numbers(5, 3)
Output: