-2

I want to generate a random number of " * " smaller than 21 and larger than 0 in a row for 100 times, in python

I tried to write:

import random 
for x in range(100): 
    a = random.randint(1, 20) 
    for y in a: 
        print("*")

Can someone help me? I am beginner in programming

And
  • 1
  • Get into an interactive python session and see what happens when you write a line like `5 * '*'`. – pjs Feb 19 '21 at 15:28

3 Answers3

3

You can multiply a string like 'a'*5 = 'aaaaa'

import random 
for x in range(100): 
    #a = random.randint(1, 20)
    #print('*'*a)
    print('*'*random.randint(1, 20))
Epsi95
  • 8,832
  • 1
  • 16
  • 34
0

You can do it in a single line like this:

from random import randint
print(*( "*"*randint(1,20) for _ in range(100) ),sep="\n")

The print function can accept multiple value and separate them with a string supplied in its sep= parameter (here "\n" for a new line).

You can generate 100 strings with a comprehension (... for _ in range(100)) where each string is a random repetition of the "*" character (repeated by multiplying the single character by a random number).

This comprehension can be converted to individual parameters for the print function using unpacking *(...)

Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

Is this ok ? I just Added range in the second for loop and end = "\n" in first loop and end = "" in inner loop

import random 
for x in range(100): 
    a = random.randint(1, 20) 
    for y in range (a) : 
        print("*",end = "")
    print(end = "\n")
ITSME
  • 36
  • 2