Exercise
Function To Check Numeric Value
Objective
Develop a Python program that defines a function to check if a string represents an integer value. This function can be used to determine whether a string like '1234' is a valid numeric value. If it is, the program will print a message saying 'It is a numerical value'.
Example Python Exercise
Show Python Code
# Function to check if a string represents an integer value
def is_integer(value):
# Try to convert the string to an integer
try:
int(value) # Attempt to convert the string to an integer
return True # Return True if successful
except ValueError:
return False # Return False if a ValueError occurs (i.e., not a valid integer)
# Example usage of the is_integer function
def main():
# Take a string input from the user
value = input("Enter a value: ")
# Check if the input value is a valid integer
if is_integer(value):
print(f"It is a numerical value.") # Print if it is a valid integer
else:
print(f"It is not a numerical value.") # Print if it is not a valid integer
# Run the main function if the script is executed directly
if __name__ == "__main__":
main()
Output
Case 1:
Enter a value: 1234
It is a numerical value.
Case 2:
Enter a value: abc
It is not a numerical value.
Share this Python Exercise