我需要计算'player_number'和'comp_number'之间的差异,但它说:
TypeError:Sub:'NoneType'和'int'
不支持的操作数类型
我理解这个错误。我的代码生成的player_number是None类型,这就是我无法减去它的原因。
我该如何处理这个问题?有什么想法吗?
这是我的代码:
def name_to_number(name):
if name == "rock":
name = 0
elif name == "paper":
name = 1
elif name == "Spock":
name = 2
elif name == "lizard":
name = 3
elif name == "scissors":
name = 4
else:
print 'Name is not listed:',name
def number_to_name(number):
if number == 0:
print "rock"
elif number == 1:
print "Spock"
elif number == 2:
print "paper"
elif number == 3:
print "lizard"
elif number == 4:
print "scissors"
else:
print 'Your number is not valid:',number
def rpsls(player_choice):
if player_choice == "rock":
print 'Player choses', player_choice
player_number = name_to_number(player_choice)
elif player_choice == "Spock":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
elif player_choice == "paper":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
elif player_choice == "lizard":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
elif player_choice == "scissors":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
else:
print "Name not in list",player_choice
import random
comp_number = random.randrange(0,4)
if comp_number == 0:
print "Computer choses",number_to_name(0)
elif comp_number == 1:
print "Computer choses",number_to_name(1)
elif comp_number == 2:
print "Computer choses",number_to_name(2)
elif comp_number == 3:
print "Computer choses",number_to_name(3)
elif comp_number == 4:
print "Computer choses",number_to_name(4)
diffrence = player_number - comp_number
if diffrence % 5 == 1 or 2:
print 'Player wins!'
elif (diffrence % 5) == 3 or 4:
print 'Computer wins!'
else:
print 'Game tie'
rpsls("rock")
答案 0 :(得分:3)
你有这个分配
player_number = name_to_number(player_choice)
但if/elif/else
中的name_to_number
个案例都没有使用return
关键字。要return
来自此函数的值,您可以执行
def name_to_number(name):
if name == "rock":
return 0
elif name == "paper":
return 1
elif name == "Spock":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
else:
print 'Name is not listed:',name
number_to_name
功能
答案 1 :(得分:1)
未经测试的修复。 'return'声明丢失了。对字符串和int使用相同的变量名称不是很好的编程风格。
def name_to_number(name):
number = -1
if name == "rock":
number = 0
elif name == "paper":
number = 1
elif name == "Spock":
number = 2
elif name == "lizard":
number = 3
elif name == "scissors":
number = 4
else:
print 'Name is not listed:',name
return number #This line was missing