Mar-10-2022, 12:40 PM
You can use default arguments,
In the function specification, you can see that hydrogen and oxygen are assigned to
Checking a
So if you don't set hydrogen or oxygen, those branches are not executed, because they are
The += is an inline addition. This works also with
str
concatenation and format-strings.def hydrocarbon(carbon, hydrogen=None, oxygen=None): result = f"C{carbon}" if hydrogen: result += f"H{hydrogen}" if oxygen: result += f"O{oxygen}" return resultThis does only generate the
str
and does not check, if anything is valid.In the function specification, you can see that hydrogen and oxygen are assigned to
None
.Checking a
None
of truthiness returns False
.So if you don't set hydrogen or oxygen, those branches are not executed, because they are
None
.The += is an inline addition. This works also with
str
.greeting = "Hello" greeting += " " greeting += "World"The
f
in front of the quotes marks the str
literal as format string.name = "all" # name is replaced by the str content of name greeting = f"Hello {name}"
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!