Reputation: 165
I am having issues getting my while loop to function properly. This is for my class, and I can't seem to find out what exactly is going on. For some reason it stops adding numbers to the "totalStars" variable after the 4th number. I can't seem to find anything that will help me. Any advice would be greatly appreciated.
# 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))
Upvotes: 0
Views: 126
Reputation: 556
Maybe an alternative could be this:
# 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))
Upvotes: 1
Reputation: 598
You only add to totalStares
with this condition:
if numStars >= 0 and numStars <=4:
totalStars += numStars
So it stopped after 4
Upvotes: 0