In Javascript, I can assign a value like this so:
var i = p || 4
Obviously if p isn’t defined it will resort to 4. Is there a more elegant version of this operation in Python than a try: / except: combo?
try:
i = p
except:
i = 4
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
People sometime use Python’s or-operator for this purpose:
The relies on a “unique to Python” aspect of the or-operator to return the value that makes the expression true (rather than just returning True or False).
Another option that affords more flexibility is to use a conditional expression:
If you just want to check to see if a variable is already defined, a try/except is the cleanest approach:
That being said, this would be atypical for Python and may be a hint that there is something wrong with the program design.
It is better to simply initialize a variable to a place-holder value such as None. In this regard, Python’s style is somewhat different from Javascript.