Search code examples
pythonwhile-loop

Adding multiple conditions in a while loop in python


i'm having problems adding these 3 conditions in a while loop, where is the error?

n = eval(input("Number: "))

i = 0

while (i % 3 == 0) and (i % 5 == 0) and (i < n):
    print(i, end=" ")
    i = i + 1

I want it to print the numbers divisible by 3 and 5 as long as i < n. If i type in 100 it gives back 0 right now.


Solution

  • You should separate the conditions for division and being less than n, making the latter the while loop condition, and the former an if condition inside the while loop, also, you should use int instead of eval to get the input value as an integer:

    n = int(input("Number: "))
    
    i = 0
    
    while i < n:
        if (i % 3 == 0) and (i % 5 == 0):
            print(i, end=" ")
        
        i = i + 1