Here is part of my code:
i = int(input("length of speech: " ))
b = 0
while b < i:
print(random.choice(uppercase) " ", end = "")
b = 1
CodePudding user response:
You definitely have the right idea if you want to do this with a loop.
uppercase = [...] # your list goes here
while len(uppercase) > 0:
i = random.randint(0, len(uppercase)) # Pick a random index in the list
print(uppercase[i]) # Print out the corresponding element
del uppercase[i] # Delete the element from the list and start again
CodePudding user response:
You should be able to use random.sample
, which samples without replacement:
See: https://docs.python.org/3/library/random.html#random.sample
Since random.sample
takes the number of draws as an input, you would draw all i
letters at the same time, i.e. you don't use the loop anymore. This also makes things more "pythonic", as some call it.
Putting everything together, your example would look like this:
import random
import string
uppercase = string.ascii_uppercase
i = int(input("length of speech: " ))
print(" ".join(random.sample(uppercase, i)))
Note that this throws an error if i
is larger than the length of uppercase, as it should.