1346
1346

Reputation: 21

Python - List is not defined

from typing import List, Tuple, Dict, TextIO
def names(file:TextIO) -> None:
    """ create a list with all the names from the file
    """
    lines = ""
    firstname = ""
    lastname = ""
    name_list = []
    file = open(file, 'r')
    for line in file:
      line = line.strip()
      lines += line
    for i in range(len(lines)):
      if lines[i] == ",":
        lastname += lines[i+2]
        first = i
        last = i + 3
      while lines[first].islower() and lines[last].islower():
        firstname += lines[first]
        lastname += lines[last]
        first -= 1
        last += 1
    name_list.append(firstname + " " + lastname)

keep returning the name_list is not defined, where went wrong?

Upvotes: 2

Views: 12290

Answers (1)

ShadowMitia
ShadowMitia

Reputation: 2533

I tried your code and I didn't get the same error. Maybe check the indentation is correct in your code?

On the other hand you have a problem here:

  if lines[i] == ",":
    lastname += lines[i+2]
    first = i
    last = i + 3

You're declaring local variables in an if block, they will not be visible later in the code, such as in the while loop just afterwards.

You need to declare the variables in a block where they will be visible by all the subsequent blocks that use them.

My suggestion would be to add them to the variables at the top of your function:

lines = ""
firstname = ""
lastname = ""
name_list = []
lines = 0 # or whatever value it's supposed to start with
last = 0  # or whatever value it's supposed to start with

Upvotes: 1

Related Questions