Having fun with my friend @veronezenaay, follow her on instagram and let's play some card game hahahha

Pick a number. Any number.

We demand rigidly defined areas of doubt and uncertainty
Douglas Adams. The Hitchhiker’s Guide to the Galaxy

Sometimes you need to mix things up with a random number. Anybody who’s written a basic card game has probably had cause to reach for a random number generator. Other typical uses include picking random dictionary words to create nicknames, creating variations in simulations (eg of terrain or weather), influencing the outcomes of user and sprite actions in games and so on. As you’d expect, both PHP and Python are there to support you in your quest for a little organised chaos.

PHP Code Example

In PHP, rand() requires lower and a upper integers and will return a number in that range (inclusive of the given numbers themselves)

$num = rand(1,100);
print "{$num}\n";

Python Code Example:

The Python equivalent is very similar (though note the need to import random before you can use the module):

import random

num = random.randint(1,100);
print(num)

Discussion

So this is pretty much a one for one migration from PHP. There’s the slight inconvenience of importing the random module but as compensation we win other tools for generating random stuff including random.choice() for picking a random element from a sequence…

# pick a fruit, Python
print(random.choice(["apples", "oranges", "pears"]))

and random.randrange() for choosing a number within a numeric range.

# a random number in the range 0-100 in 5 integer steps
num = random.randrange(0,100, 5); 
print(num)

Note None of these functions (in either language) should be used for cryptographic purposes. They should be seen as ‘good enough’ randomisers for day to day tasks. Pick a card.

See also

Further Reading:


Stay up to date with the Python for PHP Programmers project


Yes! Please sign me up to this newsletter


Photo by Abstral Official on Unsplash