1
\$\begingroup\$

Assign all names to a phone number. Nothing much else to explain. I think there are a lot of improvements that can be done with this code. Not really sure what though.

here is the Name/Phone Number List

phone = open("Phone.txt", "r");

name_list = []
phone_list = []

append_data = "name"

iterate_first = True
for data in phone.readlines():
    if (data == '\n'):
        append_data = "phone"

    if (append_data == "name"):
        name_list.append(data.strip())
    else:
        if (iterate_first == False):
            phone_list.append(data.strip())
        else:
            iterate_first = False

for data in name_list:
    name_index = name_list.index(data)
    print("%s is associated with the phone number %s" % (data, phone_list[name_index]))
\$\endgroup\$
1
\$\begingroup\$
  • Use with when opening files. It automatically closes the file, which you didn't do. And allows readers to easily know the scope of the file.
  • You can loop through a file, so you don't need to use readlines.
  • Rather than using iterate_first you can use continue. This is as you skip the line which is empty. It also makes your code simpler, as it explicitly says what that variable does.
  • Rather than using name_list.index(data), you could instead use enumerate, or even better, zip.
  • Rather than using %s formatting, you can use str.format. This has a simpler interface, and is the same style as f-strings, which are the new best way to format strings. However f-strings are Python 3.6+.
  • Your names are mostly good, name_list, but using plurals may be better, names.

Using all the above can allow you to get:

with open("Phone.txt", "r") as phone:
    names = []
    numbers = []
    append_data = "name"
    for data in phone:
        data = data.strip()
        if (data == ''):
            append_data = "phone"
            continue

        if (append_data == "name"):
            names.append(data)
        else:
            numbers.append(data)

for name, number in zip(names, numbers):
    print("{} is associated with the phone number {}".format(name, number))

The above is good, however, I'd personally use itertools.takewhile, and a function. You may find the code harder to read, however I don't so you may not want to use the following. And so I'd write:

from itertools import takewhile


def read_phone_file(phone_file):
    with open(phone_file, "r") as f:
        lines = (item.strip() for item in f)
        return list(takewhile(bool, lines)), list(lines)


names, numbers = read_phone_file("Phone.txt")
for name, number in zip(names, numbers):
    print("{} is associated with the phone number {}".format(name, number))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.