鱼C论坛

 找回密码
 立即注册
查看: 1564|回复: 1

[已解决]日常求助大佬,解释一下index()函数此处的意思。

[复制链接]
发表于 2020-2-16 03:37:20 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
代码如下,问题在最后:

  1. #和电脑玩猜拳游戏
  2. import random

  3. while True:
  4. # 出拳
  5.     punches = ['石头','剪刀','布']
  6.     computer_choice = random.choice(punches)
  7.     user_choice = ''
  8.     user_choice = input('请出拳:(石头、剪刀、布)')  # 请用户输入选择
  9.     while user_choice not in punches:  # 当用户输入错误,提示错误,重新输入
  10.         print('输入有误,请重新出拳')
  11.         user_choice = input()

  12. # 亮拳
  13.     print('————战斗过程————')
  14.     print('电脑出了:%s' % computer_choice)
  15.     print('你出了:%s' % user_choice)

  16. # 胜负
  17.     print('—————结果—————')
  18.     if user_choice == computer_choice:  # 使用if进行条件判断,直接相等就得到平局的结果
  19.         print('平局!')

  20.     elif user_choice == punches[punches.index(computer_choice)-1]:
  21.         print('你赢了!');
  22.     else:
  23.         print('你输了!')
  24.     xh = input('n退出,其余键继续')
  25.     if xh == "n":
  26.         print('程序结束')
  27.         break
复制代码

我想问下 elif user_choice == punches[punches.index(computer_choice)-1]:这里为什么不能把最后的-1改为+1?
+1的情况下,电脑随机到布就会报错?
-1的情况下,电脑随机到石头,却没问题?
求大神指教,先谢过
最佳答案
2020-2-16 07:30:12
列表中下标 -1 表示最后一个元素
使用 +1 会使列表下标越界,产生异常
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-2-16 07:30:12 | 显示全部楼层    本楼为最佳答案   
列表中下标 -1 表示最后一个元素
使用 +1 会使列表下标越界,产生异常
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 14:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表