i have written a simple number generation function but i want the output to line up horizontally('234567') and not vertically like it currently outputs.
import random
def get_num():
listz = [1,2,3,4,5]
for x in listz:
print(random.randrange(1,7))
get_num()
CodePudding user response:
You can use join
:
import random
def get_num():
print(''.join(str(random.randrange(1, 7)) for _ in range(5)))
get_num() # e.g., 16146
In your code, listz
does not play any roles (other than providing its length, 5). So I replaced it with for _ in range(5)
.
CodePudding user response:
It is just that you need to add a parameter in the print function as follows :
import random
def get_num():
listz = [1,2,3,4,5]
for x in listz:
y = random.randrange(1,7)
print(y,end="")
get_num()
The output was :
$python3 main.py
53234
CodePudding user response:
from random import randrange as rand
def get_randoms():
randoms = [rand(1, 7) for _ in range(5)]
randoms_str = [str(x) for x in randoms]
return ', '.join(randoms_str)
print(get_randoms())
CodePudding user response:
Could also print in one go with empty separator:
import random
def get_num():
print(*random.choices(range(1, 7), k=5), sep='')
get_num() # e.g., 16146