While loop is running even though one of the conditions by the and is false

Viewed 51
spam = 1
lam = ""

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1
    
if spam < 5:
    print("You got it right")
    
else:
        print("You got it wrong")

After I put 2 as my input lam = 2 making the condition false. However it still runs 4 more times due to the spam instead of ending.

2 Answers

You need to typecast lam to int since you are comparing it to 2. Try in this way:

spam = 1
lam = 0

while spam < 5 and lam != 2:
    print("What is 1 + 1")
    lam = int(input())
    spam = spam + 1
    
if spam < 5:
    print("You got it right")
    
else:
    print("You got it wrong")

if you dont want to typecase just compare it with '2' instead of int 2

spam = 1
lam = ""

while spam < 5 and lam != '2':
    print("What is 1 + 1")
    lam = input()
    spam = spam + 1
    
if spam < 5:
    print("You got it right")
    
else:
        print("You got it wrong")
Related