Python voltage input

95 views Asked by At

`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")
3

There are 3 answers

0
Mridul On BEST ANSWER

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")
0
Alireza Roshanzamir On

What about using the following function to check the number:

def is_number(n):
    try:
        float(n)
    except ValueError:
        return False
    return True
0
Yevhen Kuzmovych On

An easier way of doing it is by using the try-except construct:

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 True:
            try:
                frequency = float(frequency)
                break
            except ValueError:
                frequency = input("Please enter a valid number:")
        print("Frequency:", frequency, "\n")

i.e. trying to convert it to float and ask again if the conversion fails.