As part of a bigger Python homework problem, I'm trying to check if a string input contains a positive/negative integer or float, and returns True if it does, False if it does not.
The homework problem will assume that the user enters in a very simple math expression, separated by whitespace (e.g. 8 / ( 2 + 2 )), after which, the expression will be broken down into separate characters in a list (e.g. ["8", "/", "(", "2", "+", "2", ")"]). Then, I will run this list through a 'for' loop that increases the number of a counter variable, based on the current token's type (e.g. if currentToken is "2", then operandCount += 1).
So far, I'm having difficulty trying to accomplish this with a currentToken that contains a positive/negative float or int-type number (e.g. "8", "-9", "4.6"). The main challenge here is that my professor does not allow us to use try-except anywhere in our code, so that rules out a lot of the solutions I've found online so far as many of them involve catching an error message.
The closest I've come to solving this was using the 'isnumeric()' and 'isdigit()' methods.
# Assume that the user will enter in a simple math expression, separated by whitespace.
expression = input("Enter an expression: ")
expr = expression.split()
operandCount = 0
for currentToken in expr:
if currentToken.isnumeric() == True:
operandCount += 1
# operandCount should increase when the 'for' loop encounters
# a positive/negative integer/float.
However, it only returns True for strings that contain purely positive integers. I need it to be able to return True for integers and floats, both positive and negative. Thanks in advance for any advice!