变量未从While循环更新

时间:2019-10-27 03:02:35

标签: python python-3.x

我在使while循环正常运行时遇到问题。这是针对我的班级的,我似乎无法弄清楚到底发生了什么。由于某些原因,它停止在第四个数字之后将数字添加到“ totalStars”变量中。我似乎找不到任何可以帮助我的东西。任何建议将不胜感激。

# Initialize variables.
totalStars = 0  # total of star ratings.
numPatrons = 0  # keep track of number of patrons


# Get input.
numStarsString = input("Enter rating for featured movie: ")

# Convert to double.
numStars = float(numStarsString)

# Write while loop here
while numStars > -1:
    numPatrons +=1
    numStars = float(input("Enter rating for featured movie: "))
    if numStars >= 0 and numStars <=4:
        totalStars += numStars
    elif numStars < 0:
        numStars = -1
    else:
        print("Please enter a number 0 to 4")
        numPatrons -= 1
# Calculate average star rating

averageStars = float(totalStars / numPatrons)
print(totalStars)
print(numPatrons)
print("Average Star Value: " + str(averageStars))

2 个答案:

答案 0 :(得分:1)

也许是这样:

# Initialize variables.
totalStars = 0  # total of star ratings.
numPatrons = 0  # keep track of number of patrons

# Write while loop here
while True:
  # Get input
  numStarsString = input("Enter rating for featured movie: ")
  # Convert to double
  numStars = float(numStarsString)
  if numStars >= 0 and numStars <=4:
    totalStars += numStars
    numPatrons += 1
  elif numStars == -1:
    break
  else:
    print("Wrong input. Please enter a number 0 to 4")

# Calculate average star rating
print("Total stars: " + str(totalStars))
print("Number of patrons: " + str(numPatrons))
# Check for no valid inputs to avoid division by zero
if numPatrons > 0:
  averageStars = float(totalStars / numPatrons)
else:
  averageStars = 0
print("Average Star Value: " + str(averageStars))

答案 1 :(得分:0)

您仅在以下情况下添加到totalStares

 if numStars >= 0 and numStars <=4:
    totalStars += numStars

所以它在4点后停止了