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

Python报错:print_slow()需1个位置参数却传入2个,求解答

解决TypeError: print_slow() takes 1 positional argument but 2 were given错误

错误原因

你定义的print_slow函数只接受1个参数,但调用时传了两个值:"Did you say"和num1。Python函数的参数数量是固定的(除非特意设置可变参数),它没法把两个值塞进只留了一个位置的参数里,所以抛出这个错误。

解决办法

方法1:合并参数成单个字符串(简单直接)

把要打印的内容提前合并成一个字符串,只传一个参数给print_slow。用Python的f-string是最方便的方式:

修改调用print_slow的代码:

print_slow(f"Did you say {num1}")

完整修改后的代码:

import sys
import os
import time

def print_slow(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.1)

num1 = int(input("Chose any number: "))

print_slow(f"Did you say {num1}")

方法2:修改函数支持多参数(更灵活)

如果以后想经常传多个内容给print_slow,可以修改函数,让它能接收任意数量的参数,再自动拼接成字符串处理:

修改函数定义:

def print_slow(*args):
    # 把所有参数转成字符串后拼接在一起
    content = ''.join(str(arg) for arg in args)
    for letter in content:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.1)

这样原来的调用代码print_slow("Did you say",num1)不用改就能正常运行,以后还能传更多参数,比如print_slow("Hello", " ", num1, "!")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:10:30