Ashutosh Singh
Ashutosh Singh

Reputation: 51

Getting error while using the random choices function

I'm trying to open random links using

webbrowser.open(random.choices("link1","link2","link3")

but it's showing error Check it out and help me resolve this issue.

My code:

webbrowser.open(random.choices("https://www.youtube.com/watch?v=YGf8JJZM_Yg", "https://www.youtube.com/watch?v=upsF9NULamA"))

Error I am facing:

    total = cum_weights[-1] + 0.0   # convert to float
TypeError: can only concatenate str (not "float") to str

Upvotes: 2

Views: 1259

Answers (2)

Divyesh Peshavaria
Divyesh Peshavaria

Reputation: 599

The arguments to random.choices() must be an iterable like list, tuple, etc like this:

random.choices(
("https://www.youtube.com/watch?v=YGf8JJZM_Yg", "https://www.youtube.com/watch?v=upsF9NULamA")
)

Notice the extra pair of parentheses. You can pass as many arguments you want but they should be given like this:

random.choices((arg1, arg2, arg3, ...))

instead of:

random.choices(arg1, arg2, arg3, ...)

Both of the below options will work:

Use random.choice() over random.choices() to select only 1 option out of multiple options.

1.

webbrowser.open(random.choice(("https://www.youtube.com/watch?v=YGf8JJZM_Yg", "https://www.youtube.com/watch?v=upsF9NULamA")))
webbrowser.open(random.choice(["https://www.youtube.com/watch?v=YGf8JJZM_Yg", "https://www.youtube.com/watch?v=upsF9NULamA"]))

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71570

Instead of:

total = cum_weights[-1] + 0.0

Try:

total = float(cum_weights[-1])

Edit:

For your other error with random.choices, try this instead:

webbrowser.open(random.choice(["https://www.youtube.com/watch?v=YGf8JJZM_Yg", "https://www.youtube.com/watch?v=upsF9NULamA"]))

random.choices take in a single argument with a parameter of a list, it isn't a *args expression in the implementation.

Upvotes: 2

Related Questions