0

I really need help on this. Trying to create a code that determines the average temperature for an inputted amount of days. I have the input statement correct and converted to int. However, in the loop, I need it to ask the user each time

What temp was it on day X, with X being the the first day and it repeating and increasing the value each time it loops. Please help me anyone.

Here is the code below:

#Determine average temperature

days = input("How many days are you entering temperatures for:")
days = int(days)

sum = 0

for i in range(days):
    temperature = input("What temp was it on day?")
    temperature= int(temperature)
    sum = sum + temperature

average_temperature = sum/int(days)
print("Average temperature:", average_temperature)
2
  • You already have the number you need (minus 1) in i. Just use that. Commented Sep 18, 2021 at 21:44
  • temperature = input(f"What temp was it on day {i+1}?") Commented Sep 18, 2021 at 21:45

2 Answers 2

2

You can use a formatted f-string to include a variable in a string as suggested by @JohnGordon:

temperature = input(f"What temp was it on day {i + 1}? ")

It's usually a good idea to separate input/output and calculations. It usually also more intuitive to terminate input as you go along instead of asking for a count upfront. In this case I use enter (i.e. empty string as input) to signify that you are done asking for input:

import itertools

temperatures = []
for i in itertools.count(1):
    temperature = input(f"What temp was it on day {i}? ")
    if not temperature:
        break
    temperatures.append(int(temperature))

average_temperature = sum(temperatures) / len(temperatures)

print(f"Average temperature: {average_temperature}")
Sign up to request clarification or add additional context in comments.

9 Comments

Yes, but @JohnGordon have used f-strings which is much more up-to-date and considered a better way than formatting using %
Please provide a quote to support your opinion. I am not saying your are wrong, to me, it's just two different ways of doing the same thing.
you can find some basic explanations here.
Thanks but do you have a python.org (ie authoritative source)? I will update answer though just for you.
Yes, check here. Take a look at the gray box, immediately after the title. And also here they call it "old-style"
|
0

You can use built-in method str to convert int to str.

temperature = input("What temp was it on day "+ str(i+1) + " ? ")

1 Comment

This is exactly what I needed, thank you so much <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.