0

I'm new to Python. Just putting that out there.

What I want to do is to add the output of a function to a string literal that another function outputs.

This is the case:

**

def prime(n):
    **blahh blah blah....**
    if z == True:
        return " and prime"
    else:
        return ""
def happyPrime(n):
     **more blah blah blah**
            if n == 1:
                print ("Number is happy%s!" % prime)
                break
            if n in visited:
                print ("Number is sad%s!" % prime)
            visited.add(n)

[Ignore the indentations in the code snippet, StackOverflow made them come out wrong.] The intended result is, of course, that where the modulo is it adds what the other function returned. I think I may be approaching it the wrong way, though.

4

2 回答 2

1

这里:

def happyPrime(n):
     **more blah blah blah**
            if n == 1:
                print ("Number is happy%s!"  %  prime(n))
                break
            if n in visited:
                print ("Number is happy%s!"  %  prime(n))
            visited.add(n)

您的prime(n)函数返回一个字符串。因此,%s将替换为返回的字符串。

或者,您可以只连接返回的字符串。例如 :

>>> def foo(n):
        if n == True:
            return "yay"
        else:
            return "boo"

>>> def happyPrime(n):
        print "bar " + foo(n)

>>> happyPrime(True)
bar yay

>>> happyPrime(False)
bar boo
于 2013-05-11T17:51:50.890 回答
0

不太清楚你的意思,如果你想让 %s 返回 prime(n) 的结果,你必须给 prime 一个参数,因为它需要一个参数。从它的外观来看,或真或假。

print ("number is happy%s!" % prime(True))

于 2013-05-11T17:51:06.520 回答