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

Page 1 of 1

## 2 Replies - 1255 Views - Last Post: 24 February 2013 - 03:22 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=313363&amp;s=4c028630e954009fd22e348a4b03fc0b&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Orochimaru

Reputation: 3
• 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. />/>

```
# 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

• I'm not here to twist your niblets

Reputation: 4706
• Posts: 17,453
• 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

```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
```

### #3 Orochimaru

Reputation: 3
• 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

```