The reason this isn't working is because is_number() is being defined after it is accessed. When Python reaches that particular piece of code that is calling is_number, it hasn't been defined yet.
There are a few solutions to this:
1. Move the function
This is the simplest way to do it, so that the function is defined before it is accessed. Just put your function definition before you call it.
2. Put the function in a separate file and import it
Put your function in a separate file, like below:
isnum.py
def is_number(s):
try:
float(s)
return True
except ValueError:
return False;
Then in your main file:
main.py
from isnum import is_number
for check in lines:
if is_number(check):
print ("number: " + check)
else:
print ("String!" + check)
3. Make a main() function
As @santosh-patil said in his answer, you can also make a main function that will be called.
def is_number(s):
try:
float(s)
return True
except ValueError:
return False;
def main():
for check in lines:
if is_number(check):
print ("number: " + check)
else:
print ("String!" + check)
if __name__ == '__main__':
main()
4. Just don't make it a function
This is the simplest solution: just put the code directly into your main program. The way I see it, it's only being called once per loop, so you might as well just put your is_number code in your regular code.
for check in lines:
try:
float(check)
print("number: "+check)
except ValueError:
print("String!"+check)
You should get in the habit of always defining your functions: in a program, you should do you things in this order:
- Import your modules
- Declare functions, and constants
- The rest of your code
Hope this answered your question.