Python错误'imput最多期望1个参数,got 3'是什么意思?

2024-05-20 23:11:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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, '!')

Tags: andoftheinyouhaveamdo
3条回答

下面是一些基本上与您的代码相同的代码:

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?")

print允许您提供多个str参数,它将打印每个参数,并用空格隔开(或sep参数指定的任何字符串)。你知道吗

但是input需要一个单个str参数;您自己负责连接多个字符串。例如

choice1 = input(f'''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()

在这一行中,您使用三个参数调用了input函数:

choice1 = input('''Oh, you. .... I am''', giant, ''', and ''').lower()

如果要将字符串变量giant的内容放入用户看到的字符串中,可以使用字符串串联:

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?)'''

或字符串格式:

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?)'''.format(giant=giant))

相关问题 更多 >