I got a problem, when I need to check ff the number is divisible by 3, it should return “Divi”. If it is divisible by 3, it should return “Sible”. If it is divisible by both 2 and 3, it should return “DiviSible”.
I tried this code, however if my x = 6, I want to only show "Divisible" and not "divi" and "sible". However, this code returns the three values to me. Any idea on how to make it work? THANKS!
def fun_divi():
if(x%2==0):
print("Divi")
if(x%3==0):
print("Sible")
if(x%2==0) and (x%3==0):
print("Divisible")
else:
print("Not divisible by any")
fizz_buzz()
if(x%2==0) and (x%3==0):
print("Divisible")
elif(x%2==0):
print("Divi")
elif(x%3==0):
print("Sible")
else:
print("Not divisible by any")
You should check both diversity first.
You have to use elif
, fix your indentation, and bring the multicase if statement to the top. And no need for the brackets in the statements.
def fun_divi(x):
if x%2==0 and x%3==0:
print("Divisible")
elif x%2==0:
print("Divi")
elif x%3==0:
print("Sible")
else:
print("Not divisible by any")
If you would like a simpler way:
def fun_divi(x):
if not x % 2 or not x % 3:
if not x%2: print("Divi", end = "")
if not x%3: print("S" if x%2 else "s", "ible", end = "", sep = "")
print("")
else:print("Not divisible by any")
Testing:
>>> fun_divi(6) Divisible >>> fun_divi(5) Not divisible by any >>> fun_divi(3) Sible >>> fun_divi(2) Divi >>>
Use a single resulting variable:
def fun_divi(x):
res = ''
if (x % 2 == 0):
res += "divi"
if (x % 3 == 0):
res += "sible"
print("Not divisible by any" if not res else res.capitalize())
fun_divi(6) # Divisible
fun_divi(9) # Sible
fun_divi(5) # Not divisible by any
thats because you should use the conditions in descending order like
def fun_divi():
if(x%2==0) and (x%3==0):
print("Divisible")
elif(x%3==0):
print("Divi")
elif(x%2==0):
print("Sible")
else:
print("Not divisible by any")
Your question is the typical FizzBuzz excersise, which by the way is famous and you should have researched before. Anyway, your code has a couple of things you should fix first:
After fixing all that, your code should look something like this:
def fun_divi(x):
if x%2==0 and x%3==0:
print("DiviSible")
elif x%2==0:
print("Divi")
elif x%3==0:
print("Sible")
else:
print("Not divisible by any")
Following is the code
def func(x): return "DiviSible" if (x%2==0 and x%3==0) else "Sible" if x%3==0 else "Divi" if x%2==0 else "Not Divisible by any"
func(12) 'DiviSible' func(3) 'Divi' func(6) 'DiviSible' func(10) 'Sible' func(11) 'Not Divisible by any'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.