python 编写一个函数来检查整除性

gdrx4gfi  于 2023-02-02  发布在  Python
关注(0)|答案(4)|浏览(133)

我试图写一个函数来检查传入主文件中的方法的int是否能被3和5整除。
我遇到了麻烦,因为我不确定使用什么来检查我的方法中的条件,因为值是通过主文件中的方法调用传入的。
我也不确定我是否正确地使用了%操作符来检查该值是否可以被3和5整除。如果有任何关于这方面的指导,我将非常感激。
主要:

from divisibleByPackage.isDivisibleBy import *

count_passed = 0
count_failed = 0
if (is_divisible(15) == True):
print("Test #1 passed")
count_passed = count_passed + 1
else:
    print("Test #1 FAILED")
    count_failed = count_failed + 1
if (is_divisible(1) == False):
    print("Test #2 passed")
    count_passed = count_passed + 1
else:
    print("Test #2 FAILED")
    count_failed = count_failed + 1
if (is_divisible(5) == False):
    print("Test #3 passed")
    count_passed = count_passed + 1
else:
    print("Test #3 FAILED")
    count_failed = count_failed + 1
if (is_divisible(0) == True):
    print("Test #4 passed")
    count_passed = count_passed + 1
else:
    print("Test #4 FAILED")
    count_failed = count_failed + 1

    print(str(count_passed) + " tests passed and " + str(count_failed) + " tests failed")

从PyDev包导入的函数:

def is_divisible():
    number1 = 3
    number2 = 5

    if (number1 % == 0 && number2 % == 0)
        return True
    else
        return False

我希望main中的方法调用根据条件返回true或false,但是Eclipse说我的语法不正确。

fcg9iug3

fcg9iug31#

number1 % 3 == 0

表示数字可被3整除

number1 % 5 == 0

表示数字可被5整除

number1 % 3 == 0 and number1 % 5 == 0
 # NOTE it is NOT && for 'and' in python

表示它可以被3和5整除

number1 % 3 == 0 or number1 % 5 == 0

意味着它可以被3或5整除,也可以被两者整除

number1 % == 0

只是语法错误(&&在python中也不正确)

thtygnil

thtygnil2#

您的函数需要接受一个参数,即要测试的整数。
另外,3和5也不需要声明为单独的变量,只需要使用3和5即可。
另外,你不需要显式地返回true/false,你可以返回取模运算的 result,它本身就是true/false。

def is_divisible(num):
    return (num % 3 == 0) and (num % 5 == 0)
p1iqtdky

p1iqtdky3#

代码中有三个错误:
1.该函数被定义为不接受参数,但是在测试中,它是使用参数调用的。

  1. &&不是Python中的运算符,而是使用and
    1.缺少%运算符的第二个操作数。%是二元运算符,这意味着它使用两个操作数。示例3%2
    函数应编写为
def is_divisible(number):

    if number % 3 == 0 and number % 5 == 0:
        return True
    else:
        return False
lf3rwulv

lf3rwulv4#

其他的答案可以解释错误。下面的代码可以工作:

def is_divisible(number1):

    if (number1 % 3 == 0 and number1 % 5 == 0):
        return True
    else:
        return False

count_passed = 0
count_failed = 0
if (is_divisible(15) == True):
    print("Test #1 passed")
    count_passed = count_passed + 1
else:
    print("Test #1 FAILED")
    count_failed = count_failed + 1
if (is_divisible(1) == False):
    print("Test #2 passed")
    count_passed = count_passed + 1
else:
    print("Test #2 FAILED")
    count_failed = count_failed + 1
if (is_divisible(5) == False):
    print("Test #3 passed")
    count_passed = count_passed + 1
else:
    print("Test #3 FAILED")
    count_failed = count_failed + 1
if (is_divisible(0) == True):
    print("Test #4 passed")
    count_passed = count_passed + 1
else:
    print("Test #4 FAILED")
    count_failed = count_failed + 1

print(str(count_passed) + " tests passed and " + str(count_failed) + " tests failed")

相关问题