Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 4, 2020 11:50 pm GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To