python-3.xwhile-loopaccumulator

python accumulating while loop keeps repeating what did i do wrong?


I can't figure out what I am doing wrong. I have tried using a break, and tried setting what the variable !=, I am doing this on cengage and it is very finnicky.

""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""

rightTotal = 0 # Number of right-handed students. 
leftTotal = 0 # Number of left-handed students.

leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.") 
while leftOrRight != "X": 
    print (leftOrRight) 
    if leftOrRight == "L": 
        leftTotal = (leftTotal + 1) 
    elif leftOrRight == "R": 
        rightTotal = (rightTotal + 1) 
    else: 
        break

print("Number of left-handed students: " + str(leftTotal)) 
print("Number of right-handed students: " + str(rightTotal))

Solution

  • your input() is outside the while loop, so leftOrRight never changes, never get to X so it will not exit the loop:

    leftOrRight = None
    while leftOrRight != "X":
        leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
        print (leftOrRight)
        if leftOrRight == "L":
            leftTotal = (leftTotal + 1)
        elif leftOrRight == "R":
            rightTotal = (rightTotal + 1)
        else:
            break