** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
positional_augment_tuple
def say_something(word1, word2, word3):
print(word1)
print(word2)
print(word3)
say_something('Hi!', 'Mike', 'Nancy')
result
Hi!
Mike
Nancy
Of course, you can set it like word1
, word2
, word3
one by one, but
There is a way to do it well by tupleting the positional arguments.
positional_augment_tuple
def say_something(*args):
print(args)
say_something('Hi!', 'Mike', 'Nancy')
result
('Hi!', 'Mike', 'Nancy')
By prefixing the argument to be inserted in ()
of say_something ()
, you can add *
.
You can tuple the arguments that come in there.
By printing the tuple generated by this by turning the for loop further, the previous one can be reproduced.
positional_augment_tuple
def say_something(*args):
for arg in args:
print(arg)
say_something('Hi!', 'Mike', 'Nancy')
result
Hi!
Mike
Nancy
positional_augment_tuple
def say_something(word, *args):
print('word =', word)
for arg in args:
print('arg =', arg)
say_something('Hi!', 'Mike', 'Nancy')
result
word = Hi!
arg = Mike
arg = Nancy
I added word
as an argument to say_something'.
Then, only the first argument Hi!
Enters word
first,
It can be seen that the subsequent arguments Mike
and Nancy
go into * args
.
positional_augment_tuple
def say_something(*args, word):
print('word =', word)
for arg in args:
print('arg =', arg)
say_something('Hi!', 'Mike', 'Nancy')
result
say_something('Hi!', 'Mike', 'Nancy')
TypeError: say_something() missing 1 required keyword-only argument: 'word'
If you put * args
first and word
after, you will get an error.
Be sure to use the normal arguments → *
in that order.
Recommended Posts