Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Test if Raw-Input has no entry

Tags:

python

I have the silliest question ever probably...

How can I tell if the raw_input never had anything typed into it? (Null)

final = raw_input("We will only cube numbers that are divisible by 3?")
if len(final)==0:
    print "You need to type something in..."
else:
    def cube(n):
        return n**3
    def by_three(n):
        if n%3==0:
            return cube(n)
        else:
            return "Sorry Bro. Please enter a number divisible by 3"
    print by_three(int(final))

Particularly Line 2... how would I test if final had NO input? The code works fine with anything typed in, but breaks if no entry is provided....

I'm sure it's stupidly simple, but any help is appreciated.

like image 824
Nicholas Hazel Avatar asked Aug 30 '13 22:08

Nicholas Hazel


1 Answers

No entry results in an empty string; empty strings (like empty containers and numeric zero) tests as boolean false; simply test for not final:

if not final:
    print "You need to type something in..."

You may want to strip the string of all whitespace to avoid breaking when only spaces or tabs are entered:

if not final.strip():
    print "You need to type something in..."

You still need to verify that the user entered a valid integer, however. You can catch the ValueError exception:

final = raw_input("We will only cube numbers that are divisible by 3?")
try:
    final = int(final)
except ValueError:
    print "You need to type in a valid integer number!"
else:
    # code to execute when `final` was correctly interpreted as an integer.
like image 159
Martijn Pieters Avatar answered Sep 30 '22 17:09

Martijn Pieters