w3resource

Python Exercise: Check a string represent an integer or not

Python Conditional: Exercise - 35 with Solution

Write a Python program that checks whether a string represents an integer or not.

Pictorial Presentation:

Python Exercise: Check a string represent an integer or not

Sample Solution:

Python Code:

# Request input from the user to input a string and assign it to the variable 'text'
text = input("Input a string: ")

# Remove leading and trailing whitespaces from the input string using the 'strip()' function
text = text.strip()

# Check if the length of the cleaned text is less than 1
if len(text) < 1:
    print("Input a valid text")  # If the text length is less than 1, display a message asking for valid input
else:
    # Check if all characters in the cleaned text are digits (0-9), indicating an integer
    if all(text[i] in "0123456789" for i in range(len(text))):
        print("The string is an integer.")  # If all characters are digits, display a message indicating an integer
    # Check if the text starts with a '+' or '-' and all subsequent characters are digits
    elif (text[0] in "+-") and all(text[i] in "0123456789" for i in range(1, len(text))):
        print("The string is an integer.")  # If the conditions for a signed integer are met, display an integer message
    else:
        print("The string is not an integer.")  # If none of the conditions are met, display a non-integer message 

Sample Output:

Input a string: python                                                                                        
The string is not an integer. 

Flowchart :

Flowchart: Check a string represent an integer or not

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to sum of two given integers. However, if the sum is between 15 to 20 it will return 20.
Next: Write a Python program to check a triangle is equilateral, isosceles or scalene.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-conditional-exercise-35.php