Python Forum
file handing with if statements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
file handing with if statements
#1
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
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help implmenting if/else or case statements for option to choose file format. samlee916 1 1,973 Jul-22-2020, 06:06 PM
Last Post: Larz60+
  English interpretation of the following file handing snippet mortch 5 3,121 May-30-2019, 08:10 AM
Last Post: mortch

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020