首页 > 解决方案 > 石头、纸和剪刀的 Python 代码给出了错误的输出

问题描述

这段代码的本质是使用 Python 语言来描述石头剪刀布游戏,基本上带有for循环和if...else语句。我使用 PyScripter 作为引擎在 Python 3.7.2 上运行代码。def main()和是用于运行机器的if __name__ == '__main__'PyScripter 代码

import random

def main():
    pass

if __name__ == '__main__':
    main()


tie_sum, comp_sum, human_sum = 0, 0, 0
name = input('Enter your firstname here: ')

for i in range(5):
    tie_sum += tie_sum
    comp_sum += comp_sum
    human_sum += human_sum

    comp_guess = random.randint(1, 3)
    print(f'The computer guess option is {comp_guess}')
    human_guess = int(input('Enter 1 as (rock), 2 as (paper) or 3 as (scissors):'))

    if comp_guess == 1 and human_guess == 3:
        comp_sum += 1
    elif comp_guess == 1 and human_guess is 2:
        human_sum += 1
    elif comp_guess == 2 and human_guess == 3:
        human_sum += 1
    elif comp_guess == 3 and human_guess == 1:
        human_sum += 1
    elif comp_guess == 3 and human_guess == 2:
        comp_sum += 1
    elif comp_guess == 2 and human_guess == 1:
        comp_sum += 1
    else:
        tie_sum += 1

print(f'The number of tie in this game is {tie_sum}')

if comp_sum > human_sum:
    print('The winner of this game is the Computer.')
    print(f'The comp_sum is {comp_sum}')
elif comp_sum < human_sum:
    print(f'The winner of this game is {name}.')
    print(f'The human sum is {human_sum}')
else:
    print('This game ends in tie.')
    print(f'The tie sum is {tie_sum}')

标签: pythonoutputgame-physicspyscripter

解决方案


原因是 for 循环中的前三行。您在检查条件时增加了计算机、人类和领带的总和,当您再次循环迭代时,它会再次求和。这是修改后的代码:

import random

def main():
    pass

if __name__ == '__main__':
    main()


tie_sum, comp_sum, human_sum = 0, 0, 0
name = input('Enter your firstname here: ')

for i in range(5):
    

    comp_guess = random.randint(1, 3)
    
    human_guess = int(input('Enter 1 as (rock), 2 as (paper) or 3 as (scissors):'))
    print(f'The computer guess option is {comp_guess}')
    if comp_guess == 1 and human_guess == 3:
        comp_sum += 1
    elif comp_guess == 1 and human_guess == 2:
        human_sum += 1
    elif comp_guess == 2 and human_guess == 3:
        human_sum += 1
    elif comp_guess == 3 and human_guess == 1:
        human_sum += 1
    elif comp_guess == 3 and human_guess == 2:
        comp_sum += 1
    elif comp_guess == 2 and human_guess == 1:
        comp_sum += 1
    else:
        tie_sum += 1

print(f'The number of tie in this game is {tie_sum}')

if comp_sum > human_sum:
    print('The winner of this game is the Computer.')
    print(f'The comp_sum is {comp_sum}')
elif comp_sum < human_sum:
    print(f'The winner of this game is {name}.')
    print(f'The human sum is {human_sum}')
else:
    print('This game ends in tie.')
    print(f'The tie sum is {tie_sum}')

此外,还有另一个修改,计算机猜测应该是在人类猜测之后打印的。我也修好了。希望有帮助。


推荐阅读