Can I include sys.argv in this?

I am trying to create a simple script that will take age as an argument to determine the appropriate entry fee. (<6 = Free;> = 7 and <= 14 - $ 10;> = 15, and <= 59 - $ 15;> = 60 - $ 5)

I managed to get the script to work if I enter age at age = __ in the script, but I want to be able to pass age as an argument to the "Arguments" field. Run the script window. I think I should use sys.argv, but I could not figure out how to do this. I suspect this is due to some kind of disagreement between what sys.argv wants and what I provide, maybe the mismatch of strings and integers?

Any ideas?

# Enter age
age = 5

if age < 7:
    print ("Free Admission")

elif age < 15:
    print ("Admission: $10")

elif age < 60:
    print ("Admission: $15")

else:
    print ("Admission: $5")
+4
source share
2

, , sys.argv; , sys.argv[0] - script, - :

import sys

if len(sys.argv) > 1:
    try:
        age = int(sys.argv[1])
    except ValueError:
        print('Please give an age as an integer')
        sys.exit(1)

else:
    print('Please give an age as a command line argument')
    sys.exit(1)

Python argparse, sys.argv:

import argparse

parser = argparse.ArgumentParser('Admission fee determination')
parser.add_argument('age', type=int, help='the age of the visitor')
args = parser.parse_args()

age = args.age

age . script :

$ python yourscript.py -h
usage: Admission fee determination [-h] age

positional arguments:
  age         the age of the visitor

optional arguments:
  -h, --help  show this help message and exit

, age .

+4
# here you import `sys` that enables access to `sys.argv`
import sys

# then you define a function that will embed your algorithm
def admission_fee(age):
    age = int(age)
    if age < 7:
        print ("Free Admission")
    elif age < 15:
        print ("Admission: $10")

    elif age < 60:
        print ("Admission: $15")

    else:
        print ("Admission: $5")

# if you call this python module from the command line, you're in `__main__` context
# so if you want to reuse your module from another code, you can import it!
if __name__ == "__main__":
    # here you use the first argument you give to your code, 
    # sys.argv[0] being the name of the python module
    admission_fee(sys.argv[1])

, argparse docopt, !

docopt:

"""Usage: calcul_fee.py [-h] AGE

Gets the admission fee given the AGE

Arguments:
    AGE  age of the person

Options:
    -h --help"""

from docopt import docopt

def admission_fee(age):
    age = int(age)
    if age < 7:
        print ("Free Admission")
    elif age < 15:
        print ("Admission: $10")
    elif age < 60:
        print ("Admission: $15")
    else:
        print ("Admission: $5")

if __name__ == '__main__':
    arguments = docopt(__doc__)
    admission_fee(arguments.AGE)
+1

Source: https://habr.com/ru/post/1524107/


All Articles