Search code examples
pythonalphanumericnon-alphanumeric

Python voltage input


`Hi, I want to write a code to get inputs for both integer and float numbers but only numbers. If float number is given it accepts dot but not any other nonalphanumeric characters.

I wrote this code but it gives "Please enter the Frequency value:" error for float numbers, too.`

def signal_selection(signal_type):
   if signal_type == "1":  # Sine wave
        # Frekans değerini input olarak alır
        frequency = input("Please enter the Frequency value:")  # Hz
        while (frequency.isnumeric() != True):
            if frequency.isalpha():
                frequency = input("Please enter a valid number:")
            elif frequency.isnumeric() != True:
                frequency = input("Please enter a valid number:")
            elif frequency.isdigit() != True:
                frequency = input("Please enter a valid number:")
        frequency = float(frequency)
        print("Frequency:", frequency, "\n")

Solution

  • As mentioned by @Swifty, the isnumeric check doesnt work for float-like strings. Therefore, frequency.isnumeric() != True becomes true on entering a float-like string and causes another input to take place.

    An easier and alternate way of doing this is using error handling along with a while loop:

    def signal_selection(signal_type):
        if signal_type == "1":  # Sine wave
            # Frekans değerini input olarak alır
            frequency = input("Please enter the Frequency value:")  # Hz
            valid_input = False
            while not valid_input:
                try:
                    frequency = float(frequency)
                except ValueError:
                    frequency = input("Please enter a valid number:")
                else:
                    valid_input = True
            print("Frequency:", frequency, "\n")