Ternary operators , *args and **kwargs
Hey guys, welcome back to the Python basics tutorial! Today I'll tell you about ternary operators and args/kwargs.
Ternary operators
When your assigning a variable based on a condition, you'll use a if/else block. Well, you can fit it into one line too. The structure of a ternary operator in Python is:
var = value1 if condition else value 2
This may decrease readability though. Let's see an example:
if 3 < 2:
var = 3
else:
var = 4
# Can be shortened to:
var = 3 if 3 < 2 else 4
There's a significant decrease in size and readability.
*args and **kwargs
So far if you wanted to make an adder, you would specify two parameters. But if the user wanted to add three numbers? In that case, instead of adding a bunch of named arguments, you would use *args.
Basically, when you want an indefinite amount of arguments, instead of using positional arguments, you use *args:
def add(*args):
result = 0
for num in args:
result += num
return result
# OR you can do this:
def add(*args):
return sum(args)
Two things to note here, we only use a star with args when declaring it as a parameter, NOT when using it in the function. And, we also see a new function here: sum
. It just adds all the elements of the iterable (such as a list) that is given to it.
Remember, *args only takes arguments as positional ones, not named ones.
**kwargs is a bit different. It only takes named arguments. You use it the same way as *args. However, *args returns a tuple, while **kwargs returns a dictionary. So, if the user called your function like login(username='John', password='harrypotter')
, printing **kwargs would show {'username': 'John', 'password': 'harrypotter'}
and you can access the username with kwargs['username']
.
You've almost finished this course, just a few more stuff, and we'll be done.
Last updated
Was this helpful?