使用列表实现简单算法的问题

时间:2017-10-11 09:55:03

标签: python

所以我得到了这段代码:

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")

好的,用户赢了,因为获胜的算法是:你赢了(你的输入 n )数字 n + 1 n + 3 。因此,如果用户输入为1(mylist [0]),他将赢得2(mylist [user + 1])和4(mylist [user + 3])。但问题是当用户输入数字5时我会得到。

IndexError: list index out of range

有没有办法传递它?

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")

提前谢谢你,我真的被卡住了。

0 个答案:

没有答案