-2

如果我想做类似以下的事情,如何在 else 块上从 Is_Programmer() 获取返回值而不再次调用该函数?

def Is_Programmer():
    if name.lower() == "gregg":
        input = raw_input("What is the point of this app?: ")
        My_Point = Pointless(input)
        return input
    else:
        return False
if Is_Programmer() == False:
    print "I am not going to ask you what the point of this app is, because you didn't write it"
else:
    answer = Return value from Is_Programmer()

带有建议解决方案的完整“程序”

#!/usr/bin/python
# Practicing Python with random programming.

name = raw_input("What are you called?:")

class Pointless(object):
    def __init__(self,point):
        self.point = point
        print "The point of this app, according to %s is ...%s" % (name, "\n" + self.point)

def Is_Programmer():
    if name.lower() == "gregg":        
        input = raw_input("What is the point of this app?: ")        
        My_Point = Pointless(input)
        return input
    else:
        return False
IP=Is_Programmer()
if IP == False:
    print "I am not going to ask you what the point of this app is, because you didn't write it"
else:
    answer = IP
s = name + " thinks the point of this app is\n" + answer + "\n"
f = open('Pointless.txt', 'w')
f.write(s)
f.close
4

2 回答 2

4

你不能。相反,在 the 之前调用函数if并存储结果。

isIt = Is_Programmer()
if isIt == False:
    print "Is not a programmer"
else:
    print isIt, "is the point"
于 2013-10-19T23:36:10.047 回答
-1
return (True, input)
# else
return (False, None)

# then receive the values back
(isProg, text) = Is_Programmer ()
if isProg:
    # do something with text
else:
    # do something that did not need text

编辑,因为显然有人没有得到前 3 行的要点。

于 2013-10-19T23:36:41.737 回答