How do I fix this function syntax? - python

Iv'e tried searching up the problem to no avail, so I chose to come on stack overflow to ask this problem.
def Year(2015):
^
Syntax Right here
Year = 2015
return Year
Year = '2015'
print(Year)

I am not sure what are you intending to do, but what you seem to intend to do is to define Year(...) as function. Well, in Python when defining function you need to put in brackets a parameter that it would be used somewhere inside the function.
Def Year(Year_Param): # Do stuff return Year_Param
So in this is how a function is defined in Python, where Year_Param is a Parameter that you give when calling the function Year().
If what you are looking for is that the function Year uses default value for a Parameter in case it is called without Parameters, then you shoud write def Year(Year_Param = 2015): # Your stuffs here
In this case, if you call Year() like this without putting anything in middle of the brackets it would automatically be like Year(2015)

Related

Bracket not showing as closed in Python 3

I'm just starting to learn Python 3.9 as my first language. I have been fighting with this error for a while now, and I can't figure out what the issue is.
Here's what I'm working on:
def eval_express(eqstring[0], eqstring[1], eqstring[2]):
eqstring[0], eqstring[2] = float(eqstring[0]), float(eqstring[2])
return opdict[eqstring[1]](eqstring[0], eqstring[2])
I'm receiving an error that the "(" after eval_express is not closed, but as far as I can tell it is. At first, I thought it was just a glitch, but despite numerous attempts to rewrite it, increase/decrease the number of arguments, etc. it persisted. The error cropped up after I modified the arguments from variables to list items, but I don't see why that would affect it. Can anyone provide some clarification on what the program's getting hung up on?
Thank you for your help!
You are using square brackets inside the function parameters, which is not valid. Valid code would be:
def eval_express(eqstring0, eqstring1, eqstring2):
eqstring0, eqstring2 = float(eqstring0), float(eqstring2)
return opdict[eqstring1](eqstring0, eqstring2)
although you should probably use more descriptive parameter names.
You can't use parameter[] notation when entering a parameter to a function. Instead just use parameter, or you will have to do something like.
def eval_express(eqstring):
eqstring[0], eqstring[2] = float(eqstring[0]), float(eqstring[2])
return opdict[eqstring[1]](eqstring[0], eqstring[2])
Now you have to pass an array as the function parameter.

Running function code only when NOT assigning output to variable?

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.

Why is there a syntax error in my Python function?

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.

Best practice for using parentheses in Python function returns?

I'm learning Python and, so far, I absolutely love it. Everything about it.
I just have one question about a seeming inconsistency in function returns, and I'm interested in learning the logic behind the rule.
If I'm returning a literal or variable in a function return, no parentheses are needed:
def fun_with_functions(a, b):
total = a + b
return total
However, when I'm returning the result of another function call, the function is wrapped around a set of parentheses. To wit:
def lets_have_fun():
return(fun_with_functions(42, 9000))
This is, at least, the way I've been taught, using the A Smarter Way to Learn Python book. I came across this discrepancy and it was given without an explanation. You can see the online exercise here (skip to Exercize 10).
Can someone explain to me why this is necessary? Is it even necessary in the first place? And are there other similar variations in parenthetical syntax that I should be aware of?
Edit: I've rephrased the title of my question to reflect the responses. Returning a result within parentheses is not mandatory, as I originally thought, but it is generally considered best practice, as I have now learned.
It's not necessary. The parentheses are used for several reason, one reason it's for code style:
example = some_really_long_function_name() or another_really_function_name()
so you can use:
example = (some_really_long_function_name()
or
another_really_function_name())
Another use it's like in maths, to force evaluation precede. So you want to ensure the excute between parenthese before. I imagine that the functions return the result of another one, it's just best practice to ensure the execution of the first one but it's no necessary.
I don't think it is mandatory. Tried in both python2 and python3, and a without function defined without parentheses in lets_have_fun() return clause works just fine. So as jack6e says, it's just a preference.
if you
return ("something,) # , is important, the ( ) are optional, thx #roganjosh
you are returning a tuple.
If you are returning
return someFunction(4,9)
or
return (someFunction(4,9))
makes no difference. To test, use:
def f(i,g):
return i * g
def r():
return f(4,6)
def q():
return (f(4,6))
print (type(r()))
print (type(q()))
Output:
<type 'int'>
<type 'int'>

Parentheses in Python's functions and decorators(wrappers)

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())

Categories