简体   繁体   中英

My code works when not indented and not in a def function in python

I have a piece of code that runs correctly when I my code is not in a def function and not indented. Here is my code when it is indented.

import csv

my_file = open("marqueeTables.csv", "r")
search_data = input("Please enter the data you are looking for")
search_data = (search_data + " metre wide")
#print(search_data)
reader = csv.reader(my_file)
for row in my_file:
    if search_data in str(row):  # == "6 metre wide":
        stripedRow = row.strip()
        splitStrippedRow = stripedRow.split(",")[0]
        print(splitStrippedRow)
        #print(row)

It prints "6 metre wide" or "12 metre wide" depending on whether I type 6 or 12.

Here is similar code but in a def (only a few things have been changed):

def userInfo():

    while True:
        w = str(input("What size width marque would you like 6 or 12: "))

        if w == "6":
            myFile = open("userDetails.csv", "a+")
            myFile.write(str(w) + ", ")
            myFile.close()
            break
        elif w == "12":
            myFile = open("userDetails.csv", "a+")
            myFile.write(str(w) + ", ")
            myFile.close()
            break
        else:
            print("Pleas type 6 or 12")
        w = (w + "metre wide")

my_file = open("marqueeTables.csv", "r")
#search_data = input("Please enter the data you are looking for")
reader = csv.reader(my_file)
for row in my_file:
    if w in str(row):
        stripedRow = row.strip()
        splitStrippedRow = stripedRow.split(",")[0]
        print(splitStrippedRow)
userInfo()

When i run the code it prints "6 metre wide" and "Seating Capacity" and "12 metre wide" and "Seating Capacity" again (because it is in the table twice.)

Could someone tell my why my code is not working in python thanks that would be great. I am using python 3.5. Thanks

在第二个代码示例中,您定义了userInfo ,但从不调用它,因此它从不运行。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM