w3resource

Python: Determine whether variable is defined or not

Python Basic: Exercise-121 with Solution

Write a Python program to determine if a variable is defined or not.

Sample Solution:

Python Code:

# Try to execute a block of code.
try:
  x = 1
except NameError:
  print("Variable is not defined....!")
else:
  print("Variable is defined.")

# Try to execute another block of code that references an undefined variable.
try:
  y
except NameError:
  print("Variable is not defined....!")
else:
  print("Variable is defined.")
  

Sample Output:

Variable is defined.                                                                                          
Variable is not defined....!

Flowchart:

Flowchart: Determine whether variable is defined or not.

Python Code Editor:

 

Previous: Write a Python program to format a specified string limiting the length of a string.
Next: Write a Python program to empty a variable without destroying it.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-basic-exercise-121.php