user3353706
user3353706

Reputation: 11

how to generate a list based on index value

i am trying to generate a list consisting of 0's based off of user prompt. if they enter a one then the one index will be replaced with a one, if they enter a two the two index will be replaced with a one, etc. i am able to generate a random list of one's and zero's but i am having trouble with the input.
here is what i have so far:

import random

def askTheUser():
  number = input("Do you want to roll again? Pick a number or numbers thru 0 and 5:")
  myList = []
  aList = [1,0]
  for i in range(5):
    myList.append(random.choice(aList))
    if number == 1:
        return myList[1] = 0
    if number == 2:
        return myList[2] = 0

return myList




print(askTheUser())

Upvotes: 1

Views: 87

Answers (2)

m.wasowski
m.wasowski

Reputation: 6387

I am not sure what exactly your program should do. I tried to follow description more than your code (expected input and output would be welcome). Here is my piece:

from __future__ import print_function # make it work also in python 2.x
import random

def askTheUser():
    # don't use magic numbers, use 'constant-like' variables
    MAX = 5

    # try to avoid too long lines if possible
    msg = "Do you want to roll again? " +\
        "Pick a number or numbers thru 0 and {}: ".format(MAX)

    # you should use raw_input() for asking user, input() is very unsafe
    number = raw_input(msg)

    # initialize with random [0,1]
    myList = [random.randint(0,1) for i in range(MAX)]

    try:
        # you need to convert string to int
        i = int(number, 10)

        # negative indexes can be valid ;o)
        # let's not allow for that in this case, throwing error
        if i < 0:
            raise IndexError
        myList[i] = 1

    # you may expect ValueError if string was not valid integer
    # or IndexError if it was beyond range (0, MAX)
    except (IndexError, ValueError):
        print ("That was wrong value:", number) # if you want, message user
        pass
    finally:
        return myList

if __name__ == '__main__':
    print(askTheUser())

If you want to accept multiple values at once, you should use split() on input and process them in loop. Good luck.

Upvotes: 1

Mohamed Abd El Raouf
Mohamed Abd El Raouf

Reputation: 928

I think you are replacing by 0 not 1, also input is taking string not int so try to cast it and list index is 0 based so the right code should be:

import random

def askTheUser():
  number = input("Do you want to roll again? Pick a number or numbers thru 0 and 4:")
  myList = []
  aList = [1,0]
  for i in range(5):
    myList.append(random.choice(aList))
  myList[int(number)] = 1

  return myList
print(askTheUser())

Upvotes: 1

Related Questions