简体   繁体   中英

Python: generate a different random choice when importing from module (different python file) - Keep getting same output

I have a code for choosing different comments from a list, which is stored in a separate python file, like comments.py:

import random

theitems = ['a','b','c','d','e','f']

commentpick = random.choice(theitems)

I have the following code in the main file:

from comments import commentpick

for a in commentboxes:
   a.send_keys(commentpick)
        

However the same comments will be returned for all the 'a' in commentboxes: [eg. 5 inputs, 'a', 'a', 'a', 'a', 'a']

It only works if i import random and do it on the main file, like this:

for a in commentboxes:
       a.send_keys(random.choice(theitems))

then the result will be varied, [eg. 'a', 'c', 'e', 'd', 'f']

Is there any way that I will be able to write a.send_keys(commentpick) directly without doing the random.choice in the main file but still get different results each time? Thanks.

you should put

commentpick = random.choice(theitems)

in function, by that you can call random function each time to call the function you build

for example: comments.py

def commentpick():
    theitems = ['a','b','c','d','e','f']
    commentpick = random.choice(theitems)
    return commentpick

and in your main file:

from comments import commentpick

for a in commentboxes:
    a.send_keys(commentpick())

your problem is you just called once and save the value and used many times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM