Home > Blockchain >  how can i remove the last comma using python
how can i remove the last comma using python

Time:10-16

i have tried using this code but the comma after -63 reamins. The problem was Write the python programs, which prints the following sequences of values in loops:18, -27, 36, -45, 54, -63

count = 18
while count<= 63:
   if count==-63:
      print(count)
   elif count%2 == 0:
    print(count, end=',')
   elif count%2 !=0:
     print(-1*count, end=",") 
   count =9 

CodePudding user response:

The problem was that your first if condition compares to -63 which will not occur on the count variable (it only occurs on the print statement), to quick fix it, just change count == -63 to count == 63:

count = 18
while count <= 63:
   if count == 63:
       print(-1*count)
   elif count%2 == 0:
       print(count, end=',')
   elif count%2 !=0:
       print(-1*count, end=",") 
   count =9 

outputs: 18,-27,36,-45,54,-63

CodePudding user response:

Try:

count = 18
output = ''
while count<= 63:
   if count==-63:
      output  = (count)
   elif count%2 == 0:
    output  = (str(count)   ',')
   elif count%2 !=0:
     output  = (str(-1*count)   ',')
   count =9
print(output[:-1])

CodePudding user response:

Using List Comprehension:

print(*(i if i%2==0 else-i for i in range(18,63 1,9) ),sep=',')

Output:

18,-27,36,-45,54,-63
  • Related