swagdaddy
swagdaddy

Reputation: 3

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.

Upvotes: 0

Views: 759

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55489

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.

Upvotes: 1

user1438038
user1438038

Reputation: 6079

Your list only contains one element. Try this:

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

Upvotes: 0

Related Questions