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:
- 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.
- An empty list
- Using a
while
Loop:- The
while
loop continues as long asday
is less than or equal to 7. This ensures that temperatures are collected for exactly seven days.
- The
- 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 afloat
. - If the input is not a valid number (e.g. letters or symbols), a
ValueError
is raised. Thetry-except
block catches this and asks the user to try again without incrementing theday
.
- Storing the Data:
- Valid temperatures are appended to the
temperatures
list. - The day counter is incremented only when a valid input is received.
- Valid temperatures are appended to the
- Displaying the Results:
- After collecting all inputs, the function prints each temperature value along with the corresponding day using a
for
loop withenumerate
.
- After collecting all inputs, the function prints each temperature value along with the corresponding day using a
This approach ensures reliable data collection while protecting against invalid user inputs, all managed efficiently with a simple while
loop.