Home > Software engineering >  in my for how to print a specific line only once while the remaining loop prints as normal
in my for how to print a specific line only once while the remaining loop prints as normal

Time:11-30

i am trying to create a loop that print the table of number entered by the user but i want to print this line print ("table of" ,table, "is shown below") only once . look at my code below

table = (int(input("enter your number")))
for i in range (11) :
    print ("table of" ,table, "is shown below")
    print (f"{table} x {i} = {table*i})

the output i get is

enter your number 47
table of 47 is shown below
47 x 0 = 0
table of 47 is shown below
47 x 1 = 47
table of 47 is shown below
47 x 2 = 94
table of 47 is shown below
47 x 3 = 141
table of 47 is shown below
47 x 4 = 188
table of 47 is shown below
47 x 5 = 235
table of 47 is shown below
47 x 6 = 282
table of 47 is shown below
47 x 7 = 329
table of 47 is shown below
47 x 8 = 376
table of 47 is shown below
47 x 9 = 423
table of 47 is shown below
47 x 10 = 470

but the output i want is

the table of 47 is shown below
47 x 0 = 0
47 x 1 = 47
47 x 2 = 94
47 x 3 = 141
47 x 4 = 188
47 x 5 = 235
47 x 6 = 282
47 x 7 = 329
47 x 8 = 376
47 x 9 = 423
47 x 10 = 470

CodePudding user response:

You can just put the first print statement outside of the loop:

table = (int(input("enter your number")))
print("table of" ,table, "is shown below")
for i in range(11):
    print(f"{table} x {i} = {table*i})

If you have a case where something needs to be inside the loop, you can make a variable and set it to false after the first loop:

table = (int(input("enter your number")))
first_iteration = True
for i in range(11):
    if first_iteration:
        print("table of" ,table, "is shown below")
        first_iteration = False
    print(f"{table} x {i} = {table*i})

CodePudding user response:

Just push the print ("table of" ,table, "is shown below") line above the for-loop.

table = (int(input("enter your number")))
print ("table of" ,table, "is shown below")
for i in range (11) : 
    print (f"{table} x {i} = {table*i}")

Output for the number 5:

enter your number5
table of 5 is shown below
5 x 0 = 0
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
  • Related