Code in python not working

My code is to print integers from 1 to 100 and print fizz if the number is multiple of 3,print buzz if the number is multiple of 5,and print fizzbuzz if number is a multiple of 3 and 5,other wise print number itself. My code is given below.Can anyone help me find error.

Hey @jisajose12345in try this

# Iterate through numbers from 1 to 100
for num in range(1, 101):
    # Check if the number is divisible by both 3 and 5
    if num % 3 == 0 and num % 5 == 0:
        print("FizzBuzz")  # Print "FizzBuzz" if divisible by 3 and 5
    # Check if the number is divisible by 3
    elif num % 3 == 0:
        print("Fizz")  # Print "Fizz" if divisible by 3
    # Check if the number is divisible by 5
    elif num % 5 == 0:
        print("Buzz")  # Print "Buzz" if divisible by 5
    else:
        print(num)  # Print the number itself if not divisible by 3 or 5

1 Like

hey @jisajose12345in so there are a few errors in your code first in the 7th line you can instead use n%15==0 since 15 is the LCM of 3 and 5 ,secondly u need to increase the value of n by 1 always to avoid infinite loop , this can be done by adding a line n= n+1 .Also make sure the n%15==0 if statement is above n%3 and n%5 to avoid printing fizz/buzz . See screenshot for clarity

The problem with your code is that ,

if n%3 and n%5 :
this statement should be the first if statement of your code ,then only the code will give the correct output.

@jisajose12345in When your code runs, if ‘n’ is equal to a number which is divisible by both 3 and 5 it will print ‘Fizz’ instead of ‘FizzBuzz’ because the first ‘if statement’ will be executed since the condition holds. Same goes for the 2nd ‘if’ statement as well. So, all you need to do is change the order of if statements by shifting the one with n%3 and n%5 == 0 on the top and the rest remains the same. I hope that helps.

You have unfortunately forgot to increment the value of n and hence resulting in an infinite loop
To solve the issue
Try adding

“n+=1” (without qoute)

Inside your while loop;or else
Use for loop

for i in range(1,101):
//rest of your code

And try using
“n%15==0” to avoid printing the above two statement when n is divisible by both 3&5