我正在嘗試將函式從一個代碼匯入另一個代碼,第一個程式正在執行 .txt 檔案并搜索單詞是否存在:
exists = 0 #To import this variable to other code i have to this
path = 'D:\Python\database.txt'
def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
exists = 1
else:
exists = 0
其他代碼:
word = input("Enter one word: ")
search(word)
if exists == 1:
print("This word exists in database!")
else:
print("This word doesn't exist in database!")
即使單詞在資料庫程式中列印“資料庫中不存在此單詞!”。問題是我無法更新函式搜索中存在的區域變數。我嘗試使用全域存在,它不起作用!請幫忙!
uj5u.com熱心網友回復:
您可以使search函式回傳值。
def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
return 1
else:
return 0
word = input("Enter one word: ")
exists = search(word)
if exists == 1:
print("This word exists in database!")
else:
print("This word doesn't exist in database!")
uj5u.com熱心網友回復:
這是因為您在函式范圍內再次定義存在。
嘗試這個:
path = 'D:\Python\database.txt'
def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
exists = 1
else:
exists = 0
return exists
和,
word = input("Enter one word: ")
exists = search(word)
if exists == 1:
print("This word exists in database!")
else:
print("This word doesn't exist in database!")
uj5u.com熱心網友回復:
現在你的函式只是將變數exists設定為 1 或 0。exists是一個區域變數。根據定義,您不應該從其他地方訪問它。如果您想知道值,則需要添加 return。
path = 'D:\Python\database.txt'
def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
return 1
else:
return 0
添加回傳后,您需要在某處接收該值。您可以按照其他評論中的建議進行操作并將其保存到變數中exists,或者您可以按照我在下面的建議進行操作。由于您將使用結果作為 if-else 來檢查回傳是 0 還是 1,您可以立即檢查if (search(word)):以獲得更清晰的代碼。
def main():
word = input("Enter one word: ")
if search(word):
print("This word exists in database!")
else:
print("This word doesn't exist in database!")
if __name__ == "__main__":
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494919.html
