Issue
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
for city_m in cities:
if cities.startswith("M"):
print("Cities that start with M:", cities)
else:
print("No cities start with M.")
print(cities)
AttributeError Traceback (most recent call last) in () 4 5 for city_m in cities: ----> 6 if cities.startswith("M"): 7 print("Cities that start with M:", cities) 8 else:
AttributeError: 'list' object has no attribute 'startswith'
I'm trying to list cities that start with "m", but I get the error in the title, and I don't understand it. Maybe I'm doing something wrong, and I appreciate any feedback on this issue. Thank you in advance.
Solution
You're referencing the wrong variable in the for loop:
for city_m in cities:
if cities.startswith("M"):
it should be:
for city_m in cities:
if city_m.startswith("M"):
Although this won't fully solve your problem as you are looping through the entire list, and this will print cities everytime, you should instead add the cities starting with m to a list and then check that list outside of the loop:
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
m_cities = []
for city_m in cities:
if city_m.startswith("M"):
m_cities.append(city_m)
if m_cities:
print("Cities that start with M:", m_cities)
else:
print("No cities start with M.")
# Prints "Cities that start with M: ['Munich', 'Mexico City']"
Answered By - GTBebbo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.