0

I am suppose to create a function that interactively prompts for user input for temperatures for a 24 hour period (0 - 23.) Each temperature must be between -50 and 130 degrees.

If any of the values are outside of this acceptable range, the user should be asked to re-enter the value until it is within the range before going on to the next temperature.

def getTemps(hourlyTemps):
     hourlyTemps.append(int(input('Enter the temperature of the hour : ')))
            while True:
                try:
                    number1 = hourlyTemps
                    if number1 > -50 or number1 < 130:
                        raise ValueError 
                    break
                except ValueError:
                    print("Invalid integer. The number must be in the range of -50 to 130.")

I am not sure if what I am doing can be applied to a list or if I should try a different approach. Any help would be appreciated.

David
  • 567
  • 4
  • 16
SSparks
  • 25
  • 6

2 Answers2

0

You can put the input inside the while loop and continue asking until the value is okay. Something like

while True:
    try:
        temp = int(input("Enter the temperature of the hour: "))
    except ValueError:
        print('Value must be a number.')
    else:
        if -50 <= temp <= 130:
            break
        else:
            print('Value must be between -50 and 130')

# outside the loop
hourlyTemps.append(temp)
benrussell80
  • 297
  • 4
  • 10
0

Firstly you want to break this up into specific tasks.

  1. Read an integer from input
  2. Check that the integer is in the valid range
  3. Repeat this step 24 times

So first read an integer and check range

def input_int(msg, min, max):
    # Repeat until a correct value is entered
    while True:
        try:
            value = int(input(msg))
        except ValueError:
            print("Input value was not an integer")
        else:
            # Ensure the range is correct
            if value < min or value > max:
                print(f"Value must be between {min} and {max}")
            else:
                # Retern the validated value
                return value

Now repeat this the 24 times required

hourly_temps = []
for idx in range(0, 24):
    temp = input_int("Enter the temperature of the hour : ", -50, 130)
    hourly_temps.append(temp)
Tim
  • 2,510
  • 1
  • 22
  • 26