Python Forum
Randomly generate an even number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Randomly generate an even number
#11
for x in range(14):
         return random.randrange(10,22,2)
It works. by the way, is there any difference between random.randrange and random.choice?
Reply
#12
i don't think the loop is needed:
import random
def stochasticNumber():
    return random.randrange(10,22,2)

or maybe:
import random
def stochasticNumber(*args)
    return random.randrange(*args)
[note: the use of *args may be beyond the class assignment limitations]

so, what is the value of this function beyond inserting it into existing code? it looks like module "random" has plenty of capability. if i needed a non-uniform distribution, i would look at documentation to see what it has. for example,bell-curve distributions are easy enough to do if they are not already in there.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#13
You should be able to do this right -

import random

def stochasticNumber():
    while True:
        rn = random.randint(9, 21)
        if rn % 2 == 0:
            return rn
            break
Reply
#14
Sheepp, while True: is a nice solution, looks better than for loop.
Reply
#15
Thx, I take pride in my programming, no one at school really cares. I mean why would they, I'm only in 7th grade, all people care about is how good you are at Fortnite
Reply
#16
Also note that there is a 0.00206% chance that you don't get an even number in 14 tries, and end up returning None.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#17
I don't quite understand that.
But it's definitely better to use the range that was given in problem description.
Reply
#18
there is no need for a loop or any of the code in the body of that loop to get an even random number in a desired range, uniformly distributed. random.randrange() will do all you need. why do anything else?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  randomly title of game development Kia 1 300 Mar-30-2025, 01:53 PM
Last Post: buran
  Using randomly generated lists souprqtpie 3 3,289 Apr-19-2019, 07:46 PM
Last Post: souprqtpie

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020