我应该在add()和sub()中用作if语句中的参数



我想使用用户输入进行计算,并且我已经定义了add(*args)和sub(*args),但是如果我在if语句中的add()中编写*args错误:未定义的args如果写m,则它显示我的价值,而不是总数....

def add(*args):
    total = 0
    for a in args:
        total += a
    print(total)
def sub(*args):
    total = 0
    for a in args:
        total -= a
    print(total)
print('1-addn2-sub')
n=int(input("enter choice:"))
counter = int(input("enter no of No.to be calculated:"))
if n == 1:
    for i in range(counter):
        m=int(input("enter no."))
    add()
elif n == 2:
    for i in range(counter):
        m = int(input("enter no."))
    sub()
else:
    print("invalid")

调用addsub功能时,您不会传递任何内容,也没有保存所有用户输入。您需要将用户输入保存到列表,然后将列表传递给功能。请注意,您还需要从要通过列表中的功能签名中删除*,而不是任意数量的参数。

def add(args):
    total = 0
    for a in args:
        total += a
    print(total)
def sub(args):
    total = 0
    for a in args:
        total -= a
    print(total)
.
.
if n == 1:
    li = []
    for i in range(counter):
        li.append(int(input("enter no.")))
    add(li)
elif n == 2:
    li = []
    for i in range(counter):
        m = li.append(int(input("enter no.")))
    sub(li)

请记住,您可以使用发电机使代码短(不一定更可读):

if n == 1:
    add(int(input()) for i in range(counter))
elif n == 2:
    sub(int(input()) for i in range(counter))

最新更新