【问题标题】:Writing a Function to check for Divisibility编写一个函数来检查整除性
【发布时间】:2023-02-02 08:33:47
【问题描述】:

我正在尝试编写一个函数来检查主文件中传入我的方法的 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 说我的语法不正确。

【问题讨论】:

    标签: python eclipse function pydev


    【解决方案1】:
    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 
    

    只是一个语法错误

    【讨论】:

      【解决方案2】:

      您的函数需要接受一个参数,该参数是要测试的整数。

      此外,无需将 3 和 5 声明为单独的变量。只需使用 3 和 5。

      此外,您不需要显式返回 true/false。您可以返回结果的模运算。

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

      【讨论】:

        猜你喜欢
        • 2016-12-26
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-07
        • 2019-09-20
        • 1970-01-01
        • 2020-10-22
        相关资源
        最近更新 更多