基本缩进Python

2024-10-03 21:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

#RockPS
import random

Choices=['R','P','S']
UserScore=0
CpuScore=0
Games=0

while Games<6:
    UserChoice=input('Rock, paper or scissors? (Type R, P or S respectively)')
    if UserChoice in Choices:
        Games+=1
CpuChoice = random.choice(Choices)   

if UserChoice == 'S' and CpuChoice == 'P':
    UserScore+=1
if UserChoice == 'P' and CpuChoice == 'R':
    UserScore+=1
if UserChoice == 'R' and CpuChoice == 'S':
    UserScore+=1
if UserChoice == 'S' and CpuChoice == 'R':
    CpuScore+=1
if UserChoice == 'P' and CpuChoice == 'S':
    CpuScore+=1
if UserChoice == 'R' and CpuChoice == 'P':
    CpuScore+=1

print(UserScore, CpuScore)
if UserScore>CpuScore:
    print('Well done, you won!')
if UserScore==CpuScore:
    print('You tied!')
if UserScore<CpuScore:
    ('Unlucky, you lost.')

我是Python的新手,所以我可能错过了一些明显的东西。程序运行良好。这是一个石头,布或剪刀的游戏。比赛共进行了5场,比赛结束时列出了比分。目前,它只说10,0 0,或0 1的任何方式,只算1场比赛。我不知道这是为什么。我认为这与我的缩进有关,因为我认为我的循环没有问题。你知道吗


Tags: orandimportyouifrandomgameschoices
2条回答

这是怎么回事:这部分代码

while Games<6:
    UserChoice=input('Rock, paper or scissors? (Type R, P or S respectively)')
    if UserChoice in Choices:
        Games+=1

执行6次,但接下来的所有行:

CpuChoice = random.choice(Choices)   

if UserChoice == 'S' and CpuChoice == 'P':
    UserScore+=1
if UserChoice == 'P' and CpuChoice == 'R':
    UserScore+=1

循环迭代完成后,只执行一次。所有if UserChoice ==行都应该缩进,以便它们是循环体的一部分。你知道吗

是的,你的压痕确实是个问题。你应该识别这条线

CpuChoice = random.choice(Choices)   

然后是线

if UserChoice == ...

与线路水平

if UserChoice in Choices:

当标识返回到与while相同的级别时,while循环的主体结束。因此,目前,所有的if UserChoice == ...条件只在while循环完成后检查一次(这就是为什么会看到1 00 00 1)。如果您识别出我建议的行,那么它们将是while循环体的一部分。你知道吗

相关问题 更多 >