首页 > 解决方案 > Python 错误“最多输入 1 个参数,得到 3 个”是什么意思?

问题描述

我是 Python 的新手,昨天在我的 PC 上创建一个基于文本的冒险游戏,当我遇到这个错误时,我无法弄清楚。有人可以向我解释吗?

choice1 = input('''Oh, you. You are finally awake. You have been out cold for the last 10 hours! I am''' ,giant, ''', and I will be your guide in defeating the dark lord Thaldmemau. Well, shall we get to it?
A: Where am I?
B: Ok, we will go!
C: Who are you again?''').lower()

if choice1 == 'a':
     print('You are in a recovery room in the Realm of Power, one of the seven universes of Epta. ')
elif choice1 == 'b':
     print('Ok, let me just give you a brief overview of what we will do and how to fight enemies!')
elif choice1 == 'c':
     print('I am' ,giant, '! I am a giant (but do not worry, I am a friendly giant). I do have some very good abilities, most of which are centred around the magic type of' ,magic, '!')

标签: python

解决方案


这是一些基本上与您的代码等效的代码:

name = "Tom"
user_input = input("My name is", name, "- what's yours?")

输出:

TypeError: input expected at most 1 arguments, got 3

如果我print改为使用,一切都会按照您期望的方式工作:

name = "Tom"
print("My name is", name, "- what's yours?")

输出:

My name is Tom - what's yours?

我猜这就是混乱的来源。print接受任意数量的参数 - 我给它三个单独的字符串 - 首先"My name is"是变量name(也是一个字符串),最后是第三个字符串"- what's yours?"

input是不同的。它完全接受 0 或 1 个参数。如果您尝试给它超过 1,它将引发TypeError.

因此,您需要使用字符串格式来解决这个特定问题。这个想法是您将生成一个字符串并将其作为参数传递给input函数:

name = "Tom"
user_input = input(f"My name is {name} - what's yours?")

推荐阅读