You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数复用返回值报错排查:TypeError及VSCode无语法提示问题

问题分析与解决方案

首先,你遇到的TypeError: object of type 'function' has no len()错误,核心原因是你把函数本身传递给了mot_cacher,而不是majuscule函数执行后返回的字符串结果。另外你的代码还有几个逻辑小问题,导致无法正确复用返回值,我一步步给你拆解:

错误根源

  1. 未保存majuscule的返回值:你直接调用了majuscule(mot=input(...)),但没有把它的返回值存到变量里,转换后的大写字符串没被保留下来,自然没法传给mot_cacher。
  2. mot_cacher从未被调用:你的代码里只定义了mot_cacher函数,但最后没有执行它,根本看不到星号字符串的输出。
  3. majuscule的输入校验有漏洞:如果用户第一次输入的不是纯字母,你只重新输入一次,没有循环校验直到得到有效输入。

修复后的完整代码

# -*- coding: utf-8 -*-
def essais(question1="Combien d'essai ? ", question2="Saisie invalide veuillez recommencez : Combien d'essai ? "):
    essai = input(question1)
    while not essai.isnumeric():
        essai = input(question2)
    print(f"{essai} essai(s).")
    return int(essai)  # 补充返回值,方便后续复用尝试次数

def majuscule(mot):
    # 循环校验输入,确保是纯字母
    while not mot.isalpha():
        mot = input("Quel mot voulez vous faire devinez ? ")
    print("Mot valide")
    resultat = ""
    for caractere in mot:  # 直接遍历字符比按索引更简洁
        if ord("a") <= ord(caractere) <= ord("z"):
            # 转大写:小写ASCII码减32
            caractere = chr(ord(caractere) - 32)
        resultat += caractere
    print(resultat)
    return resultat

def mot_cacher(resultat):
    mot_cache = "*" * len(resultat)  # 用乘法替代循环,更高效简洁
    print(mot_cache)
    return mot_cache  # 补充返回值,方便后续复用

# 主逻辑:按顺序调用函数并传递参数
essais()
# 保存majuscule的返回值
mot_en_majuscule = majuscule(mot=input("Quel mot voulez vous faire devinez ? "))
# 把返回值传给mot_cacher
mot_cacher(mot_en_majuscule)

关键修改点说明

  • 保存返回值:用mot_en_majuscule = majuscule(...)把转换后的大写字符串存起来,这样后续可以直接传给mot_cacher。
  • 修复输入校验:把majuscule里的if-else改成while循环,确保用户输入的一定是纯字母单词,避免无效输入。
  • 简化mot_cacher逻辑:用"*" * len(resultat)替代循环拼接,Python字符串乘法更简洁高效。
  • 补充函数返回值:给essais和mot_cacher都加上返回值,方便你后续如果需要复用这些结果(比如尝试次数、隐藏后的单词)。

为什么之前会出现TypeError?

如果之前你尝试过类似mot_cacher(majuscule)的写法,那你传递的是majuscule这个函数对象,而不是它执行后的字符串结果。函数本身没有len()属性,所以Python会抛出错误。正确的做法是传递majuscule(...)执行后的返回值,也就是我们存在mot_en_majuscule里的字符串。

内容的提问来源于stack exchange,提问作者Wireless

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 12:53:12