a = 1
b = 2
for i in range():
print(a)
#print(b)
I am trying to make a code. How can I make that randomly in one part of loop it will print b. For example one it will print "112111" and next time "211111".
a = 1
b = 2
for i in range():
print(a)
#print(b)
I am trying to make a code. How can I make that randomly in one part of loop it will print b. For example one it will print "112111" and next time "211111".
From the context of your question you want to print b only once.
import random
a = 1
b = 2
import random
b_index = random.randint(0,3)
res = [ a if i != b_index else b for i in range(4) ]
print(res)
Maybe not the most elegant solution but this should work. You assign at which index should B be printed at random and run the loop as below:
import random
A = 1
B = 2
LEN = 6
PRINT_B_INDEX = random.randint(0, LEN-1)
def main():
for i in range(LEN):
if i == PRINT_B_INDEX:
print(B)
else:
print(A)
if __name__ == "__main__":
main()
Use the random
module. One possible solution is random.shuffle()
, which will shuffle the elements of s
. This does not require a for
loop.
import random
s = ["1", "1", "1", "1", "2"]
random.shuffle(s)
print("".join(s))