84.4k views
1 vote
Question 4: Write the code for a for-loop that prints the following outputs. You should be able to do it with either a single for-loop or a nested for-loop. Output 1: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Output 2: 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0

User Wubbalubba
by
3.4k points

1 Answer

2 votes

Answer:

see explaination

Step-by-step explanation:

Program source code below:

def displayNumbers():

string = ""

num = 0

#first loop to control 5 rows

for i in range(5):

#second loop to control columns

for j in range(5):

str1 = str(num)

# str1.ljust(5) function to left justify output string

#appending number in resulting string

string = string + str1.ljust(5)

#updating num for next iteration

num = num + 1

#new line after each row to display pattern correctly

string = string + "\\"

return string

def pattern():

string = ""

num = 0

#first loop to control 1-4 rows

for i in range(5):

#In second loop to control 5 columns

for j in range(5):

str1 = str(num)

if num == 2:

num = num -2

else :

num = num + 1

# str1.ljust(5) function to left justify output string

string = string + str1.ljust(5)

# new line after each row to display pattern correctly

string = string + "\\"

return string

#Function calls

print('\033[4m')

print('\033[1m{}\033[0m'.format('Output 1:\\'))

print(displayNumbers())

print('\033[4m')

print('\u0332\033[1m{}\033[0m'.format('Output 2:\\ew'))

print(pattern())

See attachment for sample output and screenshot.

Nb: Always refer to screenshot if there is an indentation error.

Question 4: Write the code for a for-loop that prints the following outputs. You should-example-1
Question 4: Write the code for a for-loop that prints the following outputs. You should-example-2
Question 4: Write the code for a for-loop that prints the following outputs. You should-example-3
User Pavlos Panteliadis
by
3.5k points