TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

前端 未结 2 1121
南笙
南笙 2020-12-13 19:10

So I am VERY new to programming and I started with Python 3. I started reading \"Learn Python the Hard Way\". Now, I got to a point where I had this code:

x          


        
相关标签:
2条回答
  • 2020-12-13 19:32

    You want to apply % to the string instead:

    print("I said: %r" % x)
    

    Your code is applying it to the return value of the print() call, which returns None.

    Alternatively, you can switch to using str.format():

    print("I said: {!r}".format(x))
    
    0 讨论(0)
  • 2020-12-13 19:44

    You are calling the % outside of the print() function. This tries to see if the actual function print can be printed as %r, and because print doesn't return anything, it tries to get %r for the value None (hence the NoneType error). Change it to:

    print("I said: %r" %(x))
    

    The following code:

    #!/usr/local/bin/python3
    x = "Hello"
    print ("Hello World! %s") %(x)
    

    Raises the following error:

    Hello World! %s
    Traceback (most recent call last):
      File "main.py", line 3, in 
        print ("Hello World! %s") %(x)
    TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'
    

    Changing the code to the following works:

    #!/usr/local/bin/python3
    x = "Hello"
    print ("Hello World! %s" %(x))
    

    Output:

    Hello World! Hello
    
    0 讨论(0)
提交回复
热议问题