[prog] Re: [Courses]Need a little help with extremely basic Python programming

Wolfgang Petzold petzold at villa-chaos.de
Fri Aug 22 09:02:05 EST 2003


Hello!

> On Thu, Aug 21, 2003, Jason Kappel wrote:
> >    [...]
> >    and now I'm looking for a way to check if the input is actually a
> >    number, so I don't get an error when text is entered as an input. Is
> >    there a function to check if an input is either an integer or floating
> >    point?
> >
> >    #this takes number inputs from the user untill the sum reaches 100
> >    sum = 0.0
> >    while (sum < 100):
> >        remaining = 100.0-sum
> >        print "Please choose a number no larger than",remaining
> >        number = input ("> ")
> >        sum = sum+number
> >        while (number > remaining): #while input too large, subtract and try again
> >            sum = sum-number
> >            print "That was bigger than",remaining,"try again"
> >            number = input ("> ")
> >            sum = sum+number
> >    print "Good for you! You can add to",sum

I would suggest

- not to convert string --> number by input() which is equivalent to
  eval(raw_input()). By using input() the way you did you can always
  satisfy your program immediately by entering 'remaining' or '100-sum'.
  It will be evaluated, and it evaluates exactly to... well.

  Check the "Library Reference" at "Built-in functions" for details.

- but to do the conversion explictly by using raw_input() and float().
  That function float() will throw a ValueError if it can't convert its
  input into a float. So, you could do:

	input = raw_input("> ")
	try:
		number = float(input)
	except ValueError:
		print "Which part of 'number' didn't you understand?"
		number = 0.0
	# ... further processing

Cheers,
Wolfgang



More information about the Programming mailing list