我试图在Python 3中编写一个简单易用的Rock Paper Scissors版本,让中小学生能够轻松理解并希望重现。
除了基本游戏之外,我想为他们添加选项,使用%s输入player1和player2的名称,以便程序将其打印出来。我一直在我的o / p中出现这个错误:
Player 1 name: me
Player 2 name: you
%s, what do you choose? Rock (1), Paper (2), or Scissors(3)?
**Traceback (most recent call last):
File "C:/Users/xyz/PycharmProjects/rps/scorekeeping.py", line 11, in <module>
print("%s, what do you choose? Rock (1), Paper (2), or Scissors(3)?") % player1
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'**
我还试图包括每轮更新自己的得分计数器(player1 vs player2)。通常它会为赢/领/输而每轮重置为0。
请帮我看看代码出错的地方。谢谢!
player1 = input("Player 1 name: ")
player2 = input("Player 2 name: ")
while 1:
player1score = 0
player2score = 0
print("%s, what do you choose? Rock (1), Paper (2), or Scissors(3)?") % player1
choice1 = input("> ")
print("%s, what do you choose? Rock (1), Paper (2), or Scissors(3)?") % player2
choice2 = input("> ")
if choice1 == choice2 :
print("Its's a tie.")
elif choice1 - choice2 == 1 or choice2 - choice1 == 2 :
print("%s wins.") % player1
score1 = score1 + 1
else:
print("%s wins.") % player2
score2 = score2 + 1
print("%s: %d points. %s: %d points.") % (player1, score1, player2, score2)
答案 0 :(得分:2)
您正在尝试格式化打印功能的返回值。相反,要格式化您要打印的字符串,请尝试:
print("%s, what do you choose? Rock (1), Paper (2), or Scissors(3)?" % player1)
例如,表示第一个语句。格式应该出现在括号内。
要将输入值转换为整数,请尝试:
choice1 = int(input("> "))
目前,您在while循环开始时将分数重置为零。要阻止分数计数器重置,请输入
player1score = 0
player2score = 0
在while循环之前。