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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With