I am new to python and working on putting arguments into variables. I was trying to only allow three variables as arguments and put them into a, b and c as a string.
#!/usr/bin/python
import sys
x = sys.argv[1:]
x = ' '.join(x)
if len(x) > 3:
print "Only three arguments"
else:
print "Too many arguments"
a,b,c=[[y] for y in x.split()]
print a
print b
print c
Mureinik
316k54 gold badges404 silver badges406 bronze badges
asked Mar 8, 2015 at 17:41
user4647247
-
Why that's print "Too many arguments" if there's less 3???Texom512– Texom5122015年03月08日 17:54:44 +00:00Commented Mar 8, 2015 at 17:54
-
Are you expecting exactly 3 arguments, or up to 3?Jon Clements– Jon Clements2015年03月08日 18:07:09 +00:00Commented Mar 8, 2015 at 18:07
3 Answers 3
Since you want the arguments as scalars, you don't need the [] around y:
a,b,c = [y for y in x.split()]
But frankly, you don't even need to go through the joining a splitting - you can assign an array to a series of comma-delimited scalars:
a,b,c = sys.argv[1:]
Similarly, you shouldn't check len on a joined string, but on the array. A complete example:
#!/usr/bin/python
import sys
x = sys.argv[1:] # no joining!
if len(x) == 3:
print "Only three arguments"
a,b,c = x
print a
print b
print c
else:
print "Too many arguments"
answered Mar 8, 2015 at 17:46
Mureinik
316k54 gold badges404 silver badges406 bronze badges
Sign up to request clarification or add additional context in comments.
#!/usr/bin/python
import sys
if len(sys.argv)!=4:
print "Need to get 3 arguments"
sys.exit()
a=str(sys.argv[1])
b=str(sys.argv[2])
c=str(sys.argv[3])
print a
print b
print c
answered Mar 8, 2015 at 17:43
ForceBru
45k10 gold badges72 silver badges104 bronze badges
Here's the working code:
import sys
args = sys.argv[1:]
if len(args) > 3:
print "Too many arguments"
for arg in args:
print(arg)
answered Mar 8, 2015 at 18:01
Texom512
4,9213 gold badges19 silver badges16 bronze badges
Comments
lang-py