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.

1
  • 1
    You should use prime(n) instead of just prime; print ("Number is happy%s!" % prime(n)). Commented May 11, 2013 at 17:52

2 Answers 2

1

Here:

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)

Your prime(n) function returns a string. So, %s will be replaced with the returned string.

Alternatively, you can just concatenate the returned string. For example :

>>> 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
Sign up to request clarification or add additional context in comments.

4 Comments

It's worth noting the Python docs recommend the newer str.format() over the old % string formatting.
@Lattyware Thank you for pointing that out. I should have read the Python docs more carefully.
@ThanakronTandavas It's not a huge problem - % style formatting isn't even deprecated yet (although that might happen at some point), but it's probably a good idea to get into the habit of using the new style formatting. It's more powerful and easier to read.
@Lattyware Couldn't agree with you more. I will stick to str.format() then.
0

Not sure quite what you mean, if you want %s to return the result of prime(n) you have to give prime an argument because it expects one. from the looks of it, either True or False.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.