-1

I want to randomize the answers in my for loop. My current code only prints: AAA,BBB,CCC.

while True:
    for i in range(65,91):
        answer = chr(i) + chr(i) + chr(i)
        print(answer)

How can I randomly return every single possible combination like AXY,BMK, etc.

Is this possible with the random module or do I need to use something else?

2
  • Hey there! Put answer = chr(i) + chr(i + 1) + chr(i +2). Hope I helped and happy coding! Commented Sep 17, 2021 at 7:53
  • Your answer is working however because of the for loop it only returns items 26 times because of the 65,91 range. How can i solve that? Commented Sep 17, 2021 at 7:56

1 Answer 1

0

Try this:

import string
import random
char_big = string.ascii_uppercase

while True:
    print(''.join(random.choice(char_big) for _ in range(3)))

By thanks of @JiříBaum, if this is important for you to prevent from attack you can use SystemRandom from secrets like below:

import string
import secrets
char_big = string.ascii_uppercase

while True:
    print(''.join(secrets.choice(char_big) for _ in range(3)))

Or:

import string
import secrets
char_big = string.ascii_uppercase

while True:
    print(
        ''.join(char_big[secrets.SystemRandom().randrange(0, 26)] \
                for _ in range(3)
               )
    )
Sign up to request clarification or add additional context in comments.

4 Comments

Remember to use secrets rather than random if there may be an adversary involved? The function name is the same...
@JiříBaum thanks a lot, you are so nice, today I Learn from you. edited answer
You can use secrets.choice(); then it's the same as the code using random
@JiříBaum thanks a lot again, edited answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.