Ahmed Obied
Ahmed Obied

Reputation: 13

How to print a random element from a list on to excel file rows on openpyxl

I'm quite new to programming. I have been trying to print a random element from the following list:

senior_duties = ["SOPs", "EQA review", "Doc review", "NC review", "Trend analysis"]

I have tried this

import random

rand_senior_duties = print(random.choice(senior_duties))

Then I assigned rand_senior_duties to the cells like this:

sheet["D5"] = rand_senior_duties

However it only prints to the console and not the actual sheet.

Any help will be appreciated. Thanks.

Upvotes: 1

Views: 180

Answers (1)

Zach Young
Zach Young

Reputation: 11223

print() prints to the console (stdout, "standard out") as you noted, and returns the value None.

Consider this:

import random

senior_duties = ["SOPs", "EQA review", "Doc review", "NC review", "Trend analysis"]

rand_senior_duties = print(random.choice(senior_duties))
print(rand_senior_duties)

# sheet["D5"] = rand_senior_duties

What get's printed?

EQA review
None

What's the value of rand_senior_duties? It's just None, because that's what print() returns.

Let's get rid of the first print() statement, and make sure rand_senior_duties is getting a random value assigned to it:

...

rand_senior_duties = random.choice(senior_duties)
print(rand_senior_duties)

# sheet["D5"] = rand_senior_duties

and now I get:

Doc review

Now, you can delete the final print() statement, and just assign rand_senior_duties to sheet["D5"]. If you still want the print() to help you understand your program, just have it on a line by itself so that it doesn't interfere with any other value assignments:

...

rand_senior_duties = random.choice(senior_duties)
print(rand_senior_duties)

sheet["D5"] = rand_senior_duties

Upvotes: 1

Related Questions