Skip to main content
 首页 » 编程设计

python之为什么我的剪刀石头布程序不起作用

2025年05月04日14zhoujg

我是一名初级程序员,我只是不明白为什么我的剪刀石头布程序不起作用,它以前可以工作,但我尝试添加一个步骤,以便在用户按下 r 时重复。我哪里搞砸了?

第一个程序是在我尝试添加重启之前。它按我的预期工作。

from random import randint 
options = {1:"Rock",2:"Paper",3:"Scissors"}##This list is for the raw data to output 
 
number = randint(1,3)###Random selection of rock paper or scissors 
computer = options[number] 
 
print "Rock, Paper, Scissors Key" 
print "1 = Rock" 
print "2 = Paper" 
print "3 = Scissors" 
 
human = input("Enter what you want. ") 
print "Player chose",options[human] 
 
 
def end(computer,human): 
    if computer == human: 
        return "Draw" 
    elif computer == 1 and human == 2: 
        return "Computer chose Rock, Player has won!" 
    elif computer == 1 and human == 3: 
        return "Computer chose Rock, Player has lost." 
    elif computer == 2 and human == 1: 
        return "Computer chose Paper, Player has won!" 
    elif computer == 2 and human == 3: 
        return "Computer chose Paper, Player has lost" 
    elif computer == 3 and human == 1: 
        return "Computer chose Scissors, Player has won!" 
    elif computer == 3 and human == 2: 
        return "Computer chose Scissors, Player has lost." 
    else: 
        return "ERROR" 
print end(number, human) 
 
input("To finish press any key.") 

下一个程序是我尝试添加重启功能时的程序。这个已经不行了为什么?

from random import randint 
i = 1 
while i == 1: 
 
    options = {1:"Rock",2:"Paper",3:"Scissors"} 
 
    number = randint(1,3)###Random selection of rock paper or scissors 
computer = options[number] 
 
print "Rock, Paper, Scissors Key" 
print "1 = Rock" 
print "2 = Paper" 
print "3 = Scissors" 
 
human = input("Enter what you want. ") 
print "Player chose",options[human] 
 
 
def end(computer,human): 
        if computer == human: 
            return "Draw" 
        elif computer == 1 and human == 2: 
            return "Computer chose Rock, Player has won!" 
        elif computer == 1 and human == 3: 
            return "Computer chose Rock, Player has lost." 
        elif computer == 2 and human == 1: 
            return "Computer chose Paper, Player has won!" 
        elif computer == 2 and human == 3: 
            return "Computer chose Paper, Player has lost" 
        elif computer == 3 and human == 1: 
            return "Computer chose Scissors, Player has won!" 
        elif computer == 3 and human == 2: 
            return "Computer chose Scissors, Player has lost." 
        else: 
            return "ERROR" 
print end(number, human) 
restart_var = input("Press R to restart and Enter to exit") 
def restart(x): 
        if x == r: 
            i = 1 
        else: 
            i = 0 
restart(restart_var) 

请您参考如下方法:

问题出在这里:

if x == r: 

您将 x 与未知变量 r 进行比较。

正确的做法是与字符串 'r' 进行比较,因为 input 返回字符串。

if x == 'r':