this python code is randomly shows error , sometimes it runs and sometimes it doesn't shows any error and still I don't get any output [closed]

easy200707 注册会员
2023-01-24 21:36

Unlike indexing items, len()does not start with 0. If your list contains 4 items, randominteger can be 4. But, 4 can't be an index of an element since it's start from 0. Inorder to handle this problem, you can change variable number_of_members like this

number_of_members = len(names) - 1
cw90000711 注册会员
2023-01-24 21:36

The number of members is going to be 5, your code only covers up to 4, so one time out of five it's going to do nothing.

Besides, your code has two issues:

  1. your input has a space before commas, which will leave an extra space after most names. Furthermore, it requires that the separator be a space and comma, not just a comma.
  2. your code doesn't scale. If I input seven names, some of them will never have a chance to be picked. if I input too few of them, the code will have a chance to crash due to an IndexError.
# It's good practice to put all imports at the top
import random

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

# This will just require a comma to split names, and will get rid of any extra space before or after each name
names = [name.strip() for name in names_string.split(",")]

number_of_members = len(names)
randominteger = random.randint(0, number_of_members)
print(f"{names[randominteger]} is going to buy the meal today!")

Now it doesn't matter how many names you input, as long as there is at least one (you should cover that case and give feedback to the user).

cythere 注册会员
2023-01-24 21:36

You really shouldn't have that complex if/else construct because it limits you to the numbers of names that could be input. Try this:

import random
names_string = input("Give me everybody's names, separated by a comma.\n")
names = names_string.split(",")
r = random.randint(0, len(names))
print(f'{names[r].strip()} is going to buy the meal today')