python - 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, '!')
解决方案
这是一些基本上与您的代码等效的代码:
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?")
推荐阅读
- python - 使用预定义函数 python 拟合数据
- kivymd - 包含图标和文本的 KivyMD 选项卡名称
- c++ - 如何在 C++ 中迭代结构?
- reactjs - React Router 可以一次使多个路由可见并一次在 URL 中编码(理想的解决方案不是失败)吗?
- javascript - 每次使用函数时 Jquery 都会出错
- python - NGINX 阻止烧瓶后端代码执行吗?
- wpf - DataTemplate MouseEnter Grid 中的 EventTrigger 不起作用
- python - pyautogui 自动化不适用于 Zoom
- python - 将 BasicLSTMCell 转换为双向 LSTM
- android-studio - 应用安装卡在 Android Studio(物理设备)上的“安装”上