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.



Follow us on Facebook and Twitter for latest update.