Elif Won't Work


#1

So the title says it all I guess; I can't get an elif statement to work with this CSV attached with Google Drive
The code is below; can someone help me out? :slight_smile:
George Hall
GeorgeHall@GeorgeHHall.UK

print("Hello and welcome to property finder. ")
home = input(print(" What kind of property do you want. (Flat,Terrace, Semi Detached or a Mansion). "))
if home == "Flat" :
    import csv
myfile = open("Flat.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
elif home == "Terrace":       
      import csv
myfile = open("Terrace.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
myfile.close()
elif home == "Mansion":
      import csv
myfile = open("Mansion.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
myfile.close()
elif home == "Semi Detached":
      import csv
myfile = open("Semi Detached.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
myfile.close()

#2

Try changing your elif's to if's instead

print("Hello and welcome to property finder. ")
home = input(print(" What kind of property do you want. (Flat,Terrace, Semi Detached or a Mansion). "))
if home == "Flat" :
    import csv
myfile = open("Flat.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
if home == "Terrace":       
      import csv
myfile = open("Terrace.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
myfile.close()
if home == "Mansion":
      import csv
myfile = open("Mansion.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
myfile.close()
if home == "Semi Detached":
      import csv
myfile = open("Semi Detached.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
myfile.close()

#3

Good point :slight_smile: Elif can only be after a if statement or another elif statement, or the entire code has to be indented differently.

@devslayer38875, it would make more sense if your code needed to be indented differently, part of your code:

 if home == "Flat" :
    import csv
myfile = open("Flat.csv")
reader = csv.reader(myfile)
for row in myfile:
    print (row)
elif home == "Terrace":

how it might need to look:

if home == "Flat" :
    import csv
    myfile = open("Flat.csv")
    reader = csv.reader(myfile)
    for row in myfile:
        print (row)
elif home == "Terrace":

indent is crucial in python for nesting (what is inside the if statement, the for loop and s on)


#4

Thanks! :sweat_smile:


#5

see my updated answer, i think it also might be a indent issue, or do i see this wrong? what do you think? It is not really DRY, but that is a different story.


#6

No You're right the indent is off which is why he might still get an error message.
But I think you should also explain to him the DRY concept, which will make his code easier and more functional both for him and others to read, don't you think? :slight_smile:


#7

You made me realize what the problem was, you don't want the honor of explaining DRY?


#8

Haha I would love too! :laughing:


#9

You might not have known what stetim94 said when he DRY but don't worry its not any thing major. :sweat_smile:

D.R.Y stands for Don't Repeat Yourself.

In your code these are the lines that are not DRY, lines you only need to write once.

Now I know you might be wondering why these lines need to only be implemented once.
Well for one your code includes no functions meaning all of the code has a global scope (Outside of a function.)
Two, for loops can iterate of a large amounts of data thus why they are so powerful, so you only need one.
Three, after the for loop to print everything you only need one print statement seeing as everything is in the same file.
Four, this variable reader = csv.reader(myfile) is global meaning you only need to write it once before your if statements and for loop and it will apply for all code in (myfile)

And lastly, You only need to file.close() once not multiple times. :slight_smile:


#10

@devslayer38875

Let's take this a step further.

Most python code that opens a stream allows the use of the with statement. This automagically closes a stream when you are finished with it. In this case both the csv and open functions support the statement.

Now lets use it.

Python Code

from csv import reader  # only use what you need
from sys import exit as EXIT  # Allows use to end script
from os.path import join as JOIN  # Allows us to join path names into a files path object
from os import getcwd  # Gets the current working directory

# A Simple dictionary of homes is always nice to reduce user input error, press 1 to get 1 ect.
homes = {
    1: 'Flat',
    2: 'Terrace',
    3: ' Semi Detached',
    4: 'Mansion'
} 

# Ensure that the files exist so that we can retrieve them
for index, house in homes.items():
    try:
        t = ''.join(str(house).split(' '))  # Check to see if files is there
        with open(JOIN(getcwd(), t + '.csv'), 'r') as file:
            print("File Exists: {}".format(t + '.csv'))
    except FileNotFound:
        EXIT("File does not exist")

# Get the user input, we can create a simple function that does all this with code that handles an arbitrary number of entries but this will work for the 4 entries
ask = int(raw_input("Enter a number for your selection:\n1: {}\n2: {}\n3: {}\n4: {}".format(homes[1], homes[2], homes[3], homes[4])))

# If the user does not give a valid response exit the program
if homes.get(ask, "NA") == 'NA':
    EXIT("Failed to make valid selection!")

# Now we get the screen to display all the information wanted
with open(JOIN(getcwd(), ''.join(str(homes[ask]).split(' ')))) as file:
    csv_reader = reader(file)
    for row in csv_reader:
        print(row)

# Then force the script to pause until the user is ready to end the session
raw_input("\nPress enter when Finished")
EXIT("Thanks for using our service!")

That should about do it for you, look through this code and see what you can improve or what you would have done differently.

As a side note, when you start to handle data stream objects or files in general, ensure you have your data system designed before writing your code; as it will save you hours of debugging latter. Data systems are easy to design, just pick a naming scheme where you will store what and so on. This ensures less errors latter.

If you have any questions feel free to ask.


#11

Brilliantly executed! :grinning: