0

I am currently having issues with a while loop in python

! curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp = open("mean_temp.txt", "a+")
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
headings = mean_temp.readline().split(",")

while mean_temp.readline():
    city_temp = mean_temp.readline().split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is", 
    city_temp[2], "Celcius")

This code currently skips the first and every other line when printing

Current output:

City of Cairo month ave: highest high is 34.7 Celcius

City of Nairobi month ave: highest high is 26.3 Celcius

City of Sydney month ave: highest high is 26.5 Celcius

City of Rio de Janeiro month ave: highest high is 30.0 Celcius

Required output:

City of Beijing month ave: highest high is 30.9 Celsius

City of Cairo month ave: highest high is 34.7 Celsius

City of London month ave: highest high is 23.5 Celsius

City of Nairobi month ave: highest high is 26.3 Celsius

City of New York City month ave: highest high is 28.9 Celsius

City of Sydney month ave: highest high is 26.5 Celsius

City of Tokyo month ave: highest high is 30.8 Celsius

City of Rio De Janeiro month ave: highest high is 30.0 Celsius

Thanks for your help

1
  • 2
    You call readline() once in the condition, and once inside the body of the loop. You only process the output in one of those places. So you miss alternative lines. Commented Dec 6, 2017 at 9:32

2 Answers 2

1

A while loop is not the appropriate thing to use here. Instead, use a for loop; in Python, a file can be iterated over directly.

for line in mean_temp:
    city_temp = line.split(",")
Sign up to request clarification or add additional context in comments.

Comments

0

You are reading 2 lines in one loop and printing it once. Instead use below code in place of while loop:

for row in mean_temp:
    city_temp = row.split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is", city_temp[2], "Celcius")

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.