Python Forum

Full Version: user inputing data until in range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I make the function to repeat until user enter value in the range and only then to break ?

      
def scale(freq):
    freq = input("Enter a fundamental frequency number: ")
    freq = int(freq)
    if freq > 20 or freq > 2000:
        print (f"frequency entered is: {frequency}")
        return
      
    else:
        print("wrong input. frequency should be between 20 - 2000\nTry again")
Thanks
def get_frequency(min_freq=20, max_freq=2000, prompt="Enter a fundamental frequency number: "):
    while True:
        try:
            freq = int(input(prompt))
            if min_freq <= freq <= max_freq:
                return freq
            else:
                print(f"Wrong input. Frequency should be between {min_freq} - {max_freq}\nTry again")  
        except ValueError:
            print('Invalid input')

frequency = get_frequency()            
print (f"frequency entered is: {frequency}")
Output:
Enter a fundamental frequency number: a Invalid input Enter a fundamental frequency number: 10000 Wrong input. Frequency should be between 20 - 2000 Try again Enter a fundamental frequency number: -10 Wrong input. Frequency should be between 20 - 2000 Try again Enter a fundamental frequency number: 200 frequency entered is: 200