在 Python 中遇到冒号语法错误 [英] Getting a Colon Syntax Error in Python

查看:144
本文介绍了在 Python 中遇到冒号语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入

yourChoice = True

while yourChoice:
    inf_or_ltd = input('Would you like to play infinte or a limited game?: '):
        if inf_or_ltd = ((('Limited') or ('limited')) and (compScore == ('3'))):
            exit = True
            print("You lost, Goodbye")
            break
            time.sleep(1)

为什么冒号是无效语法?我已经检查了括号平衡和前面的行(它们只是变量并导入了一些模块).它说 a limited game?: '): 是无效的语法.

Why is the colon a invalid syntax? I've checked the bracket balance and the previous lines (which are just variables and importing a few modules). It says that a limited game?: '): is invalid syntax.

推荐答案

在 Python 中,一个冒号 : 定义了作用域块的开始,它本质上与 { 相同> 在大多数语言中.但是冒号是不够的,还需要识别作用域块.标识的数量取决于父块.

In Python, a colon : defines the start of a scope block, it's essentially the same as { in most languages. But the colon isn't enough, scope blocks also need to be idented. The amount of identation depends on the parent block.

scope1:
    scope2:
        scope3:

块在其标识结束时结束,即:

A block ends when its identation ends, i.e.:

scope1:
    scope1_statement
    scope2:
        scope3:
            scope3_statement
        scope2_statement
    scope1_statement

现在,你什么时候创建一个新的作用域块?好吧,当您需要定义新范围时创建它们,例如:

Now, when would you create a new scope block? Well, you create them when you need to define a new scope, such as:

  • 声明新方法(deflambda、...)
  • 声明新的代码分支(if 条件,try-catch...)
  • Declaring new methods (def, lambda, ...)
  • Declaring new code branches (if conditions, try-catch...)

在您的场景中,您试图在语句(指令)之后创建一个新的作用域,在这种情况下是一个 赋值 inf_or_ltd = input('...').

In your scenario, you are trying to create a new scope after a statement (an instruction) which in this case is an assignment inf_or_ltd = input('...').

Python 指令无法创建新的作用域块.

Python instructions cannot create a new scope block.

你需要把你的 if 放在与上面赋值相同的标识上;

You need to place your if on the same identation as the above assignment;

inf_or_ltd = input('...')
if inf_or_ltd == anything:
     # do something
else:
     # do something else

这篇关于在 Python 中遇到冒号语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆