How to Check if a String is a Number in Python

In this tutorial, we will program a 'How to Check if a String is a Number in Python'. We will gain a better understanding of checking whether a string is a number. The main goal here is to understand the structure of the program for checking the string. I will provide a sample program to demonstrate the actual coding of this tutorial.

This topic is very easy to understand; just follow the instructions I provide, and you can also do it yourself with ease. The program I will show you covers the basics of programming for checking if a string is a number. I will do my best to provide you with the easiest method of creating this program, called 'Check a string'. So, let's start with the coding.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display the checking of string. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def checkNum(num):
  2. try:
  3. float(num)
  4. return True
  5. except ValueError:
  6. return False
  7.  
  8. while True:
  9. ret=False
  10.  
  11. print("\n\n================= Check if a string is a number =================\n\n")
  12.  
  13. string=input("Enter here: ")
  14.  
  15. if checkNum(string) == True:
  16. print("This a number!")
  17. else:
  18. print("This is not a number!")
  19.  
  20.  
  21. user_input=input("\n\nExit Application? (Yes/No): ")
  22. if user_input.lower()=='yes':
  23. print("Exit program.")
  24. break
  25.  
  26. elif user_input.lower()=='no':
  27. ret=True
  28.  
  29. else:
  30. print("Wrong input.")
  31. ret=True
  32.  
  33.  
  34. if ret:
  35. continue

In the provided code, we created a method that will handle the argument to check if the string is a number. Lastly, we will create a while loop that will enclose our whole block of code.

Output:

The How to Check if a String is a Number in Python source code that I provide can be download below. Please kindly click the download button.

There you have it we successfully created How to Check if a String is a Number in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment