RPS模拟器随机选择后全为平局问题的修复求助
Hey there! I see exactly what's causing your simulator to always return a tie—let's fix this together.
The Core Problem
Your line player1 = print(random.choice(options)) is the culprit here. The print() function in Python returns None every time it runs, regardless of what it prints to the console. That means both player1 and player2 are actually set to None, so when you compare them in the compare() function, they'll always be equal (since None == None is True), resulting in a tie every single time.
Bonus Hidden Issue
You also have a sys.exit() call right before you try to print the result of compare(). That line will terminate your program immediately, so your final print statement would never run even if the tie issue was fixed!
Step-by-Step Fixes
Let's adjust your code to fix both problems:
- First assign the random choices to
player1andplayer2(without usingprint()here) - Then print the players' choices separately
- Remove the premature
sys.exit()call - Fix the typo
imputtoinputin your error message
Corrected Full Code
import sys import random options = ["Rock", "Paper", "Scissors"] # First get the random choices and store them player1 = random.choice(options) player2 = random.choice(options) # Now print the choices print(f"Player 1 chose: {player1}") print(f"Player 2 chose: {player2}") def compare(p1, p2): if p1 == p2: return "Tie!" elif p1 == "Rock": if p2 == "Scissors": return "Rock wins!" else: return "Paper wins!" elif p1 == "Scissors": if p2 == "Rock": return "Rock wins!" else: return "Scissors wins!" elif p1 == "Paper": if p2 == "Scissors": return "Scissors wins!" else: return "Paper wins!" else: return "Invalid input!" # Print the result of the comparison print(compare(player1, player2))
Explanation of Changes
- We now store the actual random choice strings in
player1andplayer2instead of assigningNonefrom theprint()function. - Separated the assignment and printing steps so we have valid values to compare.
- Removed the
sys.exit()that was blocking the result from being displayed. - Fixed the typo in the error message for clarity.
Now your simulator should correctly show the players' choices and return the proper result instead of always tying!
内容的提问来源于stack exchange,提问作者Marcello Fabrizio

