1

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
2
  • Why that's print "Too many arguments" if there's less 3??? Commented Mar 8, 2015 at 17:54
  • Are you expecting exactly 3 arguments, or up to 3? Commented Mar 8, 2015 at 18:07

3 Answers 3

1

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"
Sign up to request clarification or add additional context in comments.

3 Comments

Oh right, thanks! How can I test with a if to check that it's only three arguments and not less ore more.
You can just check len(sys.argv).
@Iknowpython you can use the == operator. See my edited post.
0
#!/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

1 Comment

If I enter four arguments I get "Only three arguments" thats wrong.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.