Pin-Jiun / Python

Python Document
0 stars 0 forks source link

28-Star or Asterisk operator * and ** #28

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

Multiplication and Exponentiation

In Multiplication, we multiply two numbers using Asterisk / Star Operator as infix an Operator. Using two(**) Star Operators we can get the exponential value of any integer value.


# using asterisk
mul = 5 * 7
print (mul)

a = 5
b = 3

# using asterisk
result = a ** b
print(result)

Multiplication of a list : With the help of ‘ * ‘ we can multiply elements of a list, it transforms the code into single line.

# using asterisk
list = ['geeks '] * 3

print(list)
['geeks ', 'geeks ', 'geeks ']

Unpacking a function using positional argument.

可以將list和tuple進行unpack

This method is very useful while printing your data in a raw format (without any comma and brackets ).

arr = ['sunday', 'monday', 'tuesday', 'wednesday']

# without using asterisk
print(' '.join(arr))

# using asterisk
print (*arr)
sunday monday tuesday wednesday
sunday monday tuesday wednesday

同理 ** 是拆解 Dict

dt = {'sep': ' # ', 'end': '\n\n'}
print('hello', 'world', **dt)
# 等同於 print('hello', 'world', sep=' # ', end='\n\n')

Passing a Function Using with an arbitrary number of keyword arguments

Here a double asterisk( ) is also used as kwargs, the double asterisks allow passing keyword arguments. This special symbol is used to pass a keyword arguments and variable-length argument lists. It has many uses, one such example is illustrated below

預設參數

一般的定義方法就不多說了,直接來看有預設值的參數:

def plus(a, b, c=None):
    res = a + b + (c if c else 0)
    return res

預設參數的用處通常是實作函式重載用的,可以使一個函式在接受引數時更有彈性,而要注意的語法問題是:預設參數在函式定義時一定要放在非預設參數的後面。

但如果我們想實作無限版的 plus() 函式呢?總不可能一直增加預設參數吧! 這時候我們可以用「*」來將引數收集到一個 tuple 中。

*-收集至 Tuple

def plus(*nums):
    res = 0
    for i in nums:
        res += i
    return res

透過 * 收集的引數會被放到一個 tuple 中,所以我們可以使用 for 來對它進行迭代。

這樣就可以理解為什麼要使用 *args 這個參數了

但是 **kwargs 又是什麼呢?我們要先從關鍵字引數來說起:

關鍵字引數 Keyword Argument

# using asterisk
def food(**kwargs):
  for items in kwargs:
    print(f"{kwargs[items]} is a {items}")

food(fruit = 'cherry', vegetable = 'potato', boy = 'srikrishna')
cherry is a fruit
potato is a vegetable
srikrishna is a boy

Just another example of using **kwargs, for much better understanding.

# using asterisk
def food(**kwargs):
  for items in kwargs:
    print(f"{kwargs[items]} is a {items}")

dict = {'fruit' : 'cherry', 'vegetable' : 'potato', 'boy' : 'srikrishna'}
# using asterisk
food(**dict)
cherry is a fruit
potato is a vegetable
srikrishna is a boy

https://www.geeksforgeeks.org/python-star-or-asterisk-operator/