0

I am trying to figure out how to have a user input the index number of an object in a list. My ultimate goal is to show a list of the spells in your spell book sorted by index number. I then want the user to be able to input the index number to choose the spell and perform a function with it. Here is a simple example:

(The spells are objects)

spells = [spell1(), spell2()]
print(spells.index(Spell),Spell.name)

Should show:

0 spell1

1 spell2

x = input('Input number of spell')
print(spells[int(x)].description)

So, by inputting the index number of the object in the list I retrieved its description. I have gotten the function itself to work. However, I am having difficulty setting up rules so that it does not accept any input other than the available indexes in the list. In this example, only 0 and 1 should be available inputs. I also wanted the option of 'p' to go back to the previous screen.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Oomptz
  • 13
  • 3
  • 2
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – jonrsharpe Jul 03 '17 at 20:43
  • `assert 0 <= int(x) <= 1, "Invalid spell!"` – cs95 Jul 03 '17 at 20:56

2 Answers2

0

If you want mixed type input, then you need to need to treat everything as string and process it separately. A simple trick is that you can check for the alphabets first and the try casting anything else to int. This isn't completely break proof, since the user can enter other alphabets. The most efficient way is probably to use try catch statements, while casting to int.

Partha Das
  • 170
  • 2
  • 11
0

So you've got two conditions that need to pass: x must a valid number and it must be within the bounds of your spell list.

You can wrap this in whatever control flow suits your application. For example, you could re-prompt the user until they give a valid input:

def validate_spell_index(spell_list, i):
    return i.isdigit() and int(i) in range(len(spell_list))

x = input('Spell index> ')
while not validate_spell_index(spells, x):
    print('Please give a number between 0 and {}.'.format(len(spells) - 1))
    x = input('Spell index> ')

print(spells[int(x)].description)

demo (I aplogize for any mispelled spells)

wbadart
  • 2,583
  • 1
  • 13
  • 27