Given the string as an input to the Python program, the Python program should accept the string and check if it is an integer or not. if the given string is an integer then print its an integer.
let’s use try Block with the type conversion to check if the string is an integer or not.
Write A Python Program To Check A String Represent An Integer Or Not
Let's take a string variable named as text and use the input function call to ask the user to enter a string.
text = input("Enter a String : ")
Once the user enters a string, take a try block and convert it into an integer using int() function call. use the except block to catch the value error, in the except block print that string does not represent an integer.
Also use the else block to print the string represents and integer and exit program
try:
int(text)
except ValueError:
print("string does not represent an integer")
else:
print("String Represent An Integer")
Python Code
===========================
text = input("Enter a String : ")
try:
int(text)
except ValueError:
print("string does not represent an integer")
else:
print("String Represent An Integer")
Output
================
Enter a String : 55
String Represent An Integer
Output
===============
Enter a String : hi
string does not represent an integer
Output
============
Enter a String : call me at 123
string does not represent an integer
Conclusion
======================
Try executing the above python program by providing a different set of string inputs and note down the result.
Comment it down below if you have any suggestions to improve the above by python program.
0 Comments