gpt4 book ai didi

Python-变量不会减法?

转载 作者:行者123 更新时间:2023-11-30 23:34:18 24 4
gpt4 key购买 nike

我正在尝试用 Python(版本 3.3.2)创建一个简单的问答游戏,但无法弄清楚如何使表达式发挥作用。下面看到的“health”和“oppHealth”变量不会随着程序运行而改变,或者至少字符串显示不会显示它们发生变化。源代码:

import time

#Variables
health = 30
oppHealth = 30
playStr = str(health)
oppStr = str(oppHealth)

def startBattle():
print()
print('You face off against your opponent.')
print()
print("Your health is " + playStr + ".")
print("Your opponent's health is " + oppStr + ".")
time.sleep(2)
print()
print('The opponent attacks with Fire!')
time.sleep(2)
print()
attack = input('How do you counter? Fire, Water, Electricity, or Ice?')
if attack == ('Fire'):
print("You're evenly matched! No damage is done!")
time.sleep(3)
startBattle()
elif attack == ('Water'):
print("Water beats fire! Your opponent takes 5 damage!")
oppHealth - 5
time.sleep(3)
startBattle()
elif attack == ('Electricity'):
print("You both damage each other!")
health - 5
oppHealth - 5
time.sleep(3)
startBattle()
elif attack == ('Ice'):
print("Fire beats ice! You take 5 damage.")
health - 5
time.sleep(3)
startBattle()

startBattle()

我只是想让适当的健康变量减少 5 - 并让健康显示字符串反射(reflect)每次战斗发生时的变化。如果有人能帮助我解决这个问题,我将不胜感激。如果我排除了任何可能对您有帮助的信息,请告诉我。

最佳答案

线条

   health - 5
oppHealth - 5

类似,实际上不修改任何内容,要将减法保存回变量中,请改用 -= 运算符

health -= 5

或者你也可以说

health = health - 5

上面两个例子都达到了相同的结果。当您只是说health - 5时,您实际上并没有将其保存在任何地方。

除此之外,您还需要在函数顶部指定 global 来修改这些值,否则您将收到错误。

def startBattle():
global health
global oppHealth
# ... rest of function

此外,您不需要 playStroppStr 变量,您可以像这样打印数值:

print("Your health is", health, ".")
print("Your opponent's health is", oppHealth, ".")
<小时/>

这些实际上根本不需要是全局的,它们可以在函数内,坐在循环中,我的程序版本将是这样的:

#!/usr/bin/env python3

import time


def startBattle():
# set initial values of healths
health = 30
oppHealth = 30
print('You face off against your opponent.', end='\n\n')
while health > 0 and oppHealth > 0: # loop until someone's health is 0
print("Your health is {0}.".format(health))
print("Your opponent's health is {0}.".format(oppHealth), end='\n\n')
time.sleep(2)
print('The opponent attacks with Fire!', end='\n\n')
time.sleep(2)
print('How do you counter? Fire, Water, Electricity, or Ice?')
attack = input('>> ').strip().lower()
if attack == 'fire':
print("You're evenly matched! No damage is done!")
elif attack == 'water':
print("Water beats fire! Your opponent takes 5 damage!")
oppHealth -= 5
elif attack == 'electricity':
print("You both damage each other!")
health -= 5
oppHealth -= 5
elif attack == 'ice':
print("Fire beats ice! You take 5 damage!")
health -= 5
else:
print("Invalid attack choice")

time.sleep(3)

if health <= 0 and oppHealth <= 0:
print("Draw!")
if health <= 0:
print("You lose")
else:
print("You win!")

startBattle()

尽管我也会摆脱所有的 sleep 。人们并不像您想象的那样喜欢等待程序“工作”,这只会导致人们点击离开。

关于Python-变量不会减法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18219229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com