Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 선택 옵션을 사용하여 인수 값을 제한하는 방법은 무엇입니까?

<시간/>

소개..

사용자로부터 테니스 그랜드슬램 타이틀의 수를 수락하고 처리하는 프로그램을 코딩하라는 요청을 받았다고 가정합니다. 우리는 이미 Federer와 Nadal이 테니스에서 최대 그랜드슬램 타이틀을 20개(2020년 현재)로 공유하는 반면 최소값은 0개라는 것을 알고 있습니다. 많은 선수들이 첫 그랜드슬램 타이틀을 얻기 위해 여전히 싸우고 있습니다.

타이틀을 수락하는 프로그램을 만들어 봅시다.

참고 - 터미널에서 프로그램을 실행합니다.

예시

import argparse

def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.

2. type - The actual Python data type
- (note the lack of quotes around str)

3. help - A brief description of the parameter for the usage

"""

parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)

# Adding our first argument player titles of type int
parser.add_argument('titles',
metavar='titles',
type=int,
help='GrandSlam Titles')

return parser.parse_args()

# define main
def main(titles):
print(f" *** Player had won {titles} GrandSlam titles.")

if __name__ == '__main__':
args = get_args()
main(args.titles)

출력

이제 프로그램에서 제목을 수락할 준비가 되었습니다. 따라서 임의의 숫자(float가 아님)를 인수로 전달합니다.

<<< python test.py 20
*** Player had won 20 GrandSlam titles.
<<< python test.py 50
*** Player had won 50 GrandSlam titles.
<<< python test.py -1
*** Player had won -1 GrandSlam titles.
<<< python test.py 30
*** Player had won 30 GrandSlam titles.

코드에 기술적인 문제는 없지만, 우리 프로그램이 네거티브 타이틀을 포함하여 그랜드슬램 타이틀을 원하는 만큼 허용하므로 분명히 기능적 문제가 있습니다.

GrandSlam 타이틀의 선택을 제한하려는 경우 선택 옵션을 사용할 수 있습니다.

다음 예에서는 제목을 범위(0, 20)로 제한합니다.

예시

import argparse
def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.

2. type - The actual Python data type
- (note the lack of quotes around str)

3. help - A brief description of the parameter for the usage

4. choices - pre defined range of choices a user can enter to this program

"""

parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)

# Adding our first argument player titles of type int
parser.add_argument('titles',
metavar='titles',
type=int,
choices=range(0, 20),
help='GrandSlam Titles')

return parser.parse_args()

# define main
def main(titles):
print(f" *** Player had won {titles} GrandSlam titles.")

if __name__ == '__main__':
args = get_args()
main(args.titles)

출력

>>> python test.py 30
usage: test.py [-h] titles
test.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
<<< python test.py 10
*** Player had won 10 GrandSlam titles.
<<< python test.py -1
usage: test.py [-h] titles
test.py: error: argument titles: invalid choice: -1 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
<<< python test.py 0
*** Player had won 0 GrandSlam titles.
<<< python test.py 20
usage: test.py [-h] titles
test.py: error: argument titles: invalid choice: 20 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

결론 :

  • 선택 옵션은 값 목록을 사용합니다. argparse는 사용자가 이들 중 하나를 제공하지 않으면 프로그램을 중지합니다.

  • 사용자는 0-19 숫자 중에서 선택해야 합니다. 그렇지 않으면 argparse가 오류와 함께 중지됩니다.

마지막으로, 문자열 선택을 허용하는 프로그램을 가질 수도 있습니다.

예시

import argparse

def get_args():
""" Function : get_args
parameters used in .add_argument
1. metavar - Provide a hint to the user about the data type.
- By default, all arguments are strings.

2. type - The actual Python data type
- (note the lack of quotes around str)

3. help - A brief description of the parameter for the usage

4. choices - pre defined range of choices a user can enter to this program

"""

parser = argparse.ArgumentParser(
description='Example for one positional arguments',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)

# Adding our first argument player names of type str.
parser.add_argument('player',
metavar='player',
type=str,
choices=['federer', 'nadal', 'djokovic'],
help='Tennis Players')

# Adding our second argument player titles of type int
parser.add_argument('titles',
metavar='titles',
type=int,
choices=range(0, 20),
help='GrandSlam Titles')

return parser.parse_args()

# define main
def main(player,titles):
print(f" *** {player} had won {titles} GrandSlam titles.")

if __name__ == '__main__':
args = get_args()
main(args.player,args.titles)

출력

<<< python test.py
usage: test.py [-h] player titles
test.py: error: the following arguments are required: player, titles
<<< python test.py "federer" 30
usage: test.py [-h] player titles
test.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
<<< python test.py "murray" 5
usage: test.py [-h] player titles
test.py: error: argument player: invalid choice: 'murray' (choose from 'federer', 'nadal', 'djokovic')
<<< python test.py "djokovic" 17
*** djokovic had won 17 GrandSlam titles.