Python 如何使这段代码包含函数,for和while循环运行良好?
我正在制作一个基于文本的RPG,但是输入有问题。我在创建一个函数时遇到了难题,该函数应该用关键字和项(例如:use item,take item…)将字符串中的两个参数分隔开。但是,出于某种原因,它不断重复相同的内容 我的代码:Python 如何使这段代码包含函数,for和while循环运行良好?,python,python-2.7,Python,Python 2.7,我正在制作一个基于文本的RPG,但是输入有问题。我在创建一个函数时遇到了难题,该函数应该用关键字和项(例如:use item,take item…)将字符串中的两个参数分隔开。但是,出于某种原因,它不断重复相同的内容 我的代码: def console(input): x = 0 y = 0 z = 0 argument1 = "" argument2 = "" for x in input:
def console(input):
x = 0
y = 0
z = 0
argument1 = ""
argument2 = ""
for x in input:
if input != " " and y != 1:
argument1 += input
elif y != 1:
y = 1
else:
argument2 += input
print argument1
print argument2
console("use item")
运行代码时收到的输出如下:use itemuse itemuse itemuse itemuse itemuse itemuse itemuse itemuse itemuse itemuse itemuse item
我不知道为什么“use”和“item”在同一行,也不知道为什么它总共重复了8次。它重复了8次,因为你要输入8个字符。我建议在进入for循环之前将字符串分解为其参数。strip()方法已经完成了您尝试执行的操作:
>>> arg1, arg2 = 'use some item'.split(' ', 1)
>>> arg1
'use'
>>> arg2
'some item'
是吗
for x in input:
所以,如果输入为“使用项”,您将循环8次(u、s、e、i、t、e、m[尝试打印x])
然后,将输入添加到带有
argument1 += input
所以你们给参数加了8次输入。
之所以将它们添加在一起,是因为末尾没有“\n” 请不要链接到代码,而是将其粘贴到此处,并通过点击
{}
按钮来正确设置格式。@g.d.d.c投票批准编辑。我注意到您正在初始化变量x
。绝对没有理由这么做。我假设您没有意识到x是从(命名不好的)输入中连续分配的字符串值。在python中,for循环的工作方式与c/c++/java中for循环的工作方式不同。如果你想给x赋值,我会对范围内的x做(len(input)):
还有,OP,使用关键字作为变量不是个好主意。在这种情况下,输入
。