I have the following function in Python (see it on Trinket):
def foo(a=1, b=2):
print(a);
print(b)
foo(,4)
When I run foo(,4), I want it to use the default when the first argument is not provided, and use the provided value if it's available. I.e. it should print:
1
4
Is this possible in Python? And, if so, how can I do this?
Use keyword arguments.
foo(b=4)
Related
I'm new to python actually started watching a tutorial, I know decent JavaScript, now here are my if statements
if str(fileType) == "V":
if (not windowTitle) and (not windowSize):
playVideo()
elif (windowTitle) and (windowSize):
playVideo(windowSize=int(windowSize), windowTitle=windowTitle)
elif (windowSize):
playVideo(int(windowSize=windowSize))
elif (windowTitle):
playVideo(windowTitle=windowTitle)
I want to know that if you want to skip the first argument and give second argument in python how would you do that, and I am giving arguments by writing their name = and the variable is that okay?
and after I check fileType I want to check if windowTitle and windowSize are empty am I doing it right?
and also I don't know what's in a variable if user skips (hits enter without writing anything), like in JavaScript it would be undefined
You are correctly using the syntax to pass arguments to a method in python. There are two two ways to pass arguments to a method:
By passing the argument's value directly - you need to pass the arguments in order.
By passing the argument's name-value pair (as you've used before) - the arguments do not need to be in order as long you've specified the name value pair. This is also known as keyword arguments.
If you want to skip first argument and only pass the second argument, you can use keyword arguments (mentioned in 2 above). Something like - playVideo(windowTitle='My Video')
Also if the user skips to pass an argument, in case of the method having the default value - it'll take the default value.
Yes, you can specify default values to function arguments. This makes the arguments optional (i.e, they do not have to be provided when the function is called).
def sum(a=0, b=0):
return a + b
print(sum(a=1)) #prints 1
print(sum(b=2)) #prints 2
print(sum(1,2)) #prints 3
print(sum()) #prints 0
I wanted to know how to work with an array as a functional argument in Python. I will show a short example:
def polynom(x, coeff_arr):
return coeff_arr[0]+ coeff_arr[1]+x +coeff_arr[2]*x**2
I obviously get the error that 2 positional arguments are needed but 4 were given when I try to run it, can anybody tell me how to do this accept just using (coeff_arr[i]) in the argument of the function?
Cheers
Your question is missing the code you use to call the function, but from the error I infer that you are calling it as polynom(x, coefficient1, coefficient2, coefficient3). Instead you need to either pass the coefficients as a list:
polynom(x, [coefficient1, coefficient2, coefficient3])
Or use the unpacking operator * to define the function as follows, which will take all positional arguments after x and put them into coeff_arr as a list:
def polynom(x, *coeff_arr):
(The unpacking operator can also be used in a function call, which will do the opposite of taking a list and passing its elements as positional arguments:
polynom(x, *[coefficient1, coefficient2, coefficient3])
is equivalent to
polynom(x, coefficient1, coefficient2, coefficient3)
)
In a nutshell, I'm trying to implement the following:
def function_one(value):
...
return a, b
def function_two(a, b):
...
And when I try
function_two(function_one(value))
I get an error message:
"function_two() missing 1 required positional argument: 'b'"
Is there a way to make this work as intended?
Thanks!
You have to unpack the tuple you return into separate arguments:
function_two(*function_one(value))
Another option would be changing function_two to accept a single argument and then unpack it inside the function or use it as-is. Whether this is a good idea or not depends on the context.
I am attempting to translate these lines of code:
error(nargchk(3, 4, nargin))
if nargout > 2, error('too many output parameters'); end
I want to translate it into Python. I have yet to find an equivalent for error (although I could perhaps just throw an exception here?), nargchk and nargin. Can anybody provide any input as to how this line of code can be translated?
There is nothing equivalent to nargin and nargchk because Python doesn't need it. You can define optional arguments in Python directly in the function definition. So for example:
def myfunc(a=1, b=3):
In this case it lets you set a and b to whatever you want, but if you don't define them it uses the default values you specified. So if you call myfunc(), it sets a to 1 and b to 3. If you call myfunc(5) it sets a to 5 and b to 3. You can also call by name, such as myfunc(b=10), which sets a to 1 and b to 10.
If you want argument to be required, just don't assign anything to them in the function definition. So in the following case, a is required while b is optional:
def myfunc(a, b=3):
If you want a user to be able to specify an arbitrary number of arguments, you can use *args (where args can be whatever variable you want. So this:
def myfunc(a=1, b=3, *args):
Will assign the first argument to a, the second argument to b, and any remaining arguments to args. You can also do this with arguments defined by name using **kwargs (again, kwargs can be any variable name). So this:
def myfunc(a=1, b=3, *args, **kwargs):
Does the same thing as the previous one, but any arguments provided by name other than a and b will go in kwargs (which is a dictionary).
So you don't need nargin and nargchk, generally you can just define the arguments you need and set default values for the optional ones. Then Python will automatically handle checking to make sure the required options are specified and there aren't too many arguments provided. If you need to capture an arbitrary number of additional arguments, just use *args and **kwargs and you can check that the len is correct yourself.
For nargout, there is no python equivalent because python requires all outputs be handled. So if you do return a, b, in myfun, a, and b must both be handled. You can simply ignore some, but you must explicitly do this. There is no easy way to check if those arguments are being ignored. So say we have this in myfunc:
return a, b, c, d
And you only want a, you can just do:
a, *_ = myfunc()
This puts the first returned value in a and dumps the remainder in the throw-away variable _ (just like *args captures all remaining arguments, *_ captures all remaining outputs). For, say, a and c, you can do:
a, _, c, _ = myfunc()
You can also index directly from a function call, something MATLAB doesn't allow. So this is also possible. So to get the first argument, you can do:
a = myfunc()[0]
So since it is easy in Python to get the returned values you want, and since implicit variable numbers of output values is an extreme pain to handle properly, Python doesn't support it. If you really want to change the number of output argument you can set an optional named argument in the function definition to do so. Since optional arguments are easy in Python, this isn't a huge issue. But it isn't usually needed.
As for errors, yes you just raise the appropriate exception. Python has different types of errors for different situations. raise TypeError('blah') is the correct approach for the wrong number of arguments, where blah is the message you want.
I am learning about functions in python and found many good tutorials and answers about functions and their types, but I am confused in some places. I have read the following:
If function has "=" then it's a keyword argument i.e (a,b=2)
If function does not have "=" then it's positional argument i.e (a,b)
My doubts :
What is the meaning of a required argument and an optional argument? Is the default argument also a keyword argument? (since because both contain "=")
Difference between the positional, keyword, optional, and required
arguments?
python official documentation says that there are two types of arguments. If so, then what are *args and **kargs (I know how they work but don't know what they are)
how *args and **kargs store values? I know how *args and
**kargs works but how do they store values? Does *args store values in a tuple and **kargs in the dictionary?
please explain in deep. I want to know about functions because I am a newbie :)
Thanks in advance
Default Values
Let's imagine a function,
def function(a, b, c):
print a
print b
print c
A positional argument is passed to the function in this way.
function("position1", "position2", "position3")
will print
position1
position2
position3
However, you could pass in a keyword argument as below,
function(c="1",a="2",b="3")
and the output will become:
2
3
1
The input is no longer based on the position of the argument, but now it is based on the keyword.
The reason that b is optional in (a,b=2) is because you are giving it a default value.
This means that if you only supply the function with one argument, it will be applied to a. A default value must be set in the function definition. This way when you omit the argument from the function call, the default will be applied to that variable. In this way it becomes 'optional' to pass in that variable.
For example:
def function(a, b=10, c=5):
print a
print b
print c
function(1)
and the output will become:
1
10
5
This is because you didn't give an argument for b or c so they used the default values. In this sense, b and c are optional because the function will not fail if you do not explicitly give them.
Variable length argument lists
The difference between *args and **kwargs is that a function like this:
def function(*args)
for argument in args:
print argument
can be called like this:
function(1,2,3,4,5,6,7,8)
and all of these arguments will be stored in a tuple called args. Keep in mind the variable name args can be replaced by any variable name, the required piece is the asterisk.
Whereas,
def function(**args):
keys = args.keys()
for key in keys:
if(key == 'somethingelse'):
print args[key]
expects to be called like this:
function(key1=1,key2=2,key3=3,somethingelse=4,doesnt=5,matter=6)
and all of these arguments will be stored in a dict called args. Keep in mind the variable name args can be replaced by any variable name, the required piece is the double asterisk.
In this way you will need to get the keys in some way:
keys = args.keys()
Optional arguments are those that have a default or those which are passed via *args and **kwargs.
Any argument can be a keyword argument, it just depends on how it's called.
these are used for passing variable numbers of args or keyword args
yes and yes
For more information see the tutorial:
https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions