What is a python statement?
A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. The syntax for simple statements is: Show
simple_stmt ::= 7.1. Expression statements¶Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value expression_stmt ::= An expression statement evaluates the expression list (which may be a single expression). In interactive mode, if the value is not 7.2. Assignment statements¶Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects: assignment_stmt ::= ( (See section Primaries for the syntax definitions for attributeref, subscription, and slicing.) An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy). Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.
Assignment of an object to a single target is recursively defined as follows.
CPython implementation detail: In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages. Although the definition of assignment implies that overlaps between
the left-hand side and the right-hand side are ‘simultaneous’ (for example x = [0, 1] i = 0 i, x[i] = 1, 2 # i is updated, then x[i] is updated print(x) See also PEP 3132 - Extended Iterable UnpackingThe
specification for the 7.2.1. Augmented assignment statements¶Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement: augmented_assignment_stmt ::= (See section Primaries for the syntax definitions of the last three symbols.) An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once. An
augmented assignment expression like Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the
right-hand side. For example, With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations. For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments. 7.2.2. Annotated assignment statements¶Annotation assignment is the combination, in a single statement, of a variable or attribute annotation and an optional assignment statement: annotated_assignment_stmt ::= The difference from normal Assignment statements is that only single target is allowed. For simple names as assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute For expressions as assignment targets, the annotations are evaluated if in class or module scope, but not stored. If a name is annotated in a function scope, then this name is local for that scope. Annotations are never evaluated and stored in function scopes. If the right hand side is present, an annotated assignment performs the actual assignment before evaluating annotations (where applicable). If the right
hand side is not present for an expression target, then the interpreter evaluates the target except for the last See also PEP 526 - Syntax for Variable AnnotationsThe proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments. PEP 484 - Type hintsThe proposal that added the Changed in version 3.8: Now annotated assignments allow same expressions in the right hand side as the regular assignments. Previously, some expressions (like un-parenthesized tuple expressions) caused a syntax error. 7.3. The assert statement¶Assert statements are a convenient way to insert debugging assertions into a program: assert_stmt ::= "assert" The simple form, if __debug__: if not expression: raise AssertionError The extended form, if __debug__: if not expression1: raise AssertionError(expression2) These equivalences assume that Assignments to
7.4. The pass statement¶pass_stmt ::= "pass"
def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet) 7.5. The del statement¶del_stmt ::= "del" Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints. Deletion of a target list recursively deletes each target, from left to right. Deletion of a name removes the binding of that name from the local or global namespace,
depending on whether the name occurs in a Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object). Changed in version 3.2: Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block. 7.6. The return statement¶return_stmt ::= "return" [
If an expression list is present, it is evaluated, else
When In a generator function, the In an asynchronous generator function, an empty
7.7. The yield statement¶yield_stmt ::= A yield <expr> yield from <expr> are equivalent to the yield expression statements (yield <expr>) (yield from <expr>) Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. For full details of 7.8. The raise statement¶raise_stmt ::= "raise" [ If no expressions are present, Otherwise, The type of the exception is the exception instance’s class, the value is the instance itself. A traceback object is normally created automatically when an exception is raised and attached to it as the raise Exception("foo occurred").with_traceback(tracebackobj) The >>> try: ... print(1 / 0) ... except Exception as exc: ... raise RuntimeError("Something bad happened") from exc ... Traceback (most recent call last): File " A similar mechanism
works implicitly if a new exception is raised when an exception is already being handled. An exception may be handled when an >>> try: ... print(1 / 0) ... except: ... raise RuntimeError("Something bad happened") ... Traceback (most recent call last): File " Exception chaining can be explicitly suppressed by specifying >>> try: ... print(1 / 0) ... except: ... raise RuntimeError("Something bad happened") from None ... Traceback (most recent call last): File " Additional information on exceptions can be found in section Exceptions, and information about handling exceptions is in section The try statement. Changed in version 3.3: New in version 3.3: The 7.9. The break statement¶break_stmt ::= "break"
It terminates the nearest enclosing loop, skipping the optional If a When 7.10. The continue statement¶continue_stmt ::= "continue"
When
7.11. The import statement¶import_stmt ::= "import" The basic import statement (no
When the statement contains multiple clauses (separated by commas) the two steps are carried out separately for each clause, just as though the clauses had been separated out into individual import statements. The details of the first step, finding and loading modules are described in greater detail in the section on the import system, which also describes the various types of packages and modules that can be imported, as well as all the hooks that can be used to customize the import system. Note that failures in this step may indicate either that the module could not be located, or that an error occurred while initializing the module, which includes execution of the module’s code. If the requested module is retrieved successfully, it will be made available in the local namespace in one of three ways:
The
Examples: import foo # foo imported and bound locally import foo.bar.baz # foo, foo.bar, and foo.bar.baz imported, foo bound locally import foo.bar.baz as fbb # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as fbb from foo.bar import baz # foo, foo.bar, and foo.bar.baz imported, foo.bar.baz bound as baz from foo import attr # foo imported and foo.attr bound as attr If the list of identifiers is replaced by a
star ( The public names defined by a module are determined by checking the module’s namespace for a variable named The wild card form of import — When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention
the package name. By using leading dots in the specified module or package after
Raises an auditing event 7.11.1. Future statements¶A future statement is a directive to the compiler that a particular module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard. The future statement is intended to ease migration to future versions of Python that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard. future_stmt ::= "from" "__future__" "import" A future statement must appear near the top of the module. The only lines that can appear before a future statement are:
The only feature that requires using the future
statement is All historical features enabled by the future statement are still recognized by Python 3. The list includes A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime. For any given release, the compiler knows which feature names have been defined, and raises a compile-time error if a future statement contains a feature not known to it. The direct runtime semantics are the same as for any import statement: there is a standard module The interesting runtime semantics depend on the specific feature enabled by the future statement. Note that there is nothing special about the statement: import __future__ [as name] That is not a future statement; it’s an ordinary import statement with no special semantics or syntax restrictions. Code compiled by calls to the built-in functions A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is
started with the See also PEP 236 - Back to the __future__The original proposal for the __future__ mechanism. 7.12. The global statement¶global_stmt ::= "global" The Names listed in a Names listed in a
CPython implementation detail: The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program. Programmer’s note: 7.13. The nonlocal statement¶nonlocal_stmt ::= "nonlocal" The
Names listed in a
Names listed in a
See also PEP 3104 - Access to Names in Outer ScopesThe specification for the
What is statement in Python with example?Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an assignment statement. if statement, for statement, while statement, etc. are other kinds of statements which will be discussed later.
What are the three statements in Python?Python 3 - IF...ELIF...ELSE Statements.
What is a statement in code?In computer programming, a statement is a single line of code that performs a specific task. For example, the following line of programming code from the Perl programming language is an example of a statement. $a = 3; In this example statement, a variable ($a) is assigned the value of "3" that is stored as a string.
What is statement and function in Python?A statement is a syntax construct. A function is an object. There's statements to create functions, like def : def Spam(): pass. So statements are one of the ways to indicate to Python that you want it to create a function.
|