在 Python 中判断数字的可整除性

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,我们可以使用取模运算符(%)来检查一个数是否能被另一个数整除。如果余数等于 0,那么这个数就能被整除。在这个挑战中,你将创建一个函数来检查一个数是否能被另一个数整除。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/booleans -.-> lab-13668{{"在 Python 中判断数字的可整除性"}} python/comments -.-> lab-13668{{"在 Python 中判断数字的可整除性"}} python/tuples -.-> lab-13668{{"在 Python 中判断数字的可整除性"}} python/function_definition -.-> lab-13668{{"在 Python 中判断数字的可整除性"}} end

数字可整除性

编写一个函数 is_divisible(dividend, divisor),它接受两个整数作为参数,如果 dividend 能被 divisor 整除,则返回 True,否则返回 False

def is_divisible(dividend, divisor):
  return dividend % divisor == 0
is_divisible(6, 3) ## True

总结

在这个挑战中,你学习了如何使用取模运算符来检查一个数是否能被另一个数整除。你创建了一个函数,该函数接受两个整数作为参数,如果被除数能被除数整除,则返回 True,否则返回 False