繁体   English   中英

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

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

当我的代码不在 def 函数中并且没有缩进时,我有一段代码可以正确运行。 这是我缩进时的代码。

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.

这是类似的代码,但在 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()

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

有人能告诉我为什么我的代码不能在 python 中工作,谢谢,那就太好了。 我正在使用 python 3.5。 谢谢

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

暂无
暂无

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

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