变量未从While循环更新

纳撒尼尔·威尔逊

我在使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))
亚伦·西尔曼

也许替代方法可能是这样的:

# 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))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章