Python中delay_print函数传参报错:期望1个参数却传入3个的解决
解决delay_print函数多参数传入报错的问题
你的delay_print函数定义时只声明了1个位置参数s,但调用时传入了3个独立参数(字符串"You have"、变量lives、字符串"lives left"),这就导致了TypeError: delay_print() takes 1 positional argument but 3 were given错误。
下面是两种可行的解决办法:
方法1:先拼接成单个字符串再传入
在调用函数前,把所有要输出的内容合并成一个字符串,再传给delay_print:
# 方法a:用+拼接(注意要把非字符串类型转成字符串) message = "You have " + str(lives) + " lives left" delay_print(message) # 方法b:用f-string更简洁(自动处理类型转换) message = f"You have {lives} lives left" delay_print(message)
方法2:修改函数使其支持多参数
修改函数定义,用*args接收任意数量的位置参数,自动将所有参数拼接成单个字符串后处理:
import sys import time def delay_print(*args): # 将所有参数转为字符串后拼接成整体 full_text = ''.join(str(arg) for arg in args) for c in full_text: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.25) # 现在可以直接传入多个参数调用 delay_print("You have ", lives, " lives left")
*args会把传入的多个参数打包成一个元组,str(arg)确保非字符串类型(比如lives是数字的话)能被正确转换,最后通过join合并成完整的文本,再逐字符输出。
内容的提问来源于stack exchange,提问作者oscar
相关产品推荐
相关产品推荐

