编写判断整数能否被3和5整除的函数遇语法问题求助
问题分析与修正方案
一、函数代码的核心问题与修正
你的is_divisible函数存在三个关键问题:
- 未定义参数接收主代码传入的整数
%运算符使用逻辑颠倒,语法错误- Python中逻辑与用
and而非&&,且if/else语句结尾必须加冒号:
修正后的函数代码:
def is_divisible(n): # 直接返回传入整数是否同时被3和5整除的判断结果 return n % 3 == 0 and n % 5 == 0
说明:
- 函数定义时添加参数
n,用来接收主代码调用时传入的整数 n % 3 == 0表示n除以3余数为0(即能被3整除),同理n % 5 == 0检查能否被5整除- 直接返回两个条件的逻辑与结果,省去冗余的
if-else结构
二、主代码的错误修正与优化
主代码存在两处缩进错误,同时可以优化布尔判断和输出写法:
from divisibleByPackage.isDivisibleBy import * count_passed = 0 count_failed = 0 if is_divisible(15): # 无需写==True,直接用布尔值做判断 print("Test #1 passed") count_passed += 1 else: print("Test #1 FAILED") count_failed += 1 if not is_divisible(1): # 用not代替==False,更符合Python风格 print("Test #2 passed") count_passed += 1 else: print("Test #2 FAILED") count_failed += 1 if not is_divisible(5): print("Test #3 passed") count_passed += 1 else: print("Test #3 FAILED") count_failed += 1 if is_divisible(0): print("Test #4 passed") count_passed += 1 else: print("Test #4 FAILED") count_failed += 1 # 用f-string格式化输出,更简洁易读 print(f"{count_passed} tests passed and {count_failed} tests failed")
优化点说明:
- 布尔判断无需额外和
True/False比较,直接用函数返回值或not取反即可 - 用
+=代替count_passed = count_passed + 1,语法更简洁 - f-string格式化字符串比拼接字符串可读性更强
关键知识点梳理
%是Python的取模运算符,a % b返回a除以b的余数,余数为0时表示a能被b整除- 函数要接收外部传入的值,必须在定义时声明参数,调用时传入对应数据才能在函数内部使用
内容的提问来源于stack exchange,提问作者mole7
相关产品推荐
相关产品推荐

