Home > Software engineering >  not the desirable output
not the desirable output

Time:12-02

the expected out put was

1 1
2 2
3 3
4 4
5 5

but the output I got is

1
1 2
2 3
3 4
4 5
5 
for num in numlist:
    print(num)
    print(num,end=' ')

I tried to execute this python code in python interpreter and got the wrong output

CodePudding user response:

Every print has an end. Unless you overwrite what print should end in, it ends in a new line. In your first print, you don't overwrite end, so you get a new line. In your second print command, you do overwrite end with a single whitespace.

What you get is this order:

1st print NEWLINE
2nd print SPACE 1st print NEWLINE
2nd print SPACE 1st print NEWLINE
...

You get the exact output you are asking for. I suggest you read the entire Input/Output section of this geeksforgeeks page: https://www.geeksforgeeks.org/taking-input-in-python/?ref=lbp

CodePudding user response:

newline ('\n') is the default end character. Therefore the first call to print() will emit the value of num followed by newline.

In the second print you override the end character with space (' ') so no newline will be emitted.

When you print multiple values, the default separator is a space. This means that you can achieve your objective with:

for num in numlist:
    print(num, num)
  • Related