简体   繁体   English

我如何让这个 python 函数返回一个值?

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

I have a file which I'm reading in python(test.txt).我有一个正在 python(test.txt) 中读取的文件。 Sample file contents are as follows.示例文件内容如下。

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

I'm searching for cool and if it exists in this file i'm trying to fetch the value let's/cool我正在寻找cool,如果它存在于这个文件中,我正在尝试获取值 let's/cool

I have tried this我试过这个

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

How do I store the value of ddda in my while loop.如何在 while 循环中存储 ddda 的值。 Is there a better way of doing things without using function?有没有更好的做事方式而不使用函数? I'm not using any external modules.我没有使用任何外部模块。

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

This is not giving you anything.这并没有给你任何东西。 It is printing .它正在打印 If you want to return a value, then return it, not print it.如果要返回一个值,则return它,而不是print它。

return ddda

Doing this will allow you to print(b) .这样做将允许您print(b)

Well, return that value:好吧,返回该值:

print(ddda)
return ddda

暂无
暂无

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

相关问题 如何获得在另一个函数中调用的函数以返回值? 蟒蛇 - How do I get a function that is called within another function to return a value? PYTHON function的code object使用Python exec如何获取返回值? - How do I get the return value when using Python exec on the code object of a function? 如何从 Python 中的异步函数访问返回值? - How do I access the return value from an async function in Python? 我怎样才能得到一个递归的python函数来返回一个值? - How can I get a recursive python function to return a value? 如何在 python 中获取 function 的返回值 - How to get a return value of a function in python 如何获取num_digit函数以提供正确的输出,以及如何使其返回python中的任何整数值? - How do I get my num_digit function to give me the correct output and how do I get it to return any integer value in python? 如何在 Python 3 中获取一个函数以返回我可以在另一个函数中使用的值? - How can I get a function in Python 3 to return a value that I can use in another function? 如何在使用返回函数的同时在 python 中获得一个定义的函数来循环? - How do I get a defined function in python to loop whilst using the return function? 如何使用Python创建一个函数,该函数将在数据表中的每一行的字典中返回一个值? - How do I create a function that will return a value in a dictionary for each row within a data sheet using Python? 在Python中,当执行`if`语句时,如何从函数返回值? - In Python, how do I return a value from a function when an `if` statement is executed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM