如何读取 Python 中给出的输入数量

How to read number of inputs given in Python

给定的问题取决于给定输入的数量(1 个输入、2 个输入或 3 个)求出圆的周长以及矩形和三角形的周长。 我似乎无法弄清楚如何读取输入的数量,例如:如果我只提供一个输入 ex:2 输出应该是“12.56”,如果我给 2 个输入说 2 4 输出应该是“6”(2*(a+b)) 到目前为止,我已经完成了所有功能,而且我还停留在输入

def cir(a):
    x=2*3.142*a
    return x
def rec(a,b):
    y=2*(int(a+b))
    return y
def tri(a,b,c):
    z=a+b+c
    return z
a=b=c=0
print("enter the dimenssions")
a,b,c=float(input()),float(input()),float(input())

如果我理解正确,这应该可行 (假设你想在 space 上分开)

def cir(a):
    x=2.0*3.142*float(a)
    return x
def rec(a,b):
    y=2*(float(a)+float(b))
    
    return y
def tri(a,b,c):
    z=float(a)+float(b)+float(c)
    return z

#fun fact, you can put a string inside "input()" and it will have that right before you can type
userInput = input("Enter dimenssions: ")
userInput = userInput.split(" ")#Split the input on all  the spaces

numInputs = len(userInput)#Get how many numbers there are

if(numInputs == 1):
    print("Calculating for cir")
    print(cir(userInput[0]))
elif(numInputs == 2):
    print("Calculating for rect")
    print(rec(userInput[0], userInput[1]))
elif(numInputs == 3):
    print("Calculating for tri")
    print(tri(userInput[0], userInput[1], userInput[2]))
else:
    print("Error, you entered something wrong :(")

测试:

Enter dimenssions: 5
Calculating for cir
31.419999999999998
Enter dimenssions: 15 7
Calculating for rect
44.0
Enter dimenssions: 10 2 7
Calculating for tri
19.0

我确实不得不根据我实现这个的方式更改你的边界函数。

我们到了

def cir(a):
    x=2*3.142*a
    return x
def rec(a,b):
    y=2*(int(a+b))
    return y
def tri(a,b,c):
    z=a+b+c
    return z

l_input = [float(x) for x in input("Input values:").split()]

print("Input = {}".format(l_input))

if len(l_input) == 1:
    print(cir(*l_input))
elif len(l_input) == 2:
    print(rec(*l_input))
elif len(l_input) == 3:
    print(tri(*l_input))

示例输出:

Input values:1
Input = [1.0]
6.284


Input values: 1 2
Input = [1.0, 2.0]
6

Input values: 1 2 3 
Input = [1.0, 2.0, 3.0]
6.0

使用str.split:

def cir(a):
    return 2 * 3.142 * a
def rec(a, b):
    return 2 * (a + b)
def tri(a, b, c):
    return a + b + c

funcs = {1: cir, 2: rec, 3: tri}

try:
    inputs = list(map(float, input("Please give floats space separated ").split()))
except ValueError:
    print("Values must be floats")

try:
    func = funcs[len(inputs)]
    print(f"Using {func.__name__}")
    print(func(*inputs))
except IndexError:
    print("Too many inputs given must be 3 or less")

Please give floats space separated 1
Using cir
6.284

Please give floats space separated 1 2
Using rec
6.0

Please give floats space separated 1 2 3
Using tri
6.0

可能改为“a,b,c=float(input()),float(input()),float(input())”,像这样:

param = input().split()
if len(param) == 1:
    print(cir(float(param[0])))
elif len(param) == 2:
    print(rec(float(param[0]), float(param[1])))
elif len(param) == 3:
    print(tri(float(param[0]), float(param[1]), float(param[2])))