簡體   English   中英

我如何讓這個 python 函數返回一個值?

[英]how do i get this python function to return a value?

我有一個正在 python(test.txt) 中讀取的文件。 示例文件內容如下。

cool let's/cool
hi let's/hi
somek let's/somek

我正在尋找cool,如果它存在於這個文件中,我正在嘗試獲取值 let's/cool

我試過這個

file = open('test.txt')
my_value='cool'

def test_function(my_value):
    for line in file:
        #fields = line.strip().split()
        if line.find(my_value) != -1:
            ddda=line.rsplit(" ",1)[1]

            print(ddda)  ###This is giving my value let's/cool

while true:
    b=test_function(my_value)
    print(b) ##not able to fetch the value of ddda here

如何在 while 循環中存儲 ddda 的值。 有沒有更好的做事方式而不使用函數? 我沒有使用任何外部模塊。

print(ddda)  ###This is giving my value let's/cool

這並沒有給你任何東西。 它正在打印 如果要返回一個值,則return它,而不是print它。

return ddda

這樣做將允許您print(b)

好吧,返回該值:

print(ddda)
return ddda

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM