-1

I am very confused on how command-line input works, so for practice I was trying to take the following program down below and produce the same information but just by using command-line input, the only problem is I have no idea where to start

def main():
    x = (input("Give me a boolean: ").lower() == 'true')
    y = str(input("Give me a string: "))
    z = int(input("Give me a number: "))
    if x == True:
        print (y)
        print ("\"",y,"\"",sep="")
    else:
        print (z*2)



main()
mvw
  • 5,075
  • 1
  • 28
  • 34
FootOfGork
  • 55
  • 6
  • @AaronHall, I agree that the questions aren't identical, but I'm hard-pressed to see how the **answers** to that question wouldn't also be applicable to this one. But yes, the one you found is even better. – Charles Duffy Feb 26 '14 at 20:22

3 Answers3

2

See the description of sys.argv in http://docs.python.org/2/library/sys.html

import sys
x = sys.argv[1].lower() == 'true'
y = sys.argv[2]
z = int(sys.argv[3])

...or, to do things the Right Way, use argparse: http://docs.python.org/dev/library/argparse.html

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 1
    My teacher has been teaching us with sys.argv, I've currently never seen the use of argparse. I am still very new to Python or any form of program for that matter haha – FootOfGork Feb 26 '14 at 20:19
1

I agree with Charles to use argparse. I just wanted to add, that your main method should look like this:

def start(var):
    # ... your program start...

def parser():
    # use argparse here
    # ...
    return var

if __name__ == "__main__":
    var = parser()
    start(var)
    # ...

You can read the reason in the answers to this question

Community
  • 1
  • 1
runDOSrun
  • 10,359
  • 7
  • 47
  • 57
0

For discovering how things work without reading the docs, the interactive interpreter is best.

>>> input("something: ")
something: true
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'true' is not defined
>>> input("something: ")
something: True
True
>>> input("something: ")
something: 12
12
>>> input("something: ")
something: 12.4
12.4
>>> type(input("something: "))
something: 14.3
<type 'float'>
>>> type(input("something: "))
something: 14
<type 'int'>

You see, it evaluates what the user writes as a Python value.

Javier
  • 2,752
  • 15
  • 30