如何检查这个数是否可以被另一个数整除

2024-03-29 06:54:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,当我需要检查ff的数字是3整除,它应该返回“Divi”。 如果它可以被3整除,它应该返回“Sible”。 如果它可以被2和3整除,它应该返回“divisible”。你知道吗

我试过这个代码,但是如果我的x=6,我只想显示“可除”而不是“divi”和“sible”。但是,这段代码将这三个值返回给我。你知道怎么做吗?谢谢!你知道吗


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()

Tags: and代码ifdef数字elseprintff
3条回答

使用单个结果变量:

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

您必须使用elif,修复缩进,并将multicase if语句置于顶部。不需要在声明中加括号。你知道吗

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")

如果您想要更简单的方法:

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")

测试:

>>> fun_divi(6)
Divisible
>>> fun_divi(5)
Not divisible by any
>>> fun_divi(3)
Sible
>>> fun_divi(2)
Divi
>>> 

这是因为你应该使用降序排列的条件,比如

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")

相关问题 更多 >