Home > Enterprise >  How can I increase the number in a input statement loop for Python?
How can I increase the number in a input statement loop for Python?

Time:09-21

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)

CodePudding user response:

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}")

CodePudding user response:

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

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