Home > OS >  With a while loop, how it is possible to output a number list with an ending dot for each number?
With a while loop, how it is possible to output a number list with an ending dot for each number?

Time:07-10

based on that code, I wish to output my result by ending each digit with a dot.

input:

x = 0
while x<=5:
  print(x)
  x  = 1

expected output:

1.
2.
3.
4.
5.

CodePudding user response:

Make sure you start at x = 1 and add a full stop to the string. Concatenating more letters or symbols to variables can be done with f-strings:

# Start at 1
x = 1
while x <= 5:
    print(f'{x}.')
    x  = 1

Alternatively, you could turn this into a one liner function:

>>> def ordered(start, stop):
...     return '\n'.join(f'{x}.' for x in range(start, stop 1))
... 
>>> print(ordered(1, 5))
1.
2.
3.
4.
5.

CodePudding user response:

Type casting can be used

x = 0
while x<=5:
    print(str(x) ".")
    x  = 1

CodePudding user response:

Just so you know, you can use the ` key to embed code :)

I believe what you want is:

x = 0
while x <= 5:
  print(str(x)   '.')
  x  = 1

Let's break down the print statement:

We add the dot to x. We can't just add a string to an integer, so we first have to use the str() function to turn the numeric value of x into a string value: str(x) '.'

  • Related