1

Wondering if there is a better way to do this. Python is my first programming language.

while True: amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ') # seperate dollars and cents. amount_list = amount_per_month.split(".") # checking if int(str) is digit if len(amount_list) == 1 and amount_list[0].isdigit() == True: break # checking if float(str) is digit elif len(amount_list) == 2 and amount_list[0].isdigit() and amount_list[1].isdigit() == True: break else: raw_input('Only enter digits 0 - 9. Press Enter to try again.') continue 
0

3 Answers 3

7

Just try to make it a float and handle the exception thrown if it can't be converted.

try: amount_per_month = float( raw_input('What is the monthly cost?') ) except (ValueError, TypeError) as e: pass # wasn't valid 

TypeError is redundant here, but if the conversion was operating on other Python objects (not just strings), then it would be required to catch things like float( [1, 2, 3] ).

Sign up to request clarification or add additional context in comments.

4 Comments

@JMS If you really wanted you could try to an int first (similar to above), and if that failed, then float, and if that failed, bail out. Does it matter if you have an int/float though?
no i could use float. Just thought about turning 15 in 15.0 isn't a problem. brain fart.
why can't we use input instead of raw_input? input basically would automatically convert the user input to the right matching python type (int, str, list, tuple, dict, float, etc..)
@ronak input() evaluates the string afterwards. So you're opening yourself up for instead of entering 2.2 or 2 or whatever, of entering: open('/path/to/important/config/file','w').write('hahaha - sucker')...
0

You could try casting the input to a float, and catching the exception if the input is invalid:

amount_per_month = raw_input('\nWhat is the monthly cost?\n==> ') try: amt = float(amount_per_month) except ValueError: raw_input('Only enter digits 0 - 9. Press Enter to try again.') 

Comments

0

use regex

r'\d+.\d+|\d+' 

http://docs.python.org/library/re.html

1 Comment

meant to add I don't know regex just yet. Thanks though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.