python - TypeError: unsupported operand type(s) for Sub: 'str' and 'int'
ringa_lee
ringa_lee 2017-04-17 15:17:30
0
1
685

import random
def number_to_name(number):
if number==0:
return "rock"
elif number==1:
return "Spock"
elif number==2:
return "paper"
elif number==3:
return "lizard"
elif number==4:
return "scissor"
else:
return "wrong number you have entered"
def name_to_number(name):
if name=="rock":
return 0
elif name=="Spock":
return 1
elif name=="paper":
return 2
elif name=="lizard":
return 3
elif name=="scissor":
return 4
else:
return "wrong name you have entered"

define the number to name function

define compare function

def rpsls(player_choice):

print "the player choice is "+player_choice

player_number=name_to_number(player_choice)

computer_number=random.randrange(0,5)

computer_choice=number_to_name(computer_number)

print "the computer choice is "+computer_choice

diff = (player_number - computer_number) % 5

if diff==1 or diff==2:
    print "player wins"
elif diff==3 or diff==4:
    print "computer wins"
else:
    print "ties"    
print ""

rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
总是提示diff = (player_number - computer_number) % 5这个操作式中存在int与str不能相减的问题,但是我没有发现问题啊

ringa_lee
ringa_lee

ringa_lee

répondre à tous(1)
洪涛
def name_to_number(name):
    if name=="rock":
        return 0
    elif name=="Spock":
        return 1
    elif name=="paper":
        return 2
    elif name=="lizard":
        return 3
    elif name=="scissor":
        return 4
    else:
        return "wrong name you have entered"
rpsls("scissors")

传入scissors,返回的是“wrong name you have entered”。

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!