|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
Testing the existnace of variable
Hi,
I have a script in which I'd like to test whether or not a particular variable has been defined or not. The php equivalent would be something like this: if !$MyVariable {$MyVariable = "Hello World";} else {echo $MyVariable;} What is the equivalent syntax in Python? Can't seem to find anything in any of the documentation I have. Thanks, NICK |
|
#2
|
|||
|
|||
|
Testing the existence of a variable
Hello,
You need to assign variables in Python before you can use them. This is good programming practice. You can re-define variables later eg: #!/usr/bin/env python def main(): testVar=None if (not testVar): testVar = "Hello World" print testVar testVar = 3 print testVar if __name__ == "__main__": main() prints: Hello World 3 But, I strongly advise you to try to avoid doing this. It makes code difficult to understand and maintain. I suggest you initialise your variables before use. Hope that helps, Adil |
|
#3
|
|||
|
|||
|
Thanks
Thanks for that
NICK |
|
#4
|
|||
|
|||
|
To answer your question directly...
One way to test the existence of a variable would be: Code:
try:
MyVariable
except NameError:
MyVariable = "Hello World"
print MyVariable
Best, parker |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Testing the existnace of variable |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|