Python剪刀石头布程序输入选择无响应问题求助
剪刀石头布程序问题排查与修复
问题根源
- 拼写错误:代码中多处把
scissor写成了sicssor,当电脑随机选中scissor时,对应的判断条件无法触发,程序没有任何输出,导致你误以为输入后没响应。 - 逻辑异常:玩家获胜时直接执行
break终止循环,违背了最多玩5次的设定。 - 其他小错误:
vaid应为valid,loose应为lose(loose是“松散的”,lose才是“输掉”的正确拼写)。
修正后的代码
import random print('Hey Lets play rock paper scissor ') number_of_tries = 0 options = ['rock', 'paper', 'scissor'] # 提前定义列表,避免循环内重复创建 while number_of_tries < 5: hand = random.choice(options) dash = str(input("whats your pick ")).lower() number_of_tries += 1 if dash not in options: print('not a valid option') elif dash == "rock": if hand == 'paper': print(f'you lost, the computer selected {hand}') elif hand == dash: print(f'its a tie the computer selected {hand}') elif hand == "scissor": print(f'you win the computer selected {hand}') elif dash == "scissor": if hand == "rock": print(f'you lose the computer selected {hand}') elif hand == "scissor": print(f'its a tie the computer selected {hand}') elif hand == "paper": print(f'you win the computer selected {hand}') elif dash == "paper": if hand == "scissor": print(f'you lost the computer selected {hand}') elif hand == "paper": print(f'its a tie the computer selected {hand}') elif hand == "rock": print(f'you win the computer selected {hand}') print("the end")
额外优化说明
- 将选项列表移到循环外定义,避免每次循环重复创建相同列表,提升代码效率。
- 把独立的
if判断改成elif,避免不必要的条件校验,逻辑更严谨。
内容的提问来源于stack exchange,提问作者Kev J
相关产品推荐
相关产品推荐

