Python代码文本Gam

2024-04-20 10:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

player_health = 100

power = 10

enemy_health = 50

player_name = input('What is your name, Guardian? ')

print('Hello ' + player_name + ' the Guardian')

player_element = input('Would you like to be the Guardian of Air, Earth, Fire or Water? ')

if player_element == 'Air':
    print('You have been granted the powers of the Air, Guardian.\
          You now have the powers of the Wind and Sky.')

if player_element == 'Earth':
    print('You have been granted the powers of the Earth, Guardian.\
          You now have the powers of the Earth.')

if player_element == 'Fire':
    print('You have been granted the powers of Fire, Guardian.\
          You now have the powers of Fire. Do not destroy as you wish.')

if player_element == 'Water':
    print('You have been granted the powers of Water, Guardian.\
          You now have the powers to control the oceans and water.')

print('There is an enemy in the distance! What do you do?')

player_action = input('What do you do ' + player_name + '? ' + 'Type A to attack ')

if player_action == 'A':
    print('The enemy\'s health is at ' + enemy_health + '! ' 'Keep attacking Guardian!')

enemy_health = print(enemy_health - power) 

在最后一段代码中,我希望它打印出来The enemy's health is at 40!(因为power - enemy_health = 40Keep attacking Guardian!' 有什么建议吗? 它隐式地获得cant convert int object to str的错误。你知道吗


Tags: ofthenameyouifishaveelement
3条回答

不能将字符串与整数串联,而是可以使用format

print('The enemy\'s health is at {}! Keep attacking Guardian!'.format(enemy_health))

要使用+运算符并执行连接,首先必须创建一个字符串

print('The enemy\'s health is at ' + str(enemy_health) + '! Keep attacking Guardian!'

你还需要改变他们的健康状况,我不知道你认为这是在做什么

enemy_health = print(enemy_health - power) 

你应该把它改成

enemy_health = enemy_health - power
enemy_health = enemy_health - power

enemy_health变量重新指定为它们的当前health-power。然后可以通过使用str(enemy_health)显式转换,在任何地方重用这个整数。PythonMaster&CoryKramer有最新的实现,它使用.format()。这些{}表示格式列表中的变量应该放在哪里。你知道吗

print(str(enemy_health))

可以改用.format(),因为不能将字符串与整数串联。请尝试:

print('The enemy\'s health is at {}! Keep attacking Guardian!'.format(enemy_health))

或者更简单的方式:

enemy_health -= power  #This is short for enemy_health = enemy_health - power
print("The enemy's health is at", enemy_health,"! Keep attacking Guardian!")

老实说,最后一句话毫无意义。不能将print()赋值给变量。它是一个函数,你不能给变量赋值。只能将类分配给变量。这也应该是错误的一部分,因为print(enemy_health - power)实际上是有效的。输出为40。你知道吗

相关问题 更多 >