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

Answer from Luke Maurer on Stack Overflow
🌐
Dataquest
dataquest.io › home › blog › tutorial: using if statements in python
How to Use IF Statements in Python (if, else, elif, and more) – Dataquest
November 24, 2024 - If instead you place pass in the if statement, Python won’t throw any error and will pass to any code you have below the if statement. This works even if you have other conditions below the first if statement. # With pass num = 4 if num == 3: pass elif num == 4: print("The variable num is 4.") else: print("The variable num is neither 3 nor 4.")
🌐
W3Schools
w3schools.com › python › python_conditions.asp
Python If Statement
In this example we use two variables, ... so we print to screen that "b is greater than a". The if statement evaluates a condition (an expression that results in True or False)....
Discussions

Question on assigning variables inside an if statement
Walrus operator := added in 3.8 make sure you are using a relatively modern python version and using guides which are targeting at least 3.12 if myVar := callToFunction(): print('myVar evaluates to true') else: print('myVar evaluates to false') More on reddit.com
🌐 r/learnpython
18
7
January 30, 2026
Python variable scope in if-statements - Stack Overflow
In Python, are variable scopes inside if-statements visible outside of the if-statement? (coming from a Java background, so find this a bit odd) In the following case, name is first defined inside... More on stackoverflow.com
🌐 stackoverflow.com
Python: using variables declared inside if statement - Stack Overflow
for case in log: for event in case: if event in process_model: index = process_model.index(event) else: print(event, index) ---------- output----------- NameError: n... More on stackoverflow.com
🌐 stackoverflow.com
Question: Is it possible to pass variables between two different if statements
you can, but only if you bother to initialize the variable to something as the fallback value. Having variables created conditionally is simply bad design. For example you could go with something like this variable = None if condition: variable = value if variable is not None and some_other_condition: do stuff btw, stop using == True all over the place. It's tautology. if x.is_filled() == True: is more or less equivalent to if x.is_filled():, because if you substitute the left side with its value for the positive case, you get if True == True: which is as good as if True: More on reddit.com
🌐 r/learnpython
4
1
May 6, 2021
🌐
Sololearn
sololearn.com › en › Discuss › 2399358 › can-we-declare-a-variable-inside-if-statement
Can we declare a variable inside if statement? | Sololearn: Learn to code for FREE!
You simply must be careful with the scoping rules (a variable declared in a 'if' block might not be usable outside this block). [Edit] Do you actually mean declaring a variable in the condition? Or in the following block? ... python allows creation of variables in an if...
🌐
Quora
quora.com › How-can-I-add-to-a-variable-in-an-if-statement-in-python
How to add to a variable in an 'if statement' in python - Quora
Answer (1 of 4): As the others have attempted to show, your problem lies in the “type” of the data contained in that variable. Even though Python uses dynamic types, it uses strong types. I.e. it adjusts the type to what is input/created, but it doesn’t simply convert willy-nilly between ...
🌐
Reddit
reddit.com › r/learnpython › question on assigning variables inside an if statement
r/learnpython on Reddit: Question on assigning variables inside an if statement
January 30, 2026 -

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.

🌐
Codecademy
codecademy.com › forum_questions › 5307468f8c1cccb139002c8b
8/11 - creating variables inside if statements | Codecademy
July 1, 2018 - Honestly, I didn’t do it that way, and don’t know what the benefit of it is, but if you want to do it that way here is what you need to have for the if part: if len(original) > 0 and original.isalpha():‌ word = original.lower()‌ first = str(word)[0]‌ print original It isn’t letting me use the input code button. Also you MUST put the variable “word” into a string before you try to get the first letter of it.
🌐
YouTube
youtube.com › watch
Python Tutorial 1 - Variables and If Statements - YouTube
Help to support the channel if you are feeling super kind: https://www.patreon.com/dapperdinoJoin our Discord: https://discord.gg/sn9xXK4In this video I show...
Published: May 10, 2018
Find elsewhere
🌐
Dot Net Perls
dotnetperls.com › if-python
Python - if Examples - Dot Net Perls
May 30, 2025 - Here We store the result of an expression in the "all" variable. We then test it twice. ... The if-statement is helpful with a tuple. In this example, we use a tuple directly inside the if-statement. The method test() prints "Match" if its argument is 0, 2 or 4. def test(x): # Test x with tuple syntax. if x in ( ... Let us consider the truth of things. Python considers some values True, in an if-statement, and others false.
🌐
Mimo
mimo.org › glossary › python › if-statement
Python If Statement: Master Conditional Logic | Learn Coding
Use == for Equality: When checking if two values are equal, use the double equals sign (==). A single equals sign (=) is for assigning a value to a variable. Indentation is Mandatory: Python uses indentation (whitespace) to define code blocks. The code indented under an if, elif, or else statement is what will be executed.
🌐
Reddit
reddit.com › r/learnpython › question: is it possible to pass variables between two different if statements
r/learnpython on Reddit: Question: Is it possible to pass variables between two different if statements
May 6, 2021 -

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)

Top answer
1 of 7
190

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
2 of 7
24

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

🌐
Guru99
guru99.com › home › python › python conditional statements: if…else, elif & switch case
Python Conditional Statements: IF…Else, ELIF & Switch Case
June 11, 2026 - Code Line 4: Prints the value of st and gives the correct output. A nested if statement places one if statement inside another, which is useful when a decision depends on a second condition.
🌐
Python.org
discuss.python.org › python help
Define variable within elif statement - Python Help - Discussions on Python.org
July 11, 2022 - Hi all, I am trying to define a variable within an elif statment, but I suspect I messed up the syntax or worse, any help would be much appreciated. My code is: for key in question_access: if (key['device']['profile']['id']) == 155975: print('true') elif (key['device']['profile']['id']) != 155975: s = (key['device']['id']) print(s) This works perfectly fine, however, if I try to use the same variable (s) further down in my code, it says (s) is not defined, is th...
🌐
Quora
quora.com › I-m-programming-in-Python-and-when-I-write-an-if-statement-I-can-t-use-the-sign-to-assign-a-new-value-to-a-variable-Why
I’m programming in Python and when I write an if statement, I can’t use the = sign to assign a new value to a variable. Why? - Quora
Answer (1 of 2): In Python, assignment (using the `=` operator) is not allowed inside an expression, and when you write an if statement the syntax is : [code]if : [/code]As you can see the piece after the ‘if’ is an expression and therefore cannot include an assignmen...
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.15.0 documentation
As well as the while statement just introduced, Python uses a few more that we will encounter in this chapter. if Statements: Perhaps the most well-known statement type is the if statement. For exa...
🌐
BeginnersBook
beginnersbook.com › 2018 › 01 › python-if-statement-example
Python If Statement explained with examples
March 29, 2019 - If the outcome of condition is true then the statements inside body of ‘if’ executes, however if the outcome of condition is false then the statements inside ‘if’ are skipped. Lets take another example to understand this: flag = False if flag: print("You Guys") print("are") print("Awesome") The output of this code is none, it does not print anything because the outcome of condition is ‘false’. In the above examples, we have used the boolean variables in place of conditions.
🌐
Studytonight
studytonight.com › python-howtos › scope-of-the-variable-initialised-in-the-if-statement
Scope of the variable initialised in the if statement - Studytonight
February 9, 2021 - In Python, so long as the variable exists at the time you require it, no exception is thrown. Here, b is not initialized or declared before the if condition. b is initialized inside if block and it can be used outside the if block locally throughout the program. #local varaible outside if a = 2 #check for an expression if(a==2): #local variable inside if b = a+2 print(b) ... In this case, the expression (a==3) is False, so the statement inside if does not executes.