For loop that takes turns between printing one thing or the other python

Question:

Not sure how else to word the title, but this is what I need:

Print either the number zero, the number one or a phrase in no consecutive order twenty times. This is what I have:

    n = 0
    x = “hello”
    for i in range(20):
        print(n, end= ‘’) or print(n+1, end= ‘’) or print(x)

The only problem is that it prints them out in order so that it is always 01hello01hello01hello and so on. I need it to be randomized so that it could print something like 000hello1hello101 or just any random variation of the three variables.

Let me know how 🙂

Asked By: Iplaysoccer

||

Answers:

Your question is hard to understand, but I think this will help.
If you want to randomize, then try importing random

import random
my_strings=["foo", "bar", "baz"]

for i in range(10):
    print(random.choose(my_strings))
Answered By: picobit

Use random.choice:

import random
choices = (0, 1, "hello")
print(''.join(str(random.choice(choices)) for _ in range(20)))
Answered By: bitflip

You could do something like:

import random

n = 0
x = “hello”
for _ in range(20):
    if random.randint(0, 1):
        print(n, end= ‘’)
    if random.randint(0, 1):
        print(n+1, end= ‘’)
    if random.randint(0, 1):
        print(x)
Answered By: Andrew Ryan
import random
choices = [1, 0, "hello"]
for i in range(20):
    print(random.choice(choices))
Answered By: Jamie.Sgro
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.