Python 在 else 语句上获取返回值,默认变量相当于 Perl $_



如果我想做如下的事情,如何在不再次调用函数的情况下从 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 isn" + answer + "n"
f = open('Pointless.txt', 'w')
f.write(s)
f.close

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

isIt = Is_Programmer()
if isIt == False:
    print "Is not a programmer"
else:
    print isIt, "is the point"
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 行的要点。

最新更新