I'm surprised no one offered this answer. It's not as "built-in" as Ruby's ||= but it's basically equivalent and still a one-liner:

foo = foo if 'foo' in locals() else 'default'

Of course, locals() is just a dictionary, so you can do:

foo = locals().get('foo', 'default')
Answer from Keith Devens on Stack Overflow
🌐
LabEx
labex.io › tutorials › python-how-to-implement-conditional-assignment-421293
Python - How to implement conditional assignment
Conditional assignment is a powerful technique in Python that allows developers to assign values based on specific conditions. This approach provides a concise and readable way to handle variable assignments dynamically.
Discussions

Python Conditional Variable Setting - Stack Overflow
For some reason I can't remember how to do this - I believe there was a way to set a variable in Python, if a condition was true? What I mean is this: value = 'Test' if 1 == 1 Where it would hope... More on stackoverflow.com
🌐 stackoverflow.com
A question about conditional variable assignment.
No, but variable += 1 if condition else -1 would. More on reddit.com
🌐 r/Python
6
2
May 26, 2014
Best way to do conditional assignment in python - Stack Overflow
I tend to use this a lot, but it's ugly: a = (lambda x: x if x else y)(get_something()) So I wrote this function: def either(val, alt): if val: return val else: return alt... More on stackoverflow.com
🌐 stackoverflow.com
Python conditional variable assignment - Stack Overflow
Morning all, Can someone advise, is it possible to achieve something like this: def myFunction(someParam) if someParam == 1: return "This and that" else: return None someVariab... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module2_EssentialsOfPython › ConditionalStatements.html
Conditional Statements — Python Like You Mean It
There are eight comparison operations in Python: The first six of these operators are familiar from mathematics: ... Note that = and == have very different meanings. The former is the assignment operator, and the latter is the equality operator: >>> x = 3 # assign the value 3 to the variable `x` >>> x == 3 # check if `x` and 3 have the same value True
🌐
The Teclado Blog
blog.teclado.com › python-pythons-ternary-operator
Python's "Ternary Operator" - The Teclado Blog
In this case we have some value bound to the variable x, and we check if the value of x is less than 10. If it is, we assign the number to value; otherwise, we assign the string, "Invalid value". We can see a case where the value of x is not less than 10 below: x = 10 value = x if x < 10 else "Invalid value" # Invalid value · Let’s break down the syntax. First we start with the value to return if the condition is True.
Find elsewhere
🌐
pythontutorials
pythontutorials.net › blog › python-conditional-variable-setting
How to Set Variables Conditionally in Python: A Guide to Ternary Operators and Multiple Conditions — pythontutorials.net
Unlike many other languages (e.g., C/C++ uses condition ? true_value : false_value), Python’s ternary operator has a unique syntax: variable = value_if_true if condition else value_if_false · condition: A boolean expression (evaluates to True or False). value_if_true: The value assigned to variable if condition is True.
🌐
Devgex
devgex.com › en › article › 00050056
Python Conditional Variable Assignment: In-depth Analysis of Conditional Expressions and Ternary Operators - DevGex
December 8, 2025 - Python offers a concise conditional expression syntax, commonly referred to as the ternary operator, with the basic structure: variable = value_if_true if condition else value_if_false · This syntax allows conditional evaluation and assignment ...
🌐
Iditect
iditect.com › faq › python › python-conditional-variable-setting.html
Python Conditional Variable Setting
# Conditional variable assignment example x = 5 y = 10 result = x if x > y else y print(result) "Python conditional variable setting if else" Description: Illustrating the usage of if-else statements for conditional variable setting in Python.
🌐
Machinelearninghelp
machinelearninghelp.org › programming-for-machine-learning › how-to-add-a-variable-in-an-if-statment-python
Conditional Variable Assignment in Python If Statements
Conditional expressions, introduced with Python 2.5, provide an elegant way to evaluate a condition and return one value if true and another value if false. However, adding variable assignments within these expressions is not as straightforward but can be achieved through creative use of assignment operators directly in conditional statements.
🌐
Python
docs.python.org › 2.5 › whatsnew › pep-308.html
https://docs.python.org/2.5/whatsnew/pep-308.html
February 28, 2018 - For a long time, people have been requesting a way to write conditional expressions, which are expressions that return value A or value B depending on whether a Boolean value is true or false. A conditional expression lets you write a single assignment statement that has the same effect as the following:
🌐
Real Python
realpython.com › python-conditional-statements
Conditional Statements in Python – Real Python
September 5, 2018 - You can see in PEP 308 that the <conditional_expr> ? <expr1> : <expr2> syntax was considered for Python but ultimately rejected in favor of the syntax shown above. A common use of the conditional expression is to select variable assignment. For ...
🌐
Finxter
blog.finxter.com › home › learn python blog › python one line conditional assignment
Python One Line Conditional Assignment - Be on the Right Side of Change
September 2, 2020 - To learn more about what you can pack into a single line, watch my tutorial video “If-Then-Else in One Line Python”: A shorthand form of the ternary operator is the following tuple syntax. Syntax: You can use the tuple syntax (x, y)[c] consisting of a tuple (x, y) and a condition c enclosed in a square bracket.
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 4-7-conditional-expressions
4.7 Conditional expressions - Introduction to Python Programming | OpenStax
March 13, 2024 - A variable can be assigned with a conditional expression. Ex: Finding the max of two numbers can be calculated with max_num = y if x < y else x · Note: Conditional expressions have the lowest precedence of all Python operations.
🌐
McNeel Forum
discourse.mcneel.com › scripting
Python Conditional Statement - Scripting - McNeel Forum
September 9, 2022 - Hi all, I currently have a python script with three solutions; does anyone have any idea on how to link the solutions together please. See attached for context. Many thanks in advance. Conditional Statement.gh (5.9 KB)
🌐
YouTube
youtube.com › watch
Creating a variable conditional to the value of another ...
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
🌐
Reddit
reddit.com › r/learnpython › assigning conditional values in class
r/learnpython on Reddit: Assigning Conditional Values in Class
August 15, 2022 -

Hello,

I'm still new to Python, and I'm trying to automate a task at work. My question is regarding attributes in classes.

In this class, the attribute will always have two values depending on the what number is given. I know if statements can be used inside the class, but no matter how I try to structure the code (moving around indentions, making the if statement into its own function inside the class), Python doesn't think the attribute exists. Can I define the attribute this way (making a decision inside the class), or do I have to pass in the 'model_name' property when I pass in 'number'? Thanks for helping a new guy.

class Generator:
    def __init__(self, number):
        self.number = number

        model_name = 'gen1'

        if number == 2:
            model_name = 'gen2'

if __name__ == '__main__':
    gen = Generator(2)
    print(gen.number)
    print(gen.model_name)

Error I receive:

line 16, in <module>

print(gen.model_name)

AttributeError: 'Generator' object has no attribute 'model_name'