Design a function that collets seven days of temperatures from the user using a while loop. This function accepts no parameters

The correct answer and explanation is:

Here’s a Python function that collects seven days of temperatures from the user using a while loop and accepts no parameters:

def collect_temperatures():
    temperatures = []
    day = 1

    while day <= 7:
        try:
            temp = float(input(f"Enter the temperature for day {day}: "))
            temperatures.append(temp)
            day += 1
        except ValueError:
            print("Invalid input. Please enter a numeric value.")

    print("You entered the following temperatures:")
    for i, t in enumerate(temperatures, 1):
        print(f"Day {i}: {t}°")

🔍 Explanation (300 words)

This function, collect_temperatures, is designed to collect temperature data for seven days from a user. It does not take any parameters, as specified. Here’s how it works:

  1. Initialization:
    • An empty list temperatures is created to store the temperature values.
    • A counter variable day is initialized to 1 to keep track of the current day.
  2. Using a while Loop:
    • The while loop continues as long as day is less than or equal to 7. This ensures that temperatures are collected for exactly seven days.
  3. User Input with Error Handling:
    • Inside the loop, the user is prompted to enter a temperature for the current day.
    • The input() function is used to receive user input, which is then converted to a float.
    • If the input is not a valid number (e.g. letters or symbols), a ValueError is raised. The try-except block catches this and asks the user to try again without incrementing the day.
  4. Storing the Data:
    • Valid temperatures are appended to the temperatures list.
    • The day counter is incremented only when a valid input is received.
  5. Displaying the Results:
    • After collecting all inputs, the function prints each temperature value along with the corresponding day using a for loop with enumerate.

This approach ensures reliable data collection while protecting against invalid user inputs, all managed efficiently with a simple while loop.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *