簡體   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