Click here to Skip to main content
15,919,341 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hey!
actually I looking for a method to check existence of a variable like bellow:

Python
a = input()
if a:
    #do somthing
else:
    #do something else


but unfortunately it's work just in python3 and don't work in python2(because of the difference between the built-in function
Python
input()
in python2&3.

I want if user enter the ENTER do something else enter something(like string or integer) do something else

Hint:I use the bellow method but it doesn't work.(consider the upper condition.)

What I have tried:

Python
a = input()
if a:
    #do somthing
else:
    #do something else

and
Python
try:
   a = input()
NameErro:
    #do somthing
else:
    #do something else
Posted
Updated 17-Jan-17 18:54pm

 
Share this answer
 
This explains the differences between the python2 and python3 interpretation of input():
python - What's the difference between raw_input() and input() in python3.x? - Stack Overflow[^]
 
Share this answer
 
Just check if the input isn't non-existant by putting a try/except case!

Python
try:
  a = input()
  #value exists
  print("You entered something!")
except:
  #value does not exist
  print("You didn't enter anything!")
 
Share this answer
 
v3
For python 2.7, use raw_input() instead of input(), e.g.
a = raw_input()
if a=="":
    print "you have not entered anything!"
else:
    print "you have enter {}.".format(a)
Refer: 2. Built-in Functions — Python 2.7.13 documentation[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900