Python类型注解练习:替换typing.Any完成正确类型标注
错误原因分析
你写的get_half类型标注不成立,核心原因是:Python 3 中/运算符默认执行浮点除法,输入整数n时,n/2的返回值是float类型(比如10/2结果为5.0而非整数5),你把返回值标注为int自然和实际返回类型不匹配。
完整正确标注代码
from typing import Any #do not edit this line def get_half(n : int) -> float: return n/2 def print_half(n : int) -> None: print(n/2) y = get_half(10) print_half(20) def is_present(s : str, char : str) -> bool: found : bool = False l : int = len(s) for i in range(0, l): if s[i] == char: found = True return found print(is_present("john", "h"))
替换逻辑说明
get_half参数n:从调用get_half(10)可知输入是整数,标注为int;返回值为除法结果,标注为floatprint_half参数n:从调用print_half(20)可知输入是整数,标注为int;函数仅执行打印没有返回值,标注为Noneis_present参数s:从调用is_present("john", "h")可知是字符串,标注为str;参数char是要匹配的单字符,标注为str;返回是否找到的布尔值,标注为bool- 函数内部变量
found是布尔标记,标注为bool;l是字符串长度,len()返回整数,标注为int
关于Any的补充说明
Any是typing模块提供的特殊类型,标注为Any的变量/参数/返回值会跳过类型检查,相当于告诉类型检查器“这个值的类型任意,不需要校验”。这个练习的核心目的就是让你根据代码逻辑和调用示例,推导每个位置的实际类型,替换掉所有无实际类型约束的Any。
内容的提问来源于stack exchange,提问作者Emilia Delizia
相关产品推荐
相关产品推荐

