Skip to content
Advertisement

Loops in Python

Total Python newbie/noob here.

I have to write a code that asks the user to input 3 or more company names. If a) the company has already been entered, a new name should be asked and b) if the company does not exists (I have a dozen of so csv files from company shares), a new one should be asked as well.

It’s a task for uni and the instructions said: “The program asks the user to enter at least three shares. However, if the share is already specified, or the file does not exist, a new one must be requested.” After a list of companies is created, it must be sent to another module which then reads the corresponding csv files based on this list and reads from them the opening and closing values.

from os import path
import csv

def read_company():
    companies = []

    while True:
        company = input("Enter a company")
        if company in companies:
            print("Company already entered. Enter a new one.")
        else:
            company.append(company)
        if company == False:
            company = "Company"
            if not path.exists(company + '.csv'):
                print(company + ' does not exist. Enter a new one') .format(company=company)
            else: 
                break

    return company
  1. Fairly certain the break is incorrect as it just stops the program instead of asking for a new one. No idea how to fix it.
  2. Should False even be used?

Advertisement

Answer

For your first question, break needs to be used somewhere or the while True loop will never end.

Your second question, No I don’t think False should be used in this context.

Here is what you could do.

from os import path

def read_company():
    companies = []

    while len(companies) < 3:
        company = input("Enter a company")
        if company in companies:
            print("Company already entered. Enter a new one.")
        elif not path.exists(company + '.csv'):
            print(company + ' does not exist. Enter a new one') 
        else:
            companies.append(company)
    return companies

Instead of using break I opted to use a condition in the while loop, so break was no longer necessary.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement