2014-03-04 44 views
0
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語句,但不會再次通過循環,爲什麼會出現這種情況?儘管Python中的循環無法正常工作

+0

只是一點點修正:::我所知,輸入已經返回INT,無需INT(intput)() – Pythonizer

+1

@Streak不在python3這顯然OP寫正在使用(打印功能而不是語句)。 – Hyperboreus

回答

0

您在循環

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比後做

pointsToAdd = 30 

然後接着。

您需要爲您的用戶輸入使用另一個變量。

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") 
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") 
-1

在Python 2.x的使用: 的raw_input在Python 3.x的使用:輸入

如果你想要的Python 2.x的之間的兼容性和3.x,你可以使用:

try: 
    input = raw_input 
except NameError: 
    pass