Why does print() print outputs one below the other and not the other?

Asked

Viewed 155 times

4

Continuing my studies in Python, a new doubt arose. Before asking, I researched here on Sopt using the expression "print next to Python" and I did not find anything that could kill my doubt and solve the problem. So come on:

I wrote the following code, very simple, just to illustrate the problem, let’s go to it:

a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
for i in range(a+1,b):
    print(i)

I got the next exit:

Digite o primeiro número: 5
Digite o segundo número: 20
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>>

The doubt is as follows: Why the function print() always prints the outputs this way, one underneath the other? How to make it print the outputs next to each other without using list resources?

3 answers

3

You can do this way using the Python 2

print "Seu texto",

And in this way using the Python 3

print("Seu texto", end="", flush=True)

The function print has a final parameter whose default is "n". Set you up a string empty prevents it from creating a new line in the final.

Source

  • It worked, but then the exit got all the numbers glued together, like it was a big multi-digit number. However, a change in what you posted made it work. I did so: print(i,end=",",flush=True).

  • 1

    That, the end swaps the pattern ' n' which is the line break for "" which is an empty string, so by putting "," it swaps ' n' for comma or any other string you want :)

1

The print() is a function Buil-in of Python which has some arguments defined by default, let’s see:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

We can alternate the argument end if we wish to make a print differentiated, as for example:

print(i, end=' ')

We will have as a result:

output: 6 7 8 9 10 11 12 13 14 15 16 17 18 19

0


The signature of the function print is the following:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The third parameter, end, is what python will put after its string (line break by default). You can override it the will.

a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
for i in range(a+1,b):
    print(i, end=' ')

Digite o primeiro número: 5
Digite o segundo número: 20
6 7 8 9 10 11 12 13 14 15 16 17 18 19
>>>
  • Yes, I tested with a comma and with empty spaces, it worked. What would be the parameter flush?

  • 1

    About the flush https://answall.com/questions/291779/o-que-é-o-flush-do-print-no-python

Browser other questions tagged

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