pointsToAdd = 30
strengthPoints = 0
healthPoints = 0
wisdomPoints= 0
dexterityPoints = 0
while pointsToAdd > 0:
choice = int(input("Choice(1-4): "))
if choice == 1:
pointsToAdd = int(input("How many Strength points would you like to add: "))
if pointsToAdd < 31 and pointsToAdd > 0 and pointsToAdd - strengthPoints > 0:
strengthPoints += pointsToAdd
pointsToAdd -= strengthPoints
print("You now have",strengthPoints,"strength points")
elif pointsToAdd > 30:
print("You cannot add that many!")
elif pointsToAdd<1:
print("You cannot add less than one point!")
elif pointsToAdd - strengthPoints <= 0:
print("You only have",pointsToAdd,"points!")
else:
print("We are sorry, but an error has occurred")
我试图让它成为用户可以为四个类别中的任何一个输入分数,但是花费不超过30分(我还没有为健康,智慧或灵巧点编写代码)。为什么当我运行程序时,如果您选择在1-30之间添加多个点,则循环仅再次运行?如果用户使用不在1-30之间的数字输入他们想要分配给strengthPoints
的点,则循环将运行相关的if语句,但不会再次循环,为什么会出现这种情况?
答案 0 :(得分:1)
您使用相同的变量用于两个不同的目的pointsToAdd
。您可以将其作为要分配的总点数,以及用户选择添加到统计数据的内容。一旦你用用户选择踩到要分配的总点数,然后将它添加到0强度并从用户输入的值中减去它,将其设置为零。用于分隔下面的变量将解决它。
totalPointsToAdd = 30
strengthPoints = 0
healthPoints = 0
wisdomPoints= 0
dexterityPoints = 0
while totalPointsToAdd > 0:
choice = int(input("Choice(1-4): "))
if choice == 1:
pointsToAdd = int(input("How many Strength points would you like to add: "))
if pointsToAdd < 31 and pointsToAdd > 0 and pointsToAdd - strengthPoints > 0:
strengthPoints += pointsToAdd
totalPointsToAdd -= pointsToAdd
print("You now have",strengthPoints,"strength points")
答案 1 :(得分:0)
你做
pointsToAdd = 30
然后在循环中
pointsToAdd = int(input("How many Strength points would you like to add: "))
然后在测试中
# Here pointsToAdd is not 30, but the value inputed by the user
strengthPoints += pointsToAdd
# Here strengthPoints == pointsToAdd == the value from the input
pointsToAdd -= strengthPoints
# Here pointsToAdd == 0
这导致pointsToAdd == 0
之后。{/ p>
您需要使用另一个变量来输入您的用户。
答案 2 :(得分:0)
正如其他人指出的那样,你要覆盖同一个变量pointsToAdd
。我还认为你可以将你的条件减少到两个:
pointsToAdd = 30
strengthPoints = 0
while pointsToAdd:
print ('You have', pointsToAdd, 'available points.')
choice = int(input("Choice(1-4): "))
if choice == 1:
toBeAdded = int(input("How many Strength points would you like to add: "))
if toBeAdded < 1: # Can't assign negative or null values
print("You cannot add less than one point!")
continue
if toBeAdded > pointsToAdd: # Don't have enough points to spend
print("You only have", pointsToAdd, "available points!")
continue
strengthPoints += toBeAdded
pointsToAdd -= toBeAdded
print("You now have", strengthPoints, "strength points")
答案 3 :(得分:-1)
在Python 2.x中使用:raw_input 在Python 3.x中使用:input
如果想要兼容Python 2.x和3.x,可以使用:
try:
input = raw_input
except NameError:
pass