Arguments and Arguments in Python

thumbnail

Know the difference!

This question is now commonplace in interviews with nearly every big tech company.

simply put,

Use parameters in function definitions,

Instead use parameters in function calls.

A good way to remember this is with scenarios - when you play a game, there are many difficulty levels - high, medium, low. Here, difficulty level is a parameter, and low, medium, and high are parameters. Likewise, when you adjust settings on your TV, you adjust brightness and contrast. Here, brightness and contrast are parameters, and numbers from 1 to 10 are parameters.

There are 4 versions:

  • default parameters
  • positional parameters
  • keyword arguments
  • Arbitrary arguments

Default parameters:

Let's create a small function power that returns the value of the first number raised to the power of the second number. If I pass only one value, the code crashes.

To prevent the code from crashing, we use default parameters, where we initialize the default value to our parameter so that if the user forgets to pass any parameter when calling the function, the default value will be passed instead.

MMMMMM

Positional parameters:

This means that the order in which you pass the parameters, the values ​​will be passed in the parameters in the function definition in the same order. For example, power(2,3) means a=2 and b=3, not the other way around.

Keyword arguments:

With so many functions, it's nearly impossible to remember the order/order of each parameter in the definition. So in most cases, people just remember the parameter names and not the order. This is where keyword arguments come in.

If you explicitly specify that you want b to have a value of 2 and a to have a value of 3, then you are using keyword arguments. A good use case for such a parameter would be a complex function with many parameters.

Note : keyword arguments take precedence over

Arbitrary parameters:

There are some features that might surprise you. For example, have you ever wondered how the print() function can receive as many arguments as you give it without throwing an error? This is because functions like print() pass in variadic arguments.

Hope all your doubts about parameters and parameters in python are now cleared up. If you still have any questions, feel free to get in touch or ask in the comments.

happy learning!

Latest Programming News and Information | GeekBar

Related Posts