JLeno46
JLeno46

Reputation: 1269

for-loops doesn't work inside if-statement in python

The if-statement and the for-loops works fine singularly but it doen't work when the loop is inside the if-statement, better detailed in code section.

keyword = input("search here: ")

with open("listaUni.txt") as lista_uni:
    if keyword in lista_uni.read():
        print("there is")
    else:
        print("there is not")
#this works fine



with open("listaUni.txt") as lista_uni:
  for uni in lista_uni.readlines():
    if keyword.lower() in uni.lower():
      print(uni)
# also this works fine, it prints out all the strings in the list 
#containing the keyword



keyword = input("search here: ")

with open("listaUni.txt") as lista_uni:
    if keyword in lista_uni.read():
      for uni in lista_uni.readlines():
        if keyword.lower() in uni.lower():
          print(uni)
    else:
          print("there is not")
#this doesn't work

lista_uni.close()

When the keyword is in the list, it should check every string of the list and print the ones with the keyword in it, if the keyword is not in the list it should print "there is no". It asked for the keyword and then do nothing. Since the 2 pieces of the code actually work separately, what I'm doing wrong? thanks to everybody.

Upvotes: 0

Views: 607

Answers (1)

rdas
rdas

Reputation: 21275

if keyword in lista_uni.read():
      for uni in lista_uni.readlines():
        if keyword.lower() in uni.lower():
          print(uni)

Here you are trying to read the file twice.

  • During read()
  • During readlines()

After the first read. You are already at the end of the file, so readlines() returns an empty list.

To get around it you can add a seek(0)

if keyword in lista_uni.read():
      list_uni.seek(0)
      for uni in lista_uni.readlines():
        if keyword.lower() in uni.lower():
          print(uni)

Upvotes: 3

Related Questions