以下代码是我的答案。仅供参考交流
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
import random
def number_to_name(number):
# convert number to a name using if/elif/else
# don't forget to return the result!
if number == 0:
return 'rock'
elif number == 1:
return 'Spock'
elif number == 2:
return 'paper'
elif number == 3:
return 'lizard'
elif number == 4:
return 'scissors'
else:
print 'plz input number between 0~4 !'
def name_to_number(name):
# convert name to number using if/elif/else
# don't forget to return the result!
if name == 'rock':
return 0
elif name == 'Spock':
return 1
elif name == 'paper':
return 2
elif name == 'lizard':
return 3
elif name == 'scissors':
return 4
else:
return 5
def rpsls(name):
# fill in your code below
# print the player's choice
print '---------------------------------------------------------'
print 'the player\'s choice is :', name
# convert name to player_number using name_to_number
player_number = name_to_number(name)
# compute random guess for comp_number using random.randrange()
comp_number = random.randrange(0, 5, 1)
# convert comp_number to name using number_to_name and print
comp_name = number_to_name(comp_number)
print 'the computer\'s choice is :', comp_name, '\n'
# compute difference of player_number and comp_number modulo five
diff = (player_number - comp_number) % 5
# use if/elif/else to determine winner and print result
if player_number == 5:
print 'Wrong Name !'
elif diff == 0:
print 'the are equal!'
elif 0 < diff <= 2:
print 'player wins!'
elif diff > 2:
print 'computer wins!'
else:
return 'there are some problems !'
# test
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
rpsls('sdvdsssss')
rpsls(123)