Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.
(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)
Question on assigning variables inside an if statement
Python variable scope in if-statements - Stack Overflow
Python: using variables declared inside if statement - Stack Overflow
Question: Is it possible to pass variables between two different if statements
Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.
(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)
Yes, they're in the same "local scope", and actually code like this is common in Python:
if condition:
x = 'something'
else:
x = 'something else'
use(x)
Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.
In other words, Python does not have block-level scopes. Be careful, though, with examples such as
if False:
x = 3
print(x)
which would clearly raise a NameError exception.
Long term PHP developer here, started Python a few weeks back.
Aksing this here because I don't know the name of the programming pattern, so I can't really google it.
In PHP, it's possibleto assign a value to a variable inside an if statement:
if($myVar = callToFunction()) {
echo '$myVar evaluates to true';
}
else {
echo '$myVar evaluates to false';
}In Pyhton this doesn't seem to work, so right now I do
var myVar = callToFunction()
if myVar:
print('myVar evaluates to true')
else:
print('myVar evaluates to false')Has Python a way to use the PHP functionality? Especially when there is no else-block needed this saves a line of code, looks cleaner and let me write the syntax I'm used to, which makes life easier.
if statements don't define a scope in Python.
Neither do loops, with statements, try / except, etc.
Only modules, functions and classes define scopes.
See Python Scopes and Namespaces in the Python Tutorial.
Yes, in Python, variable scopes inside if-statements are visible outside of the if-statement. Two related questions gave an interestion discussion:
Short Description of the Scoping Rules?
and
Python variable scope error
Good Evening everyone,
i hope you had a nice day today. Just one more day till the weekend. Almost there. I am currently designing a program used for quantitative trading. And i have a simple question which would lead to the final success of my project. My question is: can you send variables between two if statements ? Or rather, can you pass one variable, that is generated when the first if condition is met, to the other if (elif) statement and use it for the respective if statement evaluation there ?
i would like to return the variable buying_price to the below located if condition.
I constantly receive the error message: referenced variable before assignment
Thanks for everyone that takes the time to help me with my issue! I highly appreciate it.
Code below for further understanding:
if((wma_indicator > ma_indicator) and (psar_indicator < current_price) and (macd > signal) and not has_position): #and rsi < 40 and macd > signal and and ema_short > ema_long
print("-------")
print("Buy Signal: creating market order for {}".format(data.symbol))
print("Buy value: ", buy_value, " at current market price: ", data.close[-4])
buy_order = order_market_value(symbol=data.symbol, value=buy_value)
print("buy_order", buy_order)
if buy_order.is_filled() == True:
buy_order.refresh()
buying_price = buy_order.executed_price
buying_price = float(buying_price)
print("buying_price", buying_price)
order_trailing_iftouched_amount(symbol=data.symbol, amount= -float(BNB_balance),trailing_percent=0.2, stop_price=buying_price)
state['buying_price'] = buying_price
return buying_price
if has_open_position(symbol ="BTCUSDT")==True:
SellingOrder(state.buying_price, has_position, wma_indicator, ma_indicator, current_price, psar_indicator, macd, signal)
def SellingOrder(buying_price, has_position, wma_indicator, ma_indicator, current_price, psar_indicator, macd, signal):
if ((wma_indicator < ma_indicator) and (buying_price < current_price) and (psar_indicator > current_price) and (macd < signal) and has_position): # or rsi > 70 #and has_position and macd < signal and ema_short < ema_long print("-------") has_open_position(symbol ="BTCUSDT")==True
logmsg = "Sell Signal: closing {} position with exposure {} at current market price {}"
print(logmsg.format(data.symbol,float(position.exposure),data.close_last))
close_position(data.symbol)
Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (isBig(y)) as a variable (x) in order to re-use it within the body of the condition:
if x := isBig(y): return x
I see somebody else has already pointed to my old "assign and set" Cookbook recipe, which boils down in its simplest version to:
class Holder(object):
def set(self, value):
self.value = value
return value
def get(self):
return self.value
h = Holder()
...
if h.set(isBig(y)): return h.get()
However, this was intended mostly to ease transliteration between Python and languages where assignment is directly supported in if or while. If you have "hundreds" of such check-and-return in a cascade, it's much better to do something completely different:
hundreds = isBig, isSmall, isJuicy, isBlah, ...
for predicate in hundreds:
result = predicate(y)
if result: return result
or even something like
return next(x for x in (f(y) for f in hundreds) if x)
if it's OK to get a StopIteration exception if no predicate is satisfied, or
return next((x for x in (f(y) for f in hundreds) if x)), None)
if None is the proper return value when no predicate is satisfied, etc.
Almost invariably, using (or even wishing for;-) the Holder trick/non-idiom is a "design smell" which suggests looking for a different and more Pythonic approach -- the one case where Holder is justified is exactly the special case for which I designed it, i.e., the case where you want to keep close correspondence between the Python code and some non-Python (you're transliterating a reference algorithm in Python and want it working first before refactoring it into a more Pythonic form, or you're writing Python as a prototype that will be transliterated into C++, C#, Java, etc, once it's working effectively).