HarryCBurn
HarryCBurn

Reputation: 785

Can I set a variable to nothing?

The question kind of explains it. I was thinking it would be something like:

x = None
if sUserInt == x:
    #do stuff here

I'm using it to check if a user has just pushed enter and put nothing in at all. Thanks!

Upvotes: 3

Views: 7268

Answers (2)

leeladam
leeladam

Reputation: 1758

First, you don't have to define a new variable only to compare its value. So instead of

x = None
if sUserInt == x:
    #do stuff here

You could write

if sUserInt == None:
    #do stuff here

However, in case of None, you can use the implicit checking of a variable being None:

if not sUserInt:
    #do stuff here

And finally, all these won't help you anyway, because simply pushing an enter on raw_input() won't give you None, but an empty string ('').

So use:

if sUserInt == '':
        #do stuff here

or check the length of input

if len(sUserInt) == 0:
        #do stuff here

or use the implicit string checking again:

if not sUserInt:
        #do stuff here

All the last three solutions mean basically the same thing.

Upvotes: 3

Deelaka
Deelaka

Reputation: 13693

Rather Use :

if not sUserInt:
    #do something here

Example usage:

sUserInt = raw_input()
if not sUserInt:
    print "Nothing Entered"

If nothing was entered it would print Nothing Entered

Upvotes: 2

Related Questions