📜  在 python 中接受多个输入(1)

📅  最后修改于: 2023-12-03 14:51:06.113000             🧑  作者: Mango

在 Python 中接受多个输入

在编写 Python 程序时,有时候需要接受多个输入值。本文将介绍几种方法来实现在 Python 中接受多个输入。

方法一:使用 input() 函数

我们可以使用 input() 函数逐一输入多个值,并用空格分隔它们。使用 split() 方法将输入值分割成多个字符串,并使用 map() 函数将这些字符串转换为相应的类型。

a, b, c = map(int, input("Enter three numbers separated by space: ").split())
print("Sum is:", a + b + c)

运行程序,可以看到下面的输出结果:

Enter three numbers separated by space: 1 2 3
Sum is: 6
方法二:使用 unpacking

我们可以使用 unpacking(解包)语法来同时接受多个输入。将输入值存储在一个元组中,然后使用 unpacking 语法将元组拆分成单独的变量。

a, b, c = input("Enter three numbers separated by space: ").split()
print("a is:", a)
print("b is:", b)
print("c is:", c)

运行程序,可以看到下面的输出结果:

Enter three numbers separated by space: 1 2 3
a is: 1
b is: 2
c is: 3
方法三:使用 argparse 模块

最后,我们可以使用 Python 内置的 argparse 模块来接受多个命令行参数。这个模块可以帮助我们处理命令行参数并生成易于使用的帮助文本。下面是一个使用 argparse 模块的示例:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

运行程序并输入一些整数,可以看到下面的输出结果:

$ python argparse_test.py 1 2 3 4
4

本文介绍了三种方法来在 Python 中接受多个输入,即使用 input() 函数、unpacking 语法和 argparse 模块。我们可以根据自己的需要选择其中的一种或多种方法。