Home > Back-end >  Python - Random module if block print issue
Python - Random module if block print issue

Time:07-13

import random

print("Welcome to the game of Stone Paper Scissor!")
num=int(input("How many games do you wanna play ? Choose odd number only! "))
print(f"It is going to be best of {num} games")

for i in range(0,num):
    player=input("Play your move \n")
    comp=("R","P","S")
    comp=print(random.choice(comp))

    if player==comp:
        print("Tie")
    
    elif player=="R" and comp=="S":
        print("Player wins")

    elif player=="R" and comp=="P":
        print("Computer wins")
        
    elif player=="S" and comp=="P":
        print("Player wins")
    
    elif player=="S" and comp=="R":
        print("Computer wins")

    elif player=="P" and comp=="S":
        print("Computer wins")

    elif player=="P" and comp=="R":
        print("Player wins")

The code is getting executed but there is no printing of the results.i.e(Computer wins or player wins or Tie)

Please let me know if there is any fundamental error which needs to be corrected.

CodePudding user response:

as suggested by John Gordon, you want to save the result of random.choice before passing it to print. print always returns None, so your comparisons will always fail

I also notice that there is a lot of repetition in your if statements, I'd be tempted to use some data structure to reduce the amount of code you have to write.

the following puts all the above pieces together

beats = {
  "R": "S",
  "P": "R",
  "S": "P",
}

for i in range(0, num):
    player = input("Play your move \n")
    comp = random.choice("RPS")
    print(f"computer chose {comp}")

    if comp == player:
        print("Tie")
    elif beats[player] == comp:
        print("Player wins")
    elif beats[comp] == player:
        print("Computer wins")
    else:
        raise RuntimeError("something went wrong")
  • Related