Python Forum

Full Version: file handing with if statements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My code works just fine but when I introduced the 2nd if statement that returns
Output:
City not found!
then thats the only thing my code will return regardless if the city is in the text file

this is my code
# Week 5 Lab

# Exercise 1

city = input('Enter a city ') # asks for user input

with open('cities.txt','r', encoding = 'cp1252') as f: # opens a file and encodes for errors
    for line in f:
        if city in line:
            l1 = line[0:2] # assigns a variable to certain range of characters 
            t1 = line[3:5]
            c1 = line[5]
            l2 = line[7:9]
            t2 = line[10:12]
            c2 = line[12]
            print(city, 'is',l1, 'degrees',t1,'minutes',c1, 'and', l2, 'degrees',t2, 'minutes', c2) # prints coordinates
        if city not in line:
            print('City not found!')
            break
        
f.close() # closes the file
how can I fix this? I know the issue is in the way I introduced the second if statement
Remove the break statement. It ends the for loop as soon as a line is found without the city. If the first line in the file does not contain the city, it removes that, prints not found, and stops.

Of course, that will just print not found for every line in the file that isn't the city's line. I think what you want is to break if city is in the line. Then have an else for the loop (not for the if statement), where you print the not found text. The else statement for a loop executes if the loop exits without a break. So you break if you find the city, and if you don't find the city the else statement triggers.

You don't need f.close(). The with statement takes care of that. And it's a bad idea to use single letter variable names. It makes your code more confusing, which gets really bad when you start writing complicated code.