“Args in Python” Kod odpowiedzi

Args in Python

def add(*args):
    total = 0
    for i in args:
        total += i
    
    return total

print(add(5,5,10))
King Generous

Args in Python

# if args is not passed it return message
# "Hey you didn't pass the arguements"

def ech(nums,*args):
    if args:
        return [i ** nums for i in args]  # list comprehension
    else:
        return "Hey you didn't pass args"
    
print(ech(3,4,3,2,1))
King Generous

Args in Python

# normal parameters with *args

def mul(a,b,*args): # a,b are normal paremeters
    multiply = 1
    for i in args:
        multiply *= i
        
    return multiply

print(mul(3,5,6,7,8))   # 3 and 5 are being passed as a argument but 6,7,8 are args 
King Generous

Args in Python

def func(*args):
    x = []          # emplty list
    for i in args:
        i = i * 2
        x.append(i)  
        y = tuple(x) # converting back list into tuple
    return y
        
tpl = (2,3,4,5)        
print(func(*tpl))
King Generous

Args in Python

def mul(*args):  # args as argument
    multiply = 1
    for i in args:
        multiply *= i
        
    return multiply

lst = [4,4,4,4]
tpl = (4,4,4,4)    

print(mul(*lst))  # list unpacking
print(mul(*tpl)) # tuple unpacking
King Generous

Args in Python

def display(a,b,c):
    print("arg1:", a)
    print("arg2:", b)
    print("arg3:", c)

lst = [2,3]
display(1,*lst)
King Generous

Args in Python

# if args is not passed it return message
# "Hey you didn't pass the arguements"

def ech(num,*args):  
    if args:
        a = []
        for i in args:
            a.append(i**num)
        return a                 # return should be outside loop
    else:
        return "Hey you didn't pass the arguements"     # return should be outside loop
    
print(ech(3))
King Generous

Args in Python

def wrap(*args):
        lis = list(args)  # it is important to convert args into list before looping, args take tuple as a argument 
        for i in range(len(lis)):
            lis[i] = lis[i] * 2
        args = tuple(lis)
        return args
print(wrap(2,3,4,5,6))
King Generous

Args in Python

def func2(*args):
    for i in args:
        print(i * 2)
        
func2(2,3,4,5)
King Generous

Odpowiedzi podobne do “Args in Python”

Pytania podobne do “Args in Python”

Więcej pokrewnych odpowiedzi na “Args in Python” w Python

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu