0

so I got this code:

from random import randint

mylist = [1, 2, 3, 4 , 5]
enemy = 2
# it's going to be randint(1, 5)
print(enemy)
user = int(input("Enter a number between 1 and 5: ")) # user input 1
user = n-1

if enemy == mylist[user+1] or enemy == mylist[user+3]:
    print("You win!")
elif enemy == mylist[user]:
    print ("It's a draw")
else:
    print ("You lose")

Okay, yay user won since the algorithm for wining is: you win (your input n) against numbers n+1 and n+3. So if user input is 1 (mylist[0]) he will win against 2 (mylist[user+1]) and 4 (mylist[user+3]). But the issue is when user will input number 5 I will get.

IndexError: list index out of range

Is there a way to pass it?

user = int(input("Enter a number between 1 and 5: ")) # user input 5
user = n-1 # 4

if enemy == mylist[user+1] or enemy == mylist[user+3]: 
"""what you can do so that the mylist[4+1] won't equal index mylist[5] which 
is out of list range but instead it will go back to mylist[0]?""" 

    print("You win!")
elif enemy == mylist[user]:
    print ("It's a draw")
else:
    print ("You loose")

Thank you in advance, I'm really stuck.

Derek Johnson
  • 717
  • 1
  • 5
  • 9
  • 4
    you could use `mod`. like `mylist[(user+1) % 5]`. Note thought that this approach will also handle inputs like `23` which will become `3`. This might or **might not** be desired. – Ma0 Oct 11 '17 at 09:57
  • 1
    Defining `n` somewhere might also help tracking the problem – GPhilo Oct 11 '17 at 09:59
  • @Ev.Kounis thank you for the reply. Modulo will handle number 5. 6(user input +1)%5=1 8(user input +3)%5=3 And that is correct. But for let's say 3 it will go: 4(user input +1)%3 = 1 that is correct and 6(user input +3)%3 = 0. It's false sicne the winning numbers for 3 are 1 and 4. – Derek Johnson Oct 11 '17 at 10:19

0 Answers0