Random text in Python

How to make random text in Python? So that it outputs only 1 variable out of two? For example, I take two variables with this value:

import random

role1 = "Мирный житель"
role2 = "Мафия"
role = randon.randomint(role1, role2)

print("Вы - " + role)

input("")

And I need ONLY ONE VARIABLE to be output when the text is output. And from each time-different, then role1, then role2, then again role1.

I hope you explained it clearly. I am new to Python and I ask you to answer in more detail.

Author: jfs, 2016-01-05

2 answers

Random element from the sequence

random.choice(seq) uses a cryptographically insecure PRNG in Python, so if you use it in a context where it is not desirable that you can guess the result of consecutive calls, for example, when generating passwords, then you should use a CSPRNG such as random.SystemRandom(), which uses os.urandom(), which in turn uses the features provided by the OS:

#!/usr/bin/env python3
import random

random_item = random.SystemRandom().choice(["Мирный житель", "Мафия"])

See also: PEP 0506 -- Adding A Secrets Module To The Standard Library.

Each time, a different (non-random) string

So that you can print different values from a given sequence each time you run the program, you can create an infinite iterator using itertools.cycle(), which circularly returns the elements from this sequence. To save the iterator state between program runs, so that the next value is returned each time, you can use pickle for serializations:

#!/usr/bin/env python3
"""Print a different string on each run in a loop."""
import itertools
import pathlib
import pickle


# load items
path = pathlib.Path('it.pickle')
try:
    data = path.read_bytes()  # XXX no file locking, ignore concurrent issues
except FileNotFoundError:  # 1st run
    # create an infinite iterator that repeats the values
    it = itertools.cycle(iter({"Мирный житель", "Мафия"}))
else:
    # NOTE: it is insecure if you can't trust it.pickle's content
    it = pickle.loads(data)

# print next item
print(next(it))

# save items
path.write_bytes(pickle.dumps(it))  # XXX ignore data corruption issues

To avoid (unlikely) file corruption (for example, if the power suddenly goes out while the file is being written), you can use a temporary file. See Threadsafe and fault-tolerant file writes.

 5
Author: jfs, 2017-05-23 12:39:15

It's not very clear from the question what you want to do. "Different every time" and "random" (i.e. random) are completely different things. So let's try to make two options.

Option 1. Random string.

import random

strings = ['String 1', 'String 2']
print(random.choice(strings))

Option 2. Each time a different line.

def next_string():
    strings = ('String 1', 'String 2')
    next_string.i = (next_string.i + 1) % len(strings)
    return strings[next_string.i]
next_string.i = -1

print(" ".join(next_string() for r in range(10)))

But this is how you can implement the case when, at each subsequent call, the program outputs the following line:

def next_string():
    strings = ('String 1', 'String 2')
    if next_string.i < 0:
        try:
            with open("i.idx", 'r') as file:
                next_string.i = int(file.read())
        except Exception:
            pass
    next_string.i = (next_string.i + 1) % len(strings)
    with open("i.idx", 'w') as file:
        file.write(str(next_string.i))
    return strings[next_string.i]
next_string.i = -1

print(next_string())
 3
Author: , 2016-01-06 08:13:31