精华内容
下载资源
问答
  • python中空语句

    万次阅读 2013-11-25 15:58:56
    在python中使用空语句 直接写  pass

    在python中使用空语句 直接写 

    pass


    展开全文
  • Python中空语句_pass

    2020-09-10 23:01:05
    Python 代码正常情况下执行的顺序是从左到右从上到下的,但是流程控制当中不是这样的。 2、判断语句 2.1、if判断 说明 判断语句,只有满足if条件才会执行if下的语句块。 if:可以有N个。 elif:可以有N个。 else: ...

    【说明】
    1、pass 写在任何缩进的语句块部分,只是占位,什么事情都不做,为了满足 python 的语法要求。

    练习-1

    # 输出10以内的偶数
    for i in range(1,10):
    	if i % 2 == 0:
    		print(i,end = " ")
    else:
    	pass
    # 输出:2 4 6 8
    

    练习-2

    # 输出 Python 的每个字母
    for i in 'Python':
    	if i == 'h':
    		pass
    		print('这是 pass 块')
    	print('当前字母 :', i)
    
    print("Thanks!")
    
    展开全文
  • Python中各种判断为语句

    万次阅读 2018-09-18 11:48:53
    键盘输入时,常常需要输入回车来使输入结束 例如: while True: l=[] i=input('请输入学生信息') if not i: break else: l.append(i) ...if 语句 ...当表达式为真时,执行下面...在Python中None== FALSE not i...

    在键盘输入时,常常需要输入回车来使输入结束
    例如:

    while True:
    	l=[]
    	i=input('请输入学生信息')
    	if not i:
    		break
    	else:
    		l.append(i)
    	
    

    • if 语句
    • 格式: if 表达式:
    • 当表达式为真时,执行下面的语句
      这样就不难理解了,当键盘输入为空时,i = None
      在Python中None== FALSE
      not i = TRUE
      所以执行 break
      if x is None or if x is not None
    • is or is not 语句
    • 作用:判断两个对象是否为同一对象
      注意:是判断两者是否为同一对象,而不是两者值相等
    x=1000
    y=1000
    x is y   
    #Fales
    

    所以 把上面语句改写成 if x is None 就会报错

    补充:
    python中[],{},()都为None

    `

    展开全文
  • python条件语句多条件From the previous tutorials in this series, you now have quite a bit of Python code under your belt. Everything you have seen so far has consisted of sequential execution, in which...

    python条件语句多条件

    From the previous tutorials in this series, you now have quite a bit of Python code under your belt. Everything you have seen so far has consisted of sequential execution, in which statements are always performed one after the next, in exactly the order specified.

    从本系列的先前教程中,您现在掌握了很多Python代码。 到目前为止,您所看到的所有内容都包含顺序执行 ,其中语句始终按照指定的顺序在下一个之后执行。

    But the world is often more complicated than that. Frequently, a program needs to skip over some statements, execute a series of statements repetitively, or choose between alternate sets of statements to execute.

    但是世界往往比这更复杂。 通常,程序需要跳过某些语句,重复执行一系列语句,或者在要执行的备用语句集之间进行选择。

    That is where control structures come in. A control structure directs the order of execution of the statements in a program (referred to as the program’s control flow).

    这就是控制结构的用武之地。控制结构指示程序中语句的执行顺序(称为程序的控制流 )。

    Here’s what you’ll learn in this tutorial: You’ll encounter your first Python control structure, the if statement.

    这是在本教程中学习的内容:您将遇到第一个Python控件结构if语句。

    In the real world, we commonly must evaluate information around us and then choose one course of action or another based on what we observe:

    在现实世界中,我们通常必须评估我们周围的信息,然后根据我们观察到的情况选择一种行动方案或另一种行动方案:

    If the weather is nice, then I’ll mow the lawn. (It’s implied that if the weather isn’t nice, then I won’t mow the lawn.)

    如果天气晴朗,那我去修剪草坪。 (这意味着如果天气不好,那我就不会割草坪了。)

    In a Python program, the if statement is how you perform this sort of decision-making. It allows for conditional execution of a statement or group of statements based on the value of an expression.

    在Python程序中, if语句是您执行这种决策的方式。 它允许基于表达式的值有条件地执行一个语句或一组语句。

    The outline of this tutorial is as follows:

    本教程的概述如下:

    • First, you’ll get a quick overview of the if statement in its simplest form.
    • Next, using the if statement as a model, you’ll see why control structures require some mechanism for grouping statements together into compound statements or blocks. You’ll learn how this is done in Python.
    • Lastly, you’ll tie it all together and learn how to write complex decision-making code.
    • 首先,您将以最简单的形式快速了解if语句。
    • 接下来,使用if语句作为模型,您将了解为什么控制结构需要某种机制来将语句分组为复合语句 您将学习如何在Python中完成此操作。
    • 最后,将它们结合在一起,并学习如何编写复杂的决策代码。

    Ready? Here we go!

    准备? 开始了!

    if语句简介 (Introduction to the if Statement)

    We’ll start by looking at the most basic type of if statement. In its simplest form, it looks like this:

    我们将从查看最基本的if语句类型开始。 最简单的形式如下:

     if if << exprexpr >> :
        :
        << statementstatement >
    >
    

    In the form shown above:

    在上面显示的形式中:

    • <expr> is an expression evaluated in Boolean context, as discussed in the section on Logical Operators in the Operators and Expressions in Python tutorial.
    • <statement> is a valid Python statement, which must be indented. (You will see why very soon.)
    • <expr>是在布尔上下文中评估的表达式,如Python运算符和表达式中有关逻辑运算符的部分所述。
    • <statement>是有效的Python语句,必须缩进。 (您很快就会明白为什么。)

    If <expr> is true (evaluates to a value that is “truthy”), then <statement> is executed. If <expr> is false, then <statement> is skipped over and not executed.

    如果<expr>为true(评估为“ true”的值),则执行<statement> 如果<expr>为false,则将跳过<statement>并且不执行。

    Note that the colon (:) following <expr> is required. Some programming languages require <expr> to be enclosed in parentheses, but Python does not.

    注意,冒号( : )以下<expr>是必需的。 某些编程语言要求将<expr>括在括号中,而Python则不需要。

    Here are several examples of this type of if statement:

    以下是这种类型的if语句的几个示例:

    Note: If you are trying these examples interactively in a REPL session, you’ll find that, when you hit Enter after typing in the print('yes') statement, nothing happens.

    注意:如果您在REPL会话中以交互方式尝试这些示例,则会发现,在输入print('yes')语句后按Enter时,什么都不会发生。

    Because this is a multiline statement, you need to hit Enter a second time to tell the interpreter that you’re finished with it. This extra newline is not necessary in code executed from a script file.

    由于这是多行语句,因此您需要再次按Enter键以告诉解释器您已完成该语句。 从脚本文件执行的代码中不需要多余的换行符。

    分组语句:缩进和块 (Grouping Statements: Indentation and Blocks)

    So far, so good.

    到目前为止,一切都很好。

    But let’s say you want to evaluate a condition and then do more than one thing if it is true:

    但是,假设您要评估一个条件,然后在满足条件的情况下做不止一件事情:

    If the weather is nice, then I will:

    如果天气晴朗,我将:

    • Mow the lawn
    • Weed the garden
    • Take the dog for a walk
    • 修剪草坪
    • 在花园里除草
    • 带着狗散步

    In all the examples shown above, each if <expr>: has been followed by only a single <statement>. There needs to be some way to say “If <expr> is true, do all of the following things.”

    在上面显示的所有示例中,每个if <expr>:之后仅是一个<statement> 必须有某种方式说“如果<expr>为true,请执行以下所有操作。”

    The usual approach taken by most programming languages is to define a syntactic device that groups multiple statements into one compound statement or block. A block is regarded syntactically as a single entity. When it is the target of an if statement, and <expr> is true, then all the statements in the block are executed. If <expr> is false, then none of them are.

    大多数编程语言采用的通常方法是定义一种语法设备,该设备将多个语句分组为一个复合语句 块在语法上被视为单个实体。 如果它是if语句的目标并且<expr>为true,则将执行块中的所有语句。 如果<expr>为false,则都不是。

    Virtually all programming languages provide the capability to define blocks, but they don’t all provide it in the same way. Let’s see how Python does it.

    几乎所有的编程语言都提供了定义块的功能,但它们并非都以相同的方式提供。 让我们看看Python是如何做到的。

    Python:与缩进有关 (Python: It’s All About the Indentation)

    Python follows a convention known as the off-side rule, a term coined by British computer scientist Peter J. Landin. (The term is taken from the offside law in association football.) Languages that adhere to the off-side rule define blocks by indentation. Python is one of a relatively small set of off-side rule languages.

    Python遵循称为越位规则的惯例,该惯例是英国计算机科学家Peter J. Landin创造的。 (该术语取自协会足球比赛的越位法。)遵守越位规则的语言通过缩进来定义块。 Python是相对较小的越位规则语言中的一种

    Recall from the previous tutorial on Python program structure that indentation has special significance in a Python program. Now you know why: indentation is used to define compound statements or blocks. In a Python program, contiguous statements that are indented to the same level are considered to be part of the same block.

    回顾先前有关Python程序结构的教程, 缩进在Python程序中具有特殊的意义 现在您知道原因了:缩进用于定义复合语句或块。 在Python程序中,缩进相同级别的连续语句被视为同一块的一部分。

    Thus, a compound if statement in Python looks like this:

    因此,Python中的复合if语句如下所示:

     if if << exprexpr >> :
        :
        << statementstatement >
        >
        << statementstatement >
        >
        ...
        ...
        << statementstatement >
    >
    << following_statementfollowing_statement >
    >
    

    Here, all the statements at the matching indentation level (lines 2 to 5) are considered part of the same block. The entire block is executed if <expr> is true, or skipped over if <expr> is false. Either way, execution proceeds with <following_statement> (line 6) afterward.

    在此,所有匹配缩进级别的语句(第2至5行)都被视为同一块的一部分。 整个块执行如果<expr>为真,或跳过如果<expr>是假的。 无论哪种方式,执行都会在<following_statement> (第6行)之后进行。

    Python条件语句
    Python Compound if Statement
    Python复合if语句

    Notice that there is no token that denotes the end of the block. Rather, the end of the block is indicated by a line that is indented less than the lines of the block itself.

    注意,没有标记表示该块的结尾。 相反,该块的末端由缩进的线表示,该缩进线比该块本身的线小。

    Note: In the Python documentation, a group of statements defined by indentation is often referred to as a suite. This tutorial series uses the terms block and suite interchangeably.

    注意:在Python文档中,由缩进定义的一组语句通常称为suite 本教程系列互换使用术语块和套件。

    Consider this script file foo.py:

    考虑此脚本文件foo.py

    Running foo.py produces this output:

    运行foo.py会产生以下输出:

     C:UsersjohnDocuments>python foo.py
    C:UsersjohnDocuments> python foo.py
    After conditional
    After conditional
    

    The four print() statements on lines 2 to 5 are indented to the same level as one another. They constitute the block that would be executed if the condition were true. But it is false, so all the statements in the block are skipped. After the end of the compound if statement has been reached (whether the statements in the block on lines 2 to 5 are executed or not), execution proceeds to the first statement having a lesser indentation level: the print() statement on line 6.

    第2至5行的四个print()语句缩进到彼此相同的级别。 它们构成条件为真时将执行的块。 但这是错误的,因此将跳过该块中的所有语句。 在到达复合if语句的末尾之后(无论是否执行第2至5行的块中的语句),执行将继续执行缩进级别较低的第一个语句:第6行的print()语句。

    Blocks can be nested to arbitrary depth. Each indent defines a new block, and each outdent ends the preceding block. The resulting structure is straightforward, consistent, and intuitive.

    块可以嵌套到任意深度。 每个缩进定义一个新块,每个缩进结束前一个块。 最终的结构是简单,一致和直观的。

    Here is a more complicated script file called blocks.py:

    这是一个更复杂的脚本文件,称为blocks.py

    The output generated when this script is run is shown below:

    运行此脚本时生成的输出如下所示:

     C:UsersjohnDocuments>python blocks.py
    C:UsersjohnDocuments> python blocks.py
    Outer condition is true
    Outer condition is true
    Between inner conditions
    Between inner conditions
    Inner condition 2
    Inner condition 2
    End of outer condition
    End of outer condition
    After outer condition
    After outer condition
    

    Note: In case you have been wondering, the off-side rule is the reason for the necessity of the extra newline when entering multiline statements in a REPL session. The interpreter otherwise has no way to know that the last statement of the block has been entered.

    注意:如果您一直想知道,越位规则是在REPL会话中输入多行语句时需要额外的换行符的原因。 否则,解释器无法知道已输入该块的最后一条语句。

    其他语言做什么? (What Do Other Languages Do?)

    Perhaps you’re wondering what the alternatives are. How are blocks defined in languages that don’t adhere to the off-side rule?

    也许您想知道替代方案是什么。 如何用不遵守越位规则的语言来定义块?

    The tactic used by most programming languages is to designate special tokens that mark the start and end of a block. For example, in Perl blocks are defined with pairs of curly braces ({}) like this:

    大多数编程语言使用的策略是指定特殊标记,以标记块的开始和结束。 例如,在Perl中,用成对的花括号( {} )定义块,如下所示:

    C/C++, Java, and a whole host of other languages use curly braces in this way.

    C / C ++,Java和许多其他语言都以这种方式使用花括号。

    Perl conditional statement
    Compound if Statement in C/C++, Perl, and Java
    复合C / C ++,Perl和Java中的if语句

    Other languages, such as Algol and Pascal, use keywords begin and end to enclose blocks.

    其他语言,例如Algol和Pascal,则使用关键字beginend来封闭块。

    哪个更好? (Which Is Better?)

    Better is in the eye of the beholder. On the whole, programmers tend to feel rather strongly about how they do things. Debate about the merits of the off-side rule can run pretty hot.

    在情人眼中更好。 总体而言,程序员对他们的工作方式倾向于有相当强烈的感觉。 关于越位规则的优点的辩论可能非常热门。

    On the plus side:

    从积极的一面:

    • Python’s use of indentation is clean, concise, and consistent.
    • In programming languages that do not use the off-side rule, indentation of code is completely independent of block definition and code function. It’s possible to write code that is indented in a manner that does not actually match how the code executes, thus creating a mistaken impression when a person just glances at it. This sort of mistake is virtually impossible to make in Python.
    • Use of indentation to define blocks forces you to maintain code formatting standards you probably should be using anyway.
    • Python对缩进的使用是干净,简洁和一致的。
    • 在不使用越位规则的编程语言中,代码的缩进完全独立于块定义和代码功能。 可能以实际上与代码的执行方式不匹配的方式编写缩进的代码,从而在一个人瞥了一眼时会产生错误的印象。 在Python中几乎不可能犯这种错误。
    • 使用缩进来定义块会迫使您保持您可能应该使用的代码格式标准。

    On the negative side:

    不利的一面:

    • Many programmers don’t like to be forced to do things a certain way. They tend to have strong opinions about what looks good and what doesn’t, and they don’t like to be shoehorned into a specific choice.
    • Some editors insert a mix of space and tab characters to the left of indented lines, which makes it difficult for the Python interpreter to determine indentation levels. On the other hand, it is frequently possible to configure editors not to do this. It generally isn’t considered desirable to have a mix of tabs and spaces in source code anyhow, no matter the language.
    • 许多程序员不喜欢被迫以某种方式做事。 他们往往对什么看起来好和什么不好有很强的意见,并且他们不喜欢被人屈服于特定的选择。
    • 一些编辑器在缩进行的左边插入空格和制表符的混合,这使得Python解释器很难确定缩进级别。 另一方面,通常可以配置编辑器不执行此操作。 无论哪种语言,通常都不会在源代码中混用制表符和空格。

    Like it or not, if you’re programming in Python, you’re stuck with the off-side rule. All control structures in Python use it, as you will see in several future tutorials.

    不管喜欢与否,如果您使用Python进行编程,则必须遵守越位规则。 如您将在以后的一些教程中看到的那样,Python中的所有控件结构都使用它。

    For what it’s worth, many programmers who have been used to languages with more traditional means of block definition have initially recoiled at Python’s way but have gotten comfortable with it and have even grown to prefer it.

    值得一提的是,许多已经习惯了使用更传统的块定义方式的语言的程序员最初都以Python的方式退缩,但是对此感到自在,甚至变得更喜欢它。

    elseelif子句 (The else and elif Clauses)

    Now you know how to use an if statement to conditionally execute a single statement or a block of several statements. It’s time to find out what else you can do.

    现在您知道了如何使用if语句有条件地执行单个语句或多个语句的块。 现在是时候找出您还能做些什么了。

    Sometimes, you want to evaluate a condition and take one path if it is true but specify an alternative path if it is not. This is accomplished with an else clause:

    有时,您希望评估条件并采用一条路径(如果为真),但指定另一条路径(如果不是)。 这是通过else子句完成的:

     if if << exprexpr >> :
        :
        << statementstatement (( ss )) >
    >
    elseelse :
        :
        << statementstatement (( ss )) >
    >
    

    If <expr> is true, the first suite is executed, and the second is skipped. If <expr> is false, the first suite is skipped and the second is executed. Either way, execution then resumes after the second suite. Both suites are defined by indentation, as described above.

    如果<expr>为true,则执行第一个套件,然后跳过第二个套件。 如果<expr>为false,则跳过第一个套件,然后执行第二个套件。 无论哪种方式,执行都将在第二套程序之后恢复。 如上所述,两个套件都由缩进定义。

    In this example, x is less than 50, so the first suite (lines 4 to 5) are executed, and the second suite (lines 7 to 8) are skipped:

    在此示例中, x小于50 ,因此将执行第一个套件(第4至5行),而跳过第二个套件(第7至8行):

    Here, on the other hand, x is greater than 50, so the first suite is passed over, and the second suite executed:

    另一方面, x大于50 ,因此第一个套件被传递,第二个套件被执行:

     >>> >>>  x x = = 120
    120
    >>>
    >>>
    >>> >>>  if if x x < < 5050 :
    :
    ...     ...     printprint (( '(first suite)''(first suite)' )
    )
    ...     ...     printprint (( 'x is small''x is small' )
    )
    ... ...  elseelse :
    :
    ...     ...     printprint (( '(second suite)''(second suite)' )
    )
    ...     ...     printprint (( 'x is large''x is large' )
    )
    ...
    ...
    (second suite)
    (second suite)
    x is large
    x is large
    

    There is also syntax for branching execution based on several alternatives. For this, use one or more elif (short for else if) clauses. Python evaluates each <expr> in turn and executes the suite corresponding to the first that is true. If none of the expressions are true, and an else clause is specified, then its suite is executed:

    还有基于多种选择的分支执行语法。 为此,请使用一个或多个elif (if缩写)。 Python依次评估每个<expr>并执行与第一个为true相对应的套件。 如果所有表达式都不为真,并且指定了else子句,则执行其套件:

    An arbitrary number of elif clauses can be specified. The else clause is optional. If it is present, there can be only one, and it must be specified last:

    可以指定任意数量的elif子句。 else子句是可选的。 如果存在,则只能有一个,并且必须最后指定:

     >>> >>>  name name = = 'Joe'
    'Joe'
    >>> >>>  if if name name == == 'Fred''Fred' :
    :
    ...     ...     printprint (( 'Hello Fred''Hello Fred' )
    )
    ... ...  elif elif name name == == 'Xander''Xander' :
    :
    ...     ...     printprint (( 'Hello Xander''Hello Xander' )
    )
    ... ...  elif elif name name == == 'Joe''Joe' :
    :
    ...     ...     printprint (( 'Hello Joe''Hello Joe' )
    )
    ... ...  elif elif name name == == 'Arnold''Arnold' :
    :
    ...     ...     printprint (( 'Hello Arnold''Hello Arnold' )
    )
    ... ...  elseelse :
    :
    ...     ...     printprint (( "I don't know who you are!""I don't know who you are!" )
    )
    ...
    ...
    Hello Joe
    Hello Joe
    

    At most, one of the code blocks specified will be executed. If an else clause isn’t included, and all the conditions are false, then none of the blocks will be executed.

    最多将执行指定的代码块之一。 如果不包括else子句,并且所有条件均为false,则不会执行任何块。

    Note: Using a lengthy if/elif/else series can be a little inelegant, especially when the actions are simple statements like print(). In many cases, there may be a more Pythonic way to accomplish the same thing.

    注意:使用冗长的if / elif / else系列可能有点不雅观,尤其是当操作是诸如print()类的简单语句时。 在许多情况下,可能会有更多的Python方式完成同一件事。

    Here’s one possible alternative to the example above using the dict.get() method:

    这是使用dict.get()方法的上述示例的一种可能替代方法:

    Recall from the tutorial on Python dictionaries that the dict.get() method searches a dictionary for the specified key and returns the associated value if it is found, or the given default value if it isn’t.

    从Python词典的教程中回想起dict.get()方法在字典中搜索指定的键,如果找到该键,则返回关联的值;如果找不到,则返回给定的默认值。

    An if statement with elif clauses uses short-circuit evaluation, analogous to what you saw with the and and or operators. Once one of the expressions is found to be true and its block is executed, none of the remaining expressions are tested. This is demonstrated below:

    带有elif子句的if语句使用短路求值,类似于您在andor运算符中看到的内容。 一旦发现其中一个表达式为真并执行了其块,则不会测试其余任何表达式。 如下所示:

     >>> >>>  var  var  # Not defined
    # Not defined
    Traceback (most recent call last):
      File Traceback (most recent call last):
      File "<pyshell#58>", line "<pyshell#58>" , line 1, in 1 , in <module>
        <module>
        var
    var
    NameError: NameError : name 'var' is not defined
    
    name 'var' is not defined
    
    >>> >>>  if if 'a' 'a' in in 'bar''bar' :
    :
    ...     ...     printprint (( 'foo''foo' )
    )
    ... ...  elif elif 11 // 00 :
    :
    ...     ...     printprint (( "This won't happen""This won't happen" )
    )
    ... ...  elif elif varvar :
    :
    ...     ...     printprint (( "This won't either""This won't either" )
    )
    ...
    ...
    foo
    foo
    

    The second expression contains a division by zero, and the third references an undefined variable var. Either would raise an error, but neither is evaluated because the first condition specified is true.

    第二个表达式包含零除,第三个表达式引用未定义的变量var 这两种情况都会引发错误,但是由于指定的第一个条件为true,因此不会进行评估。

    单行if语句 (One-Line if Statements)

    It is customary to write if <expr> on one line and <statement> indented on the following line like this:

    通常在一行上写if <expr>并在下一行写<statement>缩进,如下所示:

    But it is permissible to write an entire if statement on one line. The following is functionally equivalent to the example above:

    但是允许在一行上编写整个if语句。 以下在功能上等同于上面的示例:

     if if << exprexpr >> : : << statementstatement >
    >
    

    There can even be more than one <statement> on the same line, separated by semicolons:

    在同一行上甚至可以有多个<statement> ,用分号分隔:

    But what does this mean? There are two possible interpretations:

    但是,这是什么意思? 有两种可能的解释:

    1. If <expr> is true, execute <statement_1>.

      Then, execute <statement_2> ... <statement_n> unconditionally, irrespective of whether <expr> is true or not.

    2. If <expr> is true, execute all of <statement_1> ... <statement_n>. Otherwise, don’t execute any of them.

    1. 如果<expr>为true,则执行<statement_1>

      然后,无论<expr>是否为真,都无条件执行<statement_2> ... <statement_n>

    2. 如果<expr>为true,则执行所有<statement_1> ... <statement_n> 否则,请勿执行任何一个。

    Python takes the latter interpretation. The semicolon separating the <statements> has higher precedence than the colon following <expr>—in computer lingo, the semicolon is said to bind more tightly than the colon. Thus, the <statements> are treated as a suite, and either all of them are executed, or none of them are:

    Python采用后一种解释。 分隔<statements>的分号比<expr>之后的冒号具有更高的优先级-在计算机术语中,分号比冒号更紧密地绑定。 因此, <statements>被视为一个套件,并且要么全部执行,要么都不执行:

     >>> >>>  if if 'f' 'f' in in 'foo''foo' : : printprint (( '1''1' ); ); printprint (( '2''2' ); ); printprint (( '3''3' )
    )
    ...
    ...
    1
    1
    2
    2
    3
    3
    >>> >>>  if if 'z' 'z' in in 'foo''foo' : : printprint (( '1''1' ); ); printprint (( '2''2' ); ); printprint (( '3''3' )
    )
    ...
    ...
    

    Multiple statements may be specified on the same line as an elif or else clause as well:

    也可以在与elifelse子句相同的行上指定多个语句:

    While all of this works, and the interpreter allows it, it is generally discouraged on the grounds that it leads to poor readability, particularly for complex if statements. PEP 8 specifically recommends against it.

    尽管所有这些工作都有效,并且解释器允许这样做,但通常不建议这样做,因为它会导致可读性差,尤其是对于复杂的if语句。 PEP 8特别建议不要这样做

    As usual, it is somewhat a matter of taste. Most people would find the following more visually appealing and easier to understand at first glance than the example above:

    像往常一样,这有点有点品味。 与上面的示例相比,大多数人会发现以下内容在视觉上更具吸引力并且乍一看更容易理解:

     >>> >>>  x x = = 3
    3
    >>> >>>  if if x x == == 11 :
    :
    ...     ...     printprint (( 'foo''foo' )
    )
    ...     ...     printprint (( 'bar''bar' )
    )
    ...     ...     printprint (( 'baz''baz' )
    )
    ... ...  elif elif x x == == 22 :
    :
    ...     ...     printprint (( 'qux''qux' )
    )
    ...     ...     printprint (( 'quux''quux' )
    )
    ... ...  elseelse :
    :
    ...     ...     printprint (( 'corge''corge' )
    )
    ...     ...     printprint (( 'grault''grault' )
    )
    ...
    ...
    corge
    corge
    grault
    grault
    

    If an if statement is simple enough, though, putting it all on one line may be reasonable. Something like this probably wouldn’t raise anyone’s hackles too much:

    但是,如果if语句足够简单,则将其全部放在一行上可能是合理的。 这样的事情可能不会引起太多人的抱怨:

    条件表达式 (Conditional Expressions)

    Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in PEP 308 and green-lighted by Guido in 2005.

    Python支持一个附加的决策实体,称为条件表达式。 (在Python文档中的各个地方,它也被称为条件运算符或三元运算符。)有人在PEP 308中提出了条件表达式,以补充该语言,并在2005年被Guido批准。

    In its simplest form, the syntax of the conditional expression is as follows:

    以最简单的形式,条件表达式的语法如下:

     << expr1expr1 > > if if << conditional_exprconditional_expr > > else else << expr2expr2 >
    >
    

    This is different from the if statement forms listed above because it is not a control structure that directs the flow of program execution. It acts more like an operator that defines an expression. In the above example, <conditional_expr> is evaluated first. If it is true, the expression evaluates to <expr1>. If it is false, the expression evaluates to <expr2>.

    这与上面列出的if语句形式不同,因为它不是控制程序执行流程的控制结构。 它的行为更像是定义表达式的运算符。 在上面的示例中,首先评估<conditional_expr> 如果为true,则表达式的结果为<expr1> 如果为假,则表达式的结果为<expr2>

    Notice the non-obvious order: the middle expression is evaluated first, and based on that result, one of the expressions on the ends is returned. Here are some examples that will hopefully help clarify:

    注意非显而易见的顺序:首先对中间表达式求值,然后根据该结果返回末端的一个表达式。 以下是一些希望有助于澄清的示例:

    Note: Python’s conditional expression is similar to the <conditional_expr> ? <expr1> : <expr2> syntax used by many other languages—C, Perl and Java to name a few. In fact, the ?: operator is commonly called the ternary operator in those languages, which is probably the reason Python’s conditional expression is sometimes referred to as a ternary operator.

    注意: Python的条件表达式类似于<conditional_expr> ? <expr1> : <expr2> <conditional_expr> ? <expr1> : <expr2>语法被许多其他语言使用-C,Perl和Java仅举几例。 实际上, ?:运算符在这些语言中通常称为三元运算符,这可能是Python条件表达式有时被称为三元运算符的原因。

    You can see in PEP 308 that the <conditional_expr> ? <expr1> : <expr2> syntax was considered for Python but ultimately rejected in favor of the syntax shown above.

    您可以在PEP 308中看到<conditional_expr> ? <expr1> : <expr2> <conditional_expr> ? <expr1> : <expr2>语法在Python中已被考虑,但最终由于上面显示的语法而被拒绝。

    A common use of the conditional expression is to select variable assignment. For example, suppose you want to find the larger of two numbers. Of course, there is a built-in function max() that does just this (and more) that you could use. But suppose you want to write your own code from scratch.

    条件表达式的常见用法是选择变量分配。 例如,假设您要查找两个数字中较大的一个。 当然,有一个内置函数max()可以做到这一点(以及更多)。 但是假设您想从头开始编写自己的代码。

    You could use a standard if statement with an else clause:

    您可以使用带有else子句的标准if语句:

     >>> >>>  if if a a > > bb :
    :
    ...     ...     m m = = a
    a
    ... ...  elseelse :
    :
    ...     ...     m m = = b
    b
    ...
    ...
    

    But a conditional expression is shorter and arguably more readable as well:

    但是条件表达式更短,并且更具可读性:

    Remember that the conditional expression behaves like an expression syntactically. It can be used as part of a longer expression. The conditional expression has lower precedence than virtually all the other operators, so parentheses are needed to group it by itself.

    请记住,条件表达式在句法上的行为类似于表达式。 它可以用作较长表达式的一部分。 条件表达式的优先级实际上比所有其他运算符的优先级都低,因此需要使用括号将其自身分组。

    In the following example, the + operator binds more tightly than the conditional expression, so 1 + x and y + 2 are evaluated first, followed by the conditional expression. The parentheses in the second case are unnecessary and do not change the result:

    在下面的示例中, +运算符比条件表达式的绑定更紧密,因此首先计算1 + xy + 2 ,然后是条件表达式。 第二种情况下的括号是不必要的,不会改变结果:

     >>> >>>  x x = = y y = = 40
    
    40
    
    >>> >>>  z z = = 1 1 + + x x if if x x > > y y else else y y + + 2
    2
    >>> >>>  z
    z
    42
    
    42
    
    >>> >>>  z z = = (( 1 1 + + xx ) ) if if x x > > y y else else (( y y + + 22 )
    )
    >>> >>>  z
    z
    42
    42
    

    If you want the conditional expression to be evaluated first, you need to surround it with grouping parentheses. In the next example, (x if x > y else y) is evaluated first. The result is y, which is 40, so z is assigned 1 + 40 + 2 = 43:

    如果要先对条件表达式求值,则需要用分组括号将其括起来。 在下一个示例中,首先评估(x if x > y else y)(x if x > y else y) 结果是y ,即40 ,因此z分配为1 + 40 + 2 = 43

    If you are using a conditional expression as part of a larger expression, it probably is a good idea to use grouping parentheses for clarification even if they are not needed.

    如果将条件表达式用作较大表达式的一部分,那么即使不需要分组括号也可能是个好主意。

    Conditional expressions also use short-circuit evaluation like compound logical expressions. Portions of a conditional expression are not evaluated if they don’t need to be.

    条件表达式还使用短路评估,例如复合逻辑表达式。 如果不需要,则不评估条件表达式的部分。

    In the expression <expr1> if <conditional_expr> else <expr2>:

    在表达式<expr1> if <conditional_expr> else <expr2>

    • If <conditional_expr> is true, <expr1> is returned and <expr2> is not evaluated.
    • If <conditional_expr> is false, <expr2> is returned and <expr1> is not evaluated.
    • 如果<conditional_expr>为true,则返回<expr1> ,并且不评估<expr2>
    • 如果<conditional_expr>为假, <expr2>返回并<expr1>不评估。

    As before, you can verify this by using terms that would raise an error:

    和以前一样,您可以使用会引发错误的术语来验证这一点:

     >>> >>>  'foo' 'foo' if if True True else else 11 // 0
    0
    'foo'
    'foo'
    >>> >>>  11 // 0 0 if if False False else else 'bar'
    'bar'
    'bar'
    'bar'
    

    In both cases, the 1/0 terms are not evaluated, so no exception is raised.

    在这两种情况下,都不会评估1/0项,因此不会引发任何异常。

    Conditional expressions can also be chained together, as a sort of alternative if/elif/else structure, as shown here:

    条件表达式也可以链接在一起,作为if / elif / else结构的一种替代方案,如下所示:

    It’s not clear that this has any significant advantage over the corresponding if/elif/else statement, but it is syntactically correct Python.

    尚不清楚它相对于相应的if / elif / else语句if具有任何显着优势,但是在语法上是正确的Python。

    pass声明 (The pass Statement)

    Occasionally, you may find that you want to write what is called a code stub: a placeholder for where you will eventually put a block of code that you haven’t implemented yet.

    有时,您可能会发现您想编写所谓的代码存根:占位符,用于在该位置最终放置尚未实现的代码块。

    In languages where token delimiters are used to define blocks, like the curly braces in Perl and C, empty delimiters can be used to define a code stub. For example, the following is legitimate Perl or C code:

    在使用令牌定界符来定义块的语言中(例如Perl和C中的花括号),可以使用空的定界符来定义代码存根。 例如,以下是合法的Perl或C代码:

    # This is not Python
    if (x)
    {
    }
    # This is not Python
    if (x)
    {
    }
    

    Here, the empty curly braces define an empty block. Perl or C will evaluate the expression x, and then even if it is true, quietly do nothing.

    在这里,空花括号定义了一个空块。 Perl或C将对表达式x求值,然后即使它为true,也不要执行任何操作。

    Because Python uses indentation instead of delimiters, it is not possible to specify an empty block. If you introduce an if statement with if <expr>:, something has to come after it, either on the same line or indented on the following line.

    由于Python使用缩进而不是定界符,因此无法指定空块。 如果使用if <expr>:引入if语句, if <expr>:必须在其后加上一行,或者在下一行缩进。

    Consider this script foo.py:

    考虑以下脚本foo.py

    If you try to run foo.py, you’ll get this:

    如果尝试运行foo.py ,则会得到以下信息:

     C:UsersjohnDocumentsPythondoc>python foo.py
    C:UsersjohnDocumentsPythondoc> python foo.py
      File "foo.py", line 3
      File "foo.py", line 3
        print('foo')
        print('foo')
            ^
            ^
    IndentationError: expected an indented block
    IndentationError: expected an indented block
    

    The pass statement solves this problem in Python. It doesn’t change program behavior at all. It is used as a placeholder to keep the interpreter happy in any situation where a statement is syntactically required, but you don’t really want to do anything:

    pass语句解决了Python中的此问题。 它根本不会改变程序的行为。 在语法上需要语句的任何情况下,它都用作占位符,以使解释器满意,但您实际上并不想做任何事情:

    Now foo.py runs without error:

    现在foo.py可以foo.py运行:

     C:UsersjohnDocumentsPythondoc>python foo.py
    C:UsersjohnDocumentsPythondoc> python foo.py
    foo
    foo
    

    结论 (Conclusion)

    With the completion of this tutorial, you are beginning to write Python code that goes beyond simple sequential execution:

    完成本教程后,您将开始编写超越简单顺序执行的Python代码:

    • You were introduced to the concept of control structures. These are compound statements that alter program control flow—the order of execution of program statements.
    • You learned how to group individual statements together into a block or suite.
    • You encountered your first control structure, the if statement, which makes it possible to conditionally execute a statement or block based on evaluation of program data.
    • 向您介绍了控制结构的概念。 这些是可更改程序控制流 (程序语句的执行顺序)的复合语句。
    • 您学习了如何将单个语句组合到一个套件中
    • 您遇到了第一个控制结构if语句,它使得可以根据程序数据的评估有条件地执行一个语句或块。

    All of these concepts are crucial to developing more complex Python code.

    所有这些概念对于开发更复杂的Python代码都是至关重要的。

    The next two tutorials will present two new control structures: the while statement and the for statement. These structures facilitate iteration, execution of a statement or block of statements repeatedly.

    接下来的两个教程将介绍两个新的控件结构: while语句和for语句。 这些结构便于重复执行, 重复执行语句或语句块。

    翻译自: https://www.pybloggers.com/2018/09/conditional-statements-in-python/

    python条件语句多条件

    展开全文
  • Python 编程 if 语句用于控制程序的执行,基本形式为:if 判断条件: 执行语句…… else: 执行语句……其中”判断条件”成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。...
  • python的pass语句Prerequisite: pass ... 先决条件: Python中的pass语句 An empty function is a function that does not contain any statement within its body. If you try to write a function definitio...
  • Python中的基本语句

    千次阅读 2013-11-17 17:15:19
    本文简单的介绍下Python的几个基本语句。 print语句  print可同时打印多个表达式,只要将他们用逗号隔开。 >>> name='Gumy' >>> greet='hello' >>> print(name+',',greet) #注意这里既有用到+号,又用到逗号同时...
  • pass语句通常什么都不做。它可以表示语句,但这个程序不需要的执行相应的动作。例如: >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ... 这是常用的,用于创建最小的类: >>> ...
  • python 赋值语句

    千次阅读 2018-11-12 11:11:40
    python中语句: 赋值语句 if语句,当条件成立时运行语句块。经常与else, elif(相当于else if)配合使用。 for语句,遍列列表、字符串、字典、集合等迭代器,依次处理迭代器的每个元素。 while语句,当条件为真...
  • 条件语句Python 条件语句跟其他语言基本一致的,都是通过一条或多条语句的执行结果( True ...执行的流程图如下:Created with Raphaël 2.1.0开始条件我的操作结束yesnoif 语句的基本形式Python ,if 语句的基本形式
  • 详解Python中的循环语句的用法

    千次阅读 2017-10-14 07:25:11
    一、简介  Python的条件和循环语句,决定了程序的控制流程,体现结构的多样性。... Python中的if子句由三部分组成:关键字本身、用于判断结果真假的条件表达式以及当表达式为真或者非零时执行的代码块。if 语句
  • python语言基本语句-python基本语句

    千次阅读 2020-10-30 00:26:17
    广告关闭2017年12月,云+社区对外发布,从最开始的技术博客到现在拥有多个... 1、python语句特点 (1) if语句中括号()是可选的。 (2) 冒号(:)出现结尾,表示一个语句的结束。 (3) 分号(;)不用出现结尾。 (4) 大...
  • python中if语句和while循环语句的用法

    千次阅读 2019-04-07 15:26:07
    其实python中的if和while的使用和C语言的if和while的使用并没有多大的差距,只不过一些地方的的使用有所不同,相较之下python中的用法更为简便快捷些。 if语句 使用if语句要注意的还是缩进,if语句后面要加上...
  • Python——条件语句(if 语句

    千次阅读 2018-08-10 19:51:55
    Python ,冒号(:)用来标识语句块的开始,语句每一个语句都要缩进(缩进量相同)。当退回到和已经闭合的块一样的缩进量时,表示当前语句块已经结束。   二. 布尔变量 标准值 False 和 None 、所有类型...
  • python输出语句"print()”是式样化输出函数,用于打印输出...printf()函数是式样化输出函数,在python中输出语句print()用于打印输出。printf()函数的语法为: printf("",);最常见的一个函数(准确...
  • Python3格式化输出语句

    千次阅读 2019-06-19 20:02:16
    笨办法学Python一书是基于Python2的例子,我不想换Python2,练习Python输出语句时想试试一次输出多个变量值。 方法 print("%s,%d,%d"%(name ,age ,school)) 注意:双引号后面没有逗号“,”,C/C++printf()函数...
  • Python之循环语句

    2018-09-19 15:10:02
    一、循环语句简介: Python中的循环语句有 for 和 ...在Python中没有do..while循环 代码块表现形式: while 判断条件: 语句   2、普通while循环代码示例: # 输出1-100的所有数的和 count = 0 num = 0 ...
  • python print 函数与print语句区别

    千次阅读 2017-07-11 14:25:57
    在Python 2,print语句最简单的使用形式就是print A,这相当于执行了sys.stdout.write(str(A) + '\n')。如果你以逗号为分隔符,传递额外的参数(argument),这些参数会被传递至str()函数,最终打印时每个参数之间...
  • python循环语句

    2015-07-26 14:46:09
    Python提供了for循环和while循环(在Python中没有do..while循环),其中break continue的作用跟C/C++ java一样: 1. while 循环 给定的判断条件为 true 时执行循环体,否则退出循环体。 2. for 循环 重复执行...
  • 当程序出错时,python会自动触发异常,也可以通过raise语句触发异常;一旦执行了raise语句,之后的语句不再执行;但如果加入了try...excepet...finally语句,except里的语句会被执行,finally一样也会被执行。 ...
  • python 入门题库————python语句和基础数理

    万次阅读 多人点赞 2018-10-25 15:59:07
    python 入门题库python 题库Python使用符号_______表示注释Python不支持的数据类型有查看python版本的命令是在Python中,print(type(16/4))的结果是什么类型的在Python3,执行下列语句后的显示结果是执行下列语句...
  • Python学习笔记 —— 逻辑语句

    千次阅读 2016-06-04 15:22:48
    一、 条件语句Python条件语句与其他语言一样都是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。如:if condition1: code ... elif condition2: code... else: code...注: python语言指定...
  • 前言第一次建学习群,而且是 Python 的学习群,虽然之前深入...也欢迎大家 Gitbook 提出文章的不足。目录一、条件语句Python 条件语句跟其他语言基本一致的,都是通过一条或多条语句的执行结果( True 或者 False
  • Python循环语句

    千次阅读 2016-04-16 12:42:23
    循环语句允许我们执行一个语句语句组多次,下面是大多数编程语言的循环语句的一般形式: Python提供了for循环和while循环(在Python中没有do..while循环): 循环类型 描述 while 循环 给定的判断...
  • Python 基本语句

    千次阅读 2017-03-02 10:31:18
    (1) if语句中括号()是可选的。 (2) 冒号(:)出现结尾,表示一个语句的结束。 (3) 分号(;)不用出现结尾。 (4) 大括号不需要,而是以缩进来表示代码块的开始和结尾。 2、if语句 (1) 一般格式 if : # if语句,以...
  • python-6 流程控制语句

    万次阅读 2018-09-20 15:32:06
    循环else语句 for while 循环语句加上else语句 如果for else没有被break终止,则执行else子句 for 变量 in 对象集合 语句 else 语句 while 条件表达式 语句 else 语句 Eg: hobby = '' for i in range(1,3+1...
  • python中语句:赋值语句if语句,当条件成立时运行语句块。经常与else, elif(相当于else if)配合使用。for语句,遍列列表、字符串、字典、集合等迭代器,依次处理迭代器的每个元素。while语句,当条件为真时,...
  • 想必大家都是刚刚才开始接触python这门语言的,今天这篇文章...Python pass语句这是一个空语句,这个语句是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。python中pass语法格式如下:pass(当...
  • 程序结构 程序三种结构 顺序 循环 分支 ...注意if后面的出现的语句,如果属于if语句块,则必须同一个缩进等级 条件表达式结果为True执行if后米娜的缩进语句块 # if 语句联系一 # 如果你...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 69,398
精华内容 27,759
关键字:

在python中什么表示空语句

python 订阅