Skip to content
Advertisement

For loop: how to print last element without blank space?

I have a strange problem which I cant figure out for some time now. I have 4 nested for loops and in the last one:

for a in range(1, 10):
 for b in range(1, 10):
    for c in range(1,10):
        for d in range(1, 10):
            if flag_c_d and flag_a_b and control_flag:
                print(f'{a}{b}{c}{d}',end=' ')
                counter += 1
                if counter == 4:
                    password = True
                    passcode += a*1000 +b*100 +c*10 + d
                if counter == 0 or counter <4:
                    password = False
  if password:
   print(f'Password: {passcode}')
  else:
   print(f'No!')

How can I remove the blank space the last time it prints, i.e the last time all flags are True? And I have to note that I still haven’t learned functions and lists.

Advertisement

Answer

Ok, this is a possible solution:

separator=''
for .......
    if flag_1 and flag_2 and flag_3 :
        print(f'{separator}{a}{b}{c}{d}',end='')
        separator=' '

You can also consider using functools.reduce

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement