Hanley Soilsmith Hanley Soilsmith - 1 year ago 67
Python Question

how to pass elements in a list to a function in a for-loop

I'm trying to print the pressure of each city.

Instead of using the cities in the list, it is returning the pressure of a city called 'city'.

Super new to this and can't find an answer to something this specific. thanks!!!!!!

import pyowm
owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff')

city = ["tokyo", "jakarta"]

for i in city:
city = owm.weather_at_place('city')
city = city.get_weather()
print (city.get_pressure()['press'])

Answer Source

Use better names and things will become clearer:

import pyowm
owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff')

cities = ["tokyo", "jakarta"]

for city in cities:
    weather = owm.weather_at_place(city).get_weather()
    print (weather.get_pressure()['press'])

Changes and rationales:

  • Changed the list of cities from city to cities. A variable named city should contain a city. Not a list of them.
  • Changed the iteration variable used by the for loop to city because that is what will be in the variable: the name of one city. i is a poor name because you'd expect it to be an index, not the item, and Python for loops don't work that way. See how nicely for city in cities expresses what is actually happening?
  • Changed the call to weather_at_place() to use the variable city (a city from the list) rather than the constant string "city", as the latter would search for a city named City.
  • Chained the calls to weather_at_place() and get_weather() rather than using city to hold the value returned by the former, because the intermediate value is never used. Also eliminates the use of the variable city for something else that is not a city.
  • Changed the variable that contains the result of get_weather() to weather from city because it contains the weather, not the city.

Readability is important, even (especially!) when the person reading the code is the one who wrote it. If you're getting confused now, writing the code for the first time, imagine how confused you'll be when you try to modify the code in six months!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download