how does the % work?

Tim Roberts timr at probo.com
Sat Mar 23 05:29:48 CET 2013


leonardo selmi <l.selmi at icloud.com> wrote:
>
>i wrote this example :
>
>name = raw_input("What is your name?")
>quest = raw_input("What is your quest?")
>color = raw_input("What is your favorite color?")
>
>print """Ah, so your name is %s, your quest is %s, 
>and your favorite color is %s."""  % (name, quest, color)

No, you didn't.  You wrote:

print('''Ah, so your name is %s, your quest is %s, and your
    favorite color is %s.''') % (name, quest, color)

>but i get this error:  Traceback (most recent call last):
>  File "/Users/leonardo/print.py", line 5, in <module>
>    favourite color is %s.''') % (name, quest, color)
>TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
>
>how can i solve it?

You are using Python 3.  In Python 3, "print" is a function that returns
None.  So, the error is exactly correct.  To fix it, you need to have the %
operator operate on the string, not on the result of the "print" function:

print('''Ah, so your name is %s, your quest is %s, and your
    favorite color is %s.''' % (name, quest, color))
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list