python - 石头、纸和剪刀的 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}')
解决方案
原因是 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}')
此外,还有另一个修改,计算机猜测应该是在人类猜测之后打印的。我也修好了。希望有帮助。
推荐阅读
- python - 尝试使用 Flask 中的渲染模板重定向到另一个 HTML 页面
- python - 检查输入时出错:预期输入为 3 维,但得到的数组形状为 (50, 1)
- python - 如何使用熊猫从csv中的2列中获取重复值列表
- .htaccess - 如何将此 htaccess 转换为 iis web.config?
- python - 自动从分组数据框中创建新数据框
- firebase - 函数执行耗时 60002 毫秒,完成状态为:可调用函数的“超时”
- java - 如何同时填写多个表
- sql - 如何根据其他列的值更新列
- html - 颜色被覆盖,但css中的文本装饰
- angular - 离子选择和离子日期时间的离子通过值计算