简体   繁体   English

我的代码在未缩进且不在 python 中的 def 函数中时有效

[英]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.当我的代码不在 def 函数中并且没有缩进时,我有一段代码可以正确运行。 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 中(仅更改了一些内容):

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.)当我运行代码时,它再次打印“6 米宽”和“座位容量”和“12 米宽”和“座位容量”(因为它在表格中出现了两次。)

Could someone tell my why my code is not working in python thanks that would be great.有人能告诉我为什么我的代码不能在 python 中工作,谢谢,那就太好了。 I am using python 3.5.我正在使用 python 3.5。 Thanks谢谢

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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