根据python中请求的元素数不同的返回语句

2024-10-04 03:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中的函数中执行类似的操作

def cool():
    if (user wants to receive one element):
        return 10
    if (user wants to receice two elements):
        return 4, 2 
 
a = cool()
print(a) # 10

x, y = cool()
print(x) # 4
print(y) # 2

Tags: to函数returnifdefelementselementone
3条回答

可以将其作为参数传递给函数

def cool(return_values):
    if return_values == 1:
        return 10
    elif return_values == 2:
        return 4, 2 
 
a = cool(1)
print(a) # 10

x, y = cool(2)
print(x) # 4
print(y) # 2

可以使用数组

def cool():
    if (user wants to receive one element):
        return [10]
    if (user wants to receice two elements):
        return [4, 2] 
 
a = cool()
for value in a:
    print(value)
#or just
print(a)

#if you want everything to print on one line:
outputString = ""
for value in a:
    outputString += str(value) + " "
    #might have to do outputString = outputString + str(value) + " "
print(outputString)

您可以使用一个列表并将其拼接起来来完成此操作。下面的函数获取一个列表,并在用户返回计数时对其进行切片

def returnCount(returns,numbers):
    return numbers[:returns]
print(returnCount(3,[1,2,3,4,5]))

输出

[1,2,3]

相关问题 更多 >