An Interest In:
Web News this Week
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
July 4, 2020 11:50 pm GMT
Original Link: https://dev.to/doublepicebs/python-fun-function-facts-joj
Python: Fun Function Facts
(Assuming that) we all know what a python function is; I want to show some hacks that might help you.
(1) Optional parameters
def hi(name, age=18): print(f"Hi {name} who is {age} years old!")
Here, when calling this function, you don't have to give a value to the age parameter, as it will default to 18. However giving a value to age will override the default value.
hi("Mahdi")# >>> Hi Mahdi who is 18 years old!hi("Magdi", 25)# >>> Hi Magdi who is 25 years old!
Note: optional arguments/parameters must come at the end, so this won't work:
def hi(age=14, name): print(f"Hi {name} who is {age} years old!")hi(15, "Mohamed")# >>> Syntax Error: non-default argument follows default argument
It's a good practice to let the default values None
.
(2) You can write parameters in a different order
Take a look at this function:
def salut(fromPerson, toPerson): print(f"Hi from {fromPerson} to {toPerson}")salut("Magdi", "Shady")# >>> Hi from Magdi to Shady
This is also valid:
salut(toPerson="Shady", fromPerson="Magdi")# >>> Hi from Magdi to Shady
It prints the same result as before. This feature is kinda cool, and it improves readability; even if you still write them in order.
Ok, that's good for now. Hope I helped you know something new, or clarified it. See you soon!
Original Link: https://dev.to/doublepicebs/python-fun-function-facts-joj
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To