Reputation: 23
When I run this bit of code here, the resulting string is random, and doesn't adhere to the rules I laid out for it. Is there a better way to format this statement for it to run properly?
import random
for x in range(1):
print random.randint(1,8)
if random.randint(1,8) in {1, 2, 3}:
print("https://media.giphy.com/media/vgPDmpQsQsjug/giphy.gif")
elif random.randint(1,8) in {4, 5, 6}:
print("http://i0.kym-cdn.com/photos/images/original/000/676/205/57b.gif")
else:
print("Bye")
Upvotes: 1
Views: 32
Reputation: 4606
For something like this random
also has random.choice
which will allow to select on of your choices randomly not needing to generate an int
to compare. There is also random.choices
which accepts an argument that allows weights, as in your example [3, 3, 2] , [.375, .375, .25]
import random
options = [
"https://media.giphy.com/media/vgPDmpQsQsjug/giphy.gif",
"http://i0.kym-cdn.com/photos/images/original/000/676/205/57b.gif",
"Bye"
]
print(random.choice(options))
print(*random.choices(options, [.375, .375, .25]))
http://i0.kym-cdn.com/photos/images/original/000/676/205/57b.gif https://media.giphy.com/media/vgPDmpQsQsjug/giphy.gif
Upvotes: 0
Reputation: 164773
random.randint
calculates a new random number each time it is called. In addition, you don't need a for
loop to print a variable.
Instead, call random.randint
once, store the number in a variable, then reuse in subsequent logic. You may also wish to utilize range
, e.g. if x in range(1, 4)
represents clearer logic than if x in {1, 2, 3}
.
x = random.randint(1, 8)
if x in range(1, 4):
print("https://media.giphy.com/media/vgPDmpQsQsjug/giphy.gif")
elif x in range(4, 7):
print("http://i0.kym-cdn.com/photos/images/original/000/676/205/57b.gif")
else:
print("Bye")
Stylistically, you should adhere to the "4-character indent" rule. Although your code is not incorrect, it's not consistent with commonly used conventions.
Upvotes: 1