Keeping Up With The Latest Version Of Python
The introduction of randrange in Python 3.8.5
In this story I provide an example of how Python is changing by discussing the introduction of the function randrange in Python 3.8.5.
A language such as English is constantly changing new words continue to be added and older words or expressions become less common.When I was in high school I would have been confused if somebody had told me to find the answer to a question by googling it.Thousands of new words have been added to our language since then.
A computer language is no different it is constantly changing. If you are looking at a Python module and you see.
print "hello world"You would be looking at code that was probably written quite some time ago. Python 3.0 was introduce in 2008. Programmers continued to write code in Python 2.x for many years. However code in Python 3.0 is not backward compatible with 2.x.
What that means is that if you are using Python 3.0 or later you can not use it to understand code written in Python 2.x
Since 2008 minor changes and updates to the language have been happening on a regular basis. If you are using Python 3.8. You can read code written with Python 3.0 and if you are using Python 3.0 it may work okay in Python 3.8 or in may require minor adjustments to run.
In Python 3.8.5 the function randrange in the random module was introduced.
Prior to the release of Python 3.8.5 if you wanted to generate a random number between two integers you would use randint. Randint continues to be used for that purpose.
import random()
print (random.randint (1,10)) would return a randomly generated number between 1 and 10.A very common usage of randint is to generate a number corresponding to the contents of a list. In python a list is indexed starting at 0. This means that if you wanted to generate a random number corresponding to a list of 10 items. You would use the following code.
import random()
print (random.randint (0,9))With the advent of Python 3.8.5 you could write instead
import random ()
print (random.randrange (10)If you want to create a function that takes a list of indeterminate length you could use the following code.
import randomdef rand_num (my_list):
print (random.randrange (len(my_list)))my_list = ["A", "B", "C",]
rand_num (my_list) # returns randomly generated number between 0 and 2To accomplish the same thing prior to the release of Python 3.8.5 you would have to use the following code
import randomdef rand_num (my_list):
print (random.randint (0,len(my_list)-1))my_list = ["A", "B", "C",]
rand_num (my_list)Jim McAulay🍁 says, Jim McAulay🍁 says, “ Politicians and diapers should be changed regularly for the same reason”
44__45
12__10
