首页 > 解决方案 > 在 python 中输入提示因输入 import Any 而感到困惑

问题描述

我有以下练习:

在另一个面板的程序中,用正确的类型注释函数以及变量的参数和返回值。为此,您只需要用适当的类型替换所有出现的 Any,除了第一行。

示例:第 3 行中的第一个 Any,即 n: Any,必须替换为 int。你可以从第 9 行看到这一点。

虽然我理解类型提示的理论,但我没有得到练习,很可能是因为我此时没有使用 Any。此外,该练习是模棱两可的,它说要替换每次出现的 Any。

如果是这种情况,第一行将是:

def get_half(n : int) -> int:
  return n/2

如果是这样,它不起作用。

from typing import Any #do not edit this line

def get_half(n : Any) -> Any:
  return n/2

def print_half(n : Any) -> Any:
  print(n/2)
  
y = get_half(10)
print_half(20)

def is_present(s : Any, char : Any) -> Any:
  found : Any = False
  l : Any = len(s)
  for i in range(0, l):
    if s[i] == char:
      found = True
  return found

print(is_present("john", "h"))

标签: pythonpython-typing

解决方案


由于您的回答,这是正确的解决方案

这个链接非常有用

https://mypy-play.net/?mypy=latest&python=3.10

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"))


推荐阅读