如何修复代码中的TypeError: input expected at most 1 arguments but got 3错误
解决TypeError: input expected at most 1 arguments but got 3的问题
嘿,这个问题很常见,我来给你捋清楚!
错误原因
Python的input()函数只接受一个字符串参数作为输入提示语,但你现在给它传了3个独立的字符串("How many legs does a"、w、"have? "),用逗号分隔的方式相当于给函数传了3个参数,这就触发了TypeError。
而你后面的print()能正常用多参数是因为print()默认会把多个参数用空格拼接后输出,但input()没有这个特性哦。
修复方法
有几种简单的方式把提示语整合成一个字符串传给input():
方法1:使用f-string(Python 3.6+推荐,最简洁)
f-string可以直接把变量嵌入字符串里,可读性超高:
def leg_count(w): x = input(f"How many legs does a {w} have? ") print("A", w, "has", x, "legs") leg_count("crocodile")
方法2:字符串拼接
用+把多个字符串和变量连起来:
def leg_count(w): x = input("How many legs does a " + w + " have? ") print("A", w, "has", x, "legs") leg_count("crocodile")
方法3:str.format()方法
这是Python 3.6之前常用的格式化方式:
def leg_count(w): x = input("How many legs does a {} have? ".format(w)) print("A", w, "has", x, "legs") leg_count("crocodile")
随便选一种方法,你的代码就能正常运行啦!
内容的提问来源于stack exchange,提问作者Kezia.petch
相关产品推荐
相关产品推荐

