[Tutor] Beginner - understanding randint arguments
Alan Gauld
alan.gauld at btinternet.com
Sat Feb 15 19:50:59 CET 2014
On 15/02/14 16:25, Marc Eymard wrote:
> Here is what happens in my script:
>
> >>> import random
> >>> low_range = -1
> >>> high_range = 101
> >>> random.randint(low_range + 1, high_range - 1)
> 56
> >>> low_range
> -1
> >>> high_range
> 101*
>
> I was rather expecting:
>
> >>> low_range
> 0
> >>> high_range
> 100
Really? Why?
You never change low_range or high_range so why would
their values change?
The help() for randint says:
randint(self, a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
So the function doesn't change the values either it
just returns a random number between them.
> Can somebody explain why both low_range and high_range are still
> returning their initial values ?
Because you didn't change them.
When you called randint you passed in two expressions:
low_range+1 and high_range-1
which Python evaluated as 0 and 100.
But that did not change your variable values in any way, it just created
new values that were passed into randint() as 'a' and 'b' respectively.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list