python - 参数声明排序

时间:2015-03-30 10:04:17

标签: python

首先,我非常非常棒,初学者等在python和编程中一般,所以对于进一步的问题很抱歉,但我有这个示例代码:

from sys import argv
p_script = argv 
p_user_name = argv
p_id = argv
v_prompt = ": "

print "Hey %s, I'm the %s script with id: '%s'" % (p_user_name, p_script, p_id)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % p_user_name
v_likes = raw_input(v_prompt)

print "Where do you live %s?" % p_user_name
v_lives = raw_input(v_prompt)

print "What kind of computer do you have?"
v_computer = raw_input(v_prompt)

print """Alright, so you said '%s' about liking me.
You live in '%s'. Not sure where that is.
And you have a '%s' computer. Nice.""" % (v_likes, v_lives, v_computer)

和此:

from sys import argv
p_script, p_user_name, p_id = argv
v_prompt = ": "

print "Hey %s, I'm the %s script with id: '%s'" % (p_user_name, p_script, p_id)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % p_user_name
v_likes = raw_input(v_prompt)

print "Where do you live %s?" % p_user_name
v_lives = raw_input(v_prompt)

print "What kind of computer do you have?"
v_computer = raw_input(v_prompt)

print """Alright, so you said '%s' about liking me.
You live in '%s'. Not sure where that is.
And you have a '%s' computer. Nice.""" % (v_likes, v_lives, v_computer)

我真的不明白为什么输出是疯狂的,比如在powershell中运行它时将参数或参数作为字符串传递给代码(例如:exec python“example 1”,“Name”,“101”)它给了我每个stept在运行时所有的参数。所以我在这里要问的是,为什么它在不同的样式参数声明中不能正常工作。请参阅第一个代码片段的声明字段和第二个声明字段,即“经典”样式。非常感谢,欢呼。

3 个答案:

答案 0 :(得分:3)

你发现python列表正在拆包。在你的第一个脚本

p_script = argv 
p_user_name = argv
p_id = argv

所有三个p_...都具有相同的值argv。在第二个脚本

p_script, p_user_name, p_id = argv

列表argv已解包,因此第一个元素变为p_script,第二个p_user_name和第三个p_id

答案 1 :(得分:2)

您没有正确使用assignment。您要反复分配列表argv,而不是将其解包,或者从中分配单个项目而不是整个列表。

这部分:

p_script, p_user_name, p_id = argv

不等同于你写的内容,它一遍又一遍地指定列表 argv

p_script = argv 
p_user_name = argv
p_id = argv
然而,它等同于:

p_script = argv[0]
p_user_name = argv[1]
p_id = argv[2]

答案 2 :(得分:1)

问题出在第一行:

p_script = argv 
p_user_name = argv
p_id = argv

你可能想从argv获取元素,比如argv[0]