0

class Passenger:

def __init__(self, name, IsBooked):
    self.name = name
    self.IsBooked = IsBooked

Seats = [[0]*2]*2

for i in range(2):

for j in range(2):
    Seats[i][j] = Passenger('', False)

for i in range(2):

for j in range(2):
    if(Seats[i][j].IsBooked == False):
        print('X')
print('\n')

I want to print the output as

X X

X X

But I am getting the result as

I am getting the result as

Where Should I modify the code to get the expected result?

  • As an aside, `Seats = [[0]*2]*2` is not doing what you think it is. See: https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – juanpa.arrivillaga Aug 02 '22 at 07:52
  • 1
    You're literally printing `\n` on every iteration of `for i` - what did you expect? Unindent that `print('\n')` line and done – Grismar Aug 02 '22 at 07:53

2 Answers2

0
class Passenger:
    def __init__(self, name, IsBooked):
        self.name = name
        self.IsBooked = IsBooked


Seats = [[0]*2]*2
for i in range(2):
    for j in range(2):
        Seats[i][j] = Passenger('', False)

for i in range(2):
    for j in range(2):
        if(Seats[i][j].IsBooked == False):
            print('X', end='')

You will need to remove print('\n') in last line as it is being executed after every two elements.

  • I want result as. X X X X But after removing that line I am getting X in new line each time I want to print in same line – Hasnain Ali Aug 02 '22 at 08:06
  • ohh print function ends with '\n' escape sequence (new line) by default. You can give another argument `end=''` in function. Your new print function will become `print('X', end='')` – Muhammad Rizwan Aug 23 '22 at 11:57
0

OK

class Passenger:
    def __init__(self, name, IsBooked):
        self.name = name
        self.IsBooked = IsBooked


txt = ''
Seats = [[0]*2]*2
for i in range(2):
    for j in range(2):
        Seats[i][j] = Passenger('', False)

for i in range(2):
    for j in range(2):
        if(Seats[i][j].IsBooked == False):
            txt += 'X '
            txt_with_new_line += 'X\n'

    print(txt + '\n')
    txt = ''
#   Result
#   X X
#
#   X X
d r
  • 3,848
  • 2
  • 4
  • 15