what needs to be corrected in the below code in python?
e.g 91 is not prime but how it can corrected?
for x in range(100):
if x%3==0:
print ("Fizz", x)
elif x%5==0:
print ("buzz",x)
elif x%3==0 and x%5 == 0:
print ("FizzBuzz",x)
elif x%x==0 and x%2==1:
print ("Prime number",x)```
As @toRex mentioned in the comments, you are checking if a number is prime using the condition:
x%x==0 and x%2==1
Please note that x%x==0
is always true. So basically you just checking if a number is odd, and print it as a prime. There are many methods to check whether a number is prime or not in general, and specifically in python. For example, you can use Checking if a number is a prime number in Python and take the first algorithm from there:
from math import sqrt
from itertools import count, islice
def is_prime(n):
return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1)))
Then call:
for x in range(100):
if x%3==0 and x%5 == 0:
print ("FizzBuzz",x)
elif x%3==0:
print ("Fizz", x)
elif x%5==0:
print ("buzz",x)
elif is_prime(x):
print ("Prime number",x)
Will output the expected output. Please also note that I've flipped the order of the conditions, to check first if a number is FizzBuzz
, and only then if he is a fizz, or a buzz separately. Otherwise a fizz
number will be considered as a fizz
and not as a FizzBuzz
as expected.