简体   繁体   中英

Getting “IndexError: list index out of range”

I'm wondering why this error comes up, IndexError: list index out of range. If the full program is required then I will upload, but the error is in this part of the code.

import random
Sign = ["+-*"]
num = int(random.random()*2)
operator = (Sign[num])
digit = int(random*10)

This is meant to output a random sign of the array.

random.random() returns a floating point number which is greater than 0 and less than 1, so int(random.random()*2) will only ever result in 0 or 1. The random module has a specific function to return random integers in a specified range, which is simpler to use than "rolling your own" random integer algorithm (and with results that are generally more uniform).

But random also has a function to return a random member of a sequence (eg a str, tuple or list), so it's appropriate to use that to select your random operator. Eg,

#! /usr/bin/env python

import random

sign = "+-*"

for i in range(10):
    op = random.choice(sign)
    digit = random.randint(0, 9)
    print op, digit

typical output

+ 7
* 9
+ 0
* 6
* 8
* 5
+ 0
- 1
- 6
- 3

I changed the variable name to op in that code because operator is the name of a standard module. It's not an error to use that name for your own variables, but it will definitely cause problems if you did want to import that module. And it's also confusing to people reading your code.

Your list only contains one element. Try this:

Sign = ["+", "-", "*"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM