Search code examples
pythonnonetype

"TypeError: '>' not supported between instances of 'int' and 'NoneType'"


I'm using def functions and when I run the code I get "TypeError: '>' not supported between instances of 'int' and 'NoneType'". I get what the error is saying but is there any way to change the nontype into an int?

import random 
random.randint(1,3)

def P1():
   print("pick ")
   playerinput = int(input("rock(1), paper(2), scissors(3):"))

   if playerinput == 1:
        print("Player 1 chose: rock")
   elif playerinput == 2:
        print("Player 1 chose: paper")
   elif playerinput == 3:
        print("Player 1 chose: scissors")
   return (playerinput)

def P2():
    computer = random.randint(1,3)  
    if computer == 1:
        print("CPU chose: rock")
    elif computer == 2:
        print("CPU chose: paper")
    elif computer == 3:
        print("CPU 2 chose: scissors")

def winner():
    if P1()>P2():
        print("Player 1 wins")


def main():
   winner()

main() 

Solution

  • if P1()>P2(): your error is occurring here

    In Python, all functions implicitly return None, and return statements can be used to give a useful value

    def f():
        pass
    

    returns None when called

    def f():
        return 1
    

    returns 1 when called

    Notice your function P2 has no return statement, so calling it will result in None. As stated by your error message, > (greater than operator, which you use with the result of P2()) is not supported between int and NoneType. In general, None is not comparable besides ==, but it is considered better to use is when determining if a value is None

    What is the difference between " is None " and " ==None "