2 Replies - 1093 Views - Last Post: 24 February 2013 - 03:22 PM Rate Topic: -----

#1 Orochimaru  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 47
  • Joined: 26-December 12

How should I loop this num_check function to stop once I get an int?

Posted 24 February 2013 - 01:48 PM

How should I loop this num_check function to stop once I get an int?
I feel like a while loop is a better choice than using a for loop. But I can't figure out how to integrate the while loop for this situation. :surrender:/>/>


# http://www.dreamincode.net/forums/topic/186908-sanity-check-for-raw-input-being-integer/
# http://learnpythonthehardway.org/book/ex35.html

# http://learnpythonthehardway.org/book/ex48.html
# http://learnpythonthehardway.org/book/ex21.html


# number = (int(raw_input(" Enter a number: ")))

def convert_number(s):
    try:
        return int(s)
    except ValueError:
        return None
        #exit(5)


#num1 = convert_number('@')
#print "This is what function-except-ValueError returned: %r" % num1

#num2 = convert_number(-3.333)
#print "\nThis is what function returned: %r" % num2


number = raw_input(" Enter a number: ")
num3 = convert_number(number)
print "\n\tThis is what function returned: %r\n" % num3




Is This A Good Question/Topic? 0
  • +

Replies To: How should I loop this num_check function to stop once I get an int?

#2 andrewsw  Icon User is offline

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3181
  • View blog
  • Posts: 10,659
  • Joined: 12-December 12

Re: How should I loop this num_check function to stop once I get an int?

Posted 24 February 2013 - 02:39 PM

It would be better if you made an attempt at this yourself, then we could help you with your code. Study this:

while True:
    number = input(" Enter a number: ")
    num3 = convert_number(number)
    if num3 is not None:
        print ("\n\tThis is what function returned: %r\n" % num3)
    else:
        break

Was This Post Helpful? 1
  • +
  • -

#3 Orochimaru  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 47
  • Joined: 26-December 12

Re: How should I loop this num_check function to stop once I get an int?

Posted 24 February 2013 - 03:22 PM

It worked thanks! :^:/>/>

def convert_number(s):
    try:
        return float(s)
    except ValueError:
        return None


#num1 = convert_number('@')
#print "This is what function-except-ValueError returned: %r" % num1

#num2 = convert_number(-3.333)
#print "\nThis is what function returned: %r" % num2


while True:
    number = raw_input(" Enter a number: ")
    num3 = convert_number(number)

    if num3 is None:
        print "\n\tThis is what function returned: %r\n" % num3
    else:
        break



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1