Doubt about Python data output

Asked

Viewed 169 times

-5

I’m solving the following exercise:

Make a program that prints on the screen the numbers from 1 to 20, one below the other. Then modify the program to show the numbers next to each other.

The first part of the statement I managed to solve, using the loop while as follows:

x = 1
while x<=20:
    print(x)
    x +=1

But I’m having a hard time keeping them in line, and I have no idea how to fix this.

  • 1

    Have you tried concatenating the numbers and then displaying this concatenated value? If you don’t know how to do this, search for concatenation that you must find something that will elucidate a solution for you

  • 1

    As already mentioned above, just make a concatenation of strings, For example, suppose I say a = 'b' + 'c' and then do print(a), he will print on the screen: 'bc'

3 answers

1

To print the natural numbers starting at "1" and going up to "20", one below the other, just use the following algorithm:

x = 1
while x < 21:
    print(x)
    x += 1

or

for c in range(1, 21):
    print(c)

Now, if you want to print them next to each other, just use the following algorithm:

for c in range(1, 21):
    print(c, end=' ')
print()

Also, if you want to print the numbers next to each other, separated by a comma and with a period at the end of the sequence, you can use the following algorithm:

for c in range(1, 21):
    print(c, end='')
    print(', ' if c < 20 else '.', end='')
print()

1

As you have already got the first part, to print the numbers on one side of the other you can use the Join:

print(' '.join(str(i) for i in range(1,21)))

The join will iterate over the elements creating a single string, and print will print that string.

Exit:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Remember that in python the count starts from 0.

1

my solution:

unmodified program

rep = 1
while rep <= 20:
 print(rep)
 rep += 1

modified program

while rep <= 20:
 print(rep, end = ' ')
 rep += 1

I could also create a def, but I don’t know if you’ve ever studied it, I hope I’ve helped :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.