Home > database >  using a list inside a function
using a list inside a function

Time:08-24

Here is my code for a "check roulette" game that decides who in the party will pay the bill at a restaurant

names_string = input("Give me everybody's names, separated by a comma. ")

names = names_string.split(", ")



number = len(names)

roulette_number = random.randint(0,number - 1)

print((names[roulette_number]),"is going to buy the meal today!")

my question is, why did i have to add the -1 in the randint function to select the roulette number? why wouldn't it just be roulette_number = random.randint(0,number)?

CodePudding user response:

You did -1 because number is the length of the list names suppose you names are

["Sam", "Jack"]

then the number variable will store 2, but the available index are only 0 and 1, this is beacuse list follow 0-based indexing.

So by doing -1 we ensure that our random integer is always in the list index range.

CodePudding user response:

This is because random.randint(a, b) returns a random integer N such that a <= N <= b. See the documentation here.

To see why this is a problem, assume (as in Harsh's example) that you have two names: names = ["Sam", "Jack"].

You'll call random.randint(0, 2), which will return one of 0, 1, or 2. But there are only two names in your array, with indexes 0 and 1. If roulette_number is 2, you'll get an exception when accessing the non-existent array member.

You have several options:

  • If you're using Python 3.x, you can use random.randrange() instead, which excludes the final value from the results. See the documentation here. That is: random.randrange(0, 2) will return 0 or 1.
  • You can (as you did) subtract one from the count, giving you (in the 2-item example) random.randint(0, 1), which will return 0 or 1.
  • (Generally, don't do this one) You can call random.randint(1, count), which will (in the same 2-item example) return 1 or 2. Then you subtract the result from the array indexer: names[roulette - 1], giving you index 0 or index 1. I mention this option for completeness. It's not idiomatic (Python devs are used to zero-based thinking), and you'll likely confuse anyone reading your code.
  • Related