How to determine if variable name is defined in Python

2 Answers

0 votes
try:
    x
except NameError:
    print("x does not exist")

  
  
'''
run:
   
x does not exist
   
'''

 



answered Jun 3, 2025 by avibootz
0 votes
x = 901

if 'x' in locals():
	print("x =", x)
    
if 'y' in locals():
	print("y =", y)

  
  
'''
run:
   
x = 901
   
'''

 



answered Jun 3, 2025 by avibootz

Related questions

1 answer 167 views
2 answers 188 views
1 answer 235 views
8 answers 635 views
...