Assume for example that I am writing a function for the following code (in pandas module):
myData.sort_values(by=myVariable, ascending=False)
Now, I want to create a function whose variables are data, variable and ascending.
sort(data=mydata, variable=myvariable, ascending=False)
The below function gives an error, because whether ascending is true or false is not given in second line:
def sort(data,variable,ascending=False):
data.sort_values(by=variable, ascending)
Although it would work, I do not want to change variable name such as:
def sort(data,variable,asc=False):
data.sort_values(by=variable, ascending=asc)
One last approach would be to create a variable inside the function:
def sort(data,variable,ascending=False):
asc = ascending
data.sort_values(by=variable, ascending=asc)
but it looks somewhat confusing. Is there an alternative approach to use the same variable in this case?
Note: the question is not related with pandas module, it is just an example.
Edit: I have clearly stated my problem and showed what I have tried. I did not understand the reason for the downvote.
have you tried:
def sort(data,variable,ascending=False):
data.sort_values(by=variable, ascending=ascending)
The below function gives an error, because whether ascending is true or false is not given in second line:
def sort(data,variable,ascending=False):
data.sort_values(by=variable, ascending)
No; it gives an error because positional arguments cannot come after keyword arguments. Like the error message says: SyntaxError: positional argument follows keyword argument.
The way to fix this is as in the other answer, using ascending=ascending. The idea is that the arguments for the function call are in a separate namespace from the current local variables.
If it "didn't work", then you need to ask a new question and properly explain the expected and actual results, with a complete example that other users can test locally.
Related
My code for the above problem statement is:
def firstletter(x):
x=input()
print(x[0])
firstletter()
But I'm getting this error
Oops, your solution is incorrect.
TypeError: firstletter() missing 1 required positional argument: 'x'
can anyone help me with that.
your function isn't taking any parameters at the moment. Below is a link to some documentation that explains what functions and function parameters are.
python functions
The correct answer to this is:
def firstletter(x):
print(x[0])
because the compiler already had custom input it was just checking whether the function had a parameter passed, and one character is taken or not.
p.s.: in udemy we are not able to see if there are test cases or custom inputs.
I am looking for a way in python to stop certain parts of the code inside a function but only when the output of the function is assigned to a variable. If the the function is run without any assignment then it should run all the inside of it.
Something like this:
def function():
print('a')
return ('a')
function()
A=function()
The first time that I call function() it should display a on the screen, while the second time nothing should print and only store value returned into A.
I have not tried anything since I am kind of new to Python, but I was imagining it would be something like the if __name__=='__main__': way of checking if a script is being used as a module or run directly.
I don't think such a behavior could be achieved in python, because within the scope of the function call, there is no indication what your will do with the returned value.
You will have to give an argument to the function that tells it to skip/stop with a default value to ease the call.
def call_and_skip(skip_instructions=False):
if not skip_instructions:
call_stuff_or_not()
call_everytime()
call_and_skip()
# will not skip inside instruction
a_variable = call_and_skip(skip_instructions=True)
# will skip inside instructions
As already mentionned in comments, what you're asking for is not technically possible - a function has (and cannot have) any knowledge of what the calling code will do with the return value.
For a simple case like your example snippet, the obvious solution is to just remove the print call from within the function and leave it out to the caller, ie:
def fun():
return 'a'
print(fun())
Now I assume your real code is a bit more complex than this so such a simple solution would not work. If that's the case, the solution is to split the original function into many distinct one and let the caller choose which part it wants to call. If you have a complex state (local variables) that need to be shared between the different parts, you can wrap the whole thing into a class, turning the sub functions into methods and storing those variables as instance attributes.
number=list(map(lambda x:int(x), input().split()))
first=".|."
second='-'
median=((number[0]-1)//2)+1
def Door(number[0],number[1]): # <<-- this one is resulting in a syntax error.
So I still fail to understand what is wrong with this code.
Can you please help me?
Thank you.
In this line:
def Door(...):
you are defining a function. You define a function with variables as parameters. When you call the function you pass it values.
What I think you are planning to do is first define Door() and then later call it with the values number[0] and number[1].
So begin your definition of the function like this:
def Door(a,b):
and when you want to call it, then you pass it the values number[0] and number[1], like this:
mydoor = Door(number[0],number[1])
Then, inside Door(), when your code refers to a and b, it is using the values of
number[0] and number[1]. This disconnect is so that the function can be called from different places with different parameters.
This applies even if you are defining the function just to modularize your code, and you only ever plan to call it from one place.
For example, I'd like to do something like: greet(,'hola'), where greet is:
def greet(person='stranger', greeting='hello')
This would help greatly for testing while writing code
Upon calling a function you can use the variable names to make it even more clear what variable will assume which value. At the same time, if defaults are provided in the function definition, skipping variables when calling the function does not raise any errors. So, in short you can just do this:
def greet(person='stranger', greeting='hello')
print('{} {}'.format(greeting, person))
return
greet(greeting='hola') # same as greet(person='stranger', greeting='hola')
# returns 'hola stranger'
Note that, as I said above this would not work if for example your function definition was like this:
def greet(person, greeting)
print('{} {}'.format(greeting, person))
return
Since in this case, Python would complain saying that it does not know what to do with person; no default is supplied..
And by the way, the problem you are describing is most likely the very reason defaults are used in the first place
Without knowing the other parameters, and only knowing that the parameter you want to change is in second position you could use the inspect module to get function signature & associated default values.
Then make a copy of the default values list and change the one at the index you want:
import inspect
def greet(person='stranger', greeting='hello'):
print(person,greeting)
argspec = inspect.getargspec(greet)
defaults = list(argspec.defaults)
defaults[1] = "hola" # change second default parameter
greet(**dict(zip(argspec.args,defaults)))
Assuming that all parameters have default values (else it shifts the lists an that fails) that prints:
stranger hola
Thanks for reading my question. As I'm still new to Python, I would like to ask about the () in Python.
def addOne(myFunc):
def addOneInside():
return myFunc() + 1
return addOneInside # <-----here is the question
#addOne
def oldFunc():
return 3
print oldFunc()
Please note that on line four, although the programme returns a function, it does not need parentheses(). Why does it NOT turn out with an error for syntax error? Thank you very much for your answers in advance!
The parentheses are used to run a function, but without them the name still refers to the function just like a variable.
return myFunc() + 1
This will evaluate the myFunc function, add 1 to its value and then return that value. The brackets are needed in order to get the function to run and return a numeric value.
return addOneInside
This is not actually running addOneInside, it is merely returning the function as a variable. You could assign this to another name and store it for later use. You could theoretically do this:
plusOne = addOneInside
plusOne()
And it will actually call the addOneInside function.
The particular instance in your initial question is known as a Decorator, and it's a way for you to perform code on the parameters being passed to your function. Your example is not very practical, but I can modify it to show a simple use case.
Let's say that you want to only have positive numbers passed to your function. If myFunc is passed a negative number, you want it to be changed to 0. You can manage this with a decorator like this.
def addOne(myFunc):
def addOneInside(num):
if num < 0:
num = 0
return myFunc(num)
return addOneInside # <-----here is the question
#addOne
def oldFunc(number):
return number
To explain, the #addOne is the decorator syntax, and it's attaching the addOneInside function to be called on the argument/s of oldFunc whenever you call it. So now here's some sample output:
oldFunc(-12)
>>> 0
oldFunc(12)
>>> 12
So now you could add logic to oldFunc that operates independently of the parameter parsing logic. You could also relatively easily change what parameters are permitted. Maybe there's also a maximum cap to hit, or you want it to log or note that the value shouldn't be negative. You can also apply this decorator to multiple functions and it will perform the same on all of them.
This blogpost explained a lot for me, so if this information is too brief to be clear, try reading the long detailed explanation there.
Your indentation in function addOne() was incorrect (I have fixed it), but I don't think that this was your problem.
If you are using Python3, then print is a function and must be called like this:
print(oldFunc())