Python函数复用返回值报错排查:TypeError及VSCode无语法提示问题
问题分析与解决方案
首先,你遇到的TypeError: object of type 'function' has no len()错误,核心原因是你把函数本身传递给了mot_cacher,而不是majuscule函数执行后返回的字符串结果。另外你的代码还有几个逻辑小问题,导致无法正确复用返回值,我一步步给你拆解:
错误根源
- 未保存
majuscule的返回值:你直接调用了majuscule(mot=input(...)),但没有把它的返回值存到变量里,转换后的大写字符串没被保留下来,自然没法传给mot_cacher。 mot_cacher从未被调用:你的代码里只定义了mot_cacher函数,但最后没有执行它,根本看不到星号字符串的输出。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
相关产品推荐
相关产品推荐

