Simple Assignment Statement


6.3 Assignment statements

Assignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:

assignment_stmt: (target_list "=")+ expression_list target_list: target ("," target)* [","] target: identifier | "(" target_list ")" | "[" target_list "]" | attributeref | subscription | slicing

(See section for the syntax definitions for the last three symbols.)

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 ).

Assignment of an object to a target list is recursively defined as follows.

  • If the target list is a single target: The object is assigned to that target.
  • If the target list is a comma-separated list of targets: The object must be a sequence with the same number of items as the there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets. (This rule is relaxed as of Python 1.5; in earlier versions, the object had to be a tuple. Since strings are sequences, an assignment like "" is now legal as long as the string has the right length.)

Assignment of an object to a single target is recursively defined as follows.

  • If the target is an identifier (name):
    • If the name does not occur in a statement in the current code block: the name is bound to the object in the current local namespace.
    • Otherwise: the name is bound to the object in the current global namespace.

    The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called.

  • If the target is a target list enclosed in parentheses or in square brackets: The object must be a sequence with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.
  • If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily ).
  • If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (e.g., a list) or a mapping object (e.g., a dictionary). Next, the subscript expression is evaluated.

    If the primary is a mutable sequence object (e.g., a list), the subscript must yield a plain integer. If it is negative, the sequence's length is added to it. The resulting value must be a nonnegative integer less than the sequence's length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, is raised (assignment to a subscripted sequence cannot add new items to a list).

    If the primary is a mapping object (e.g., a dictionary), the subscript must have a type compatible with the mapping's key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

  • If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (e.g., a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence's length. The bounds should evaluate to (small) integers. If either bound is negative, the sequence's length is added to it. The resulting bounds are clipped to lie between zero and the sequence's length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the object allows it.

(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.)

WARNING: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are `safe' (e.g., "" swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints "":

x = [0, 1] i = 0 i, x[i] = 1, 2 print x

Subsections
See About this document... for information on suggesting changes.

Statements in Visual Basic

A statement in Visual Basic is a complete instruction. It can contain keywords, operators, variables, constants, and expressions. Each statement belongs to one of the following categories:

  • Declaration Statements, which name a variable, constant, or procedure, and can also specify a data type.

  • Executable Statements, which initiate actions. These statements can call a method or function, and they can loop or branch through blocks of code. Executable statements include Assignment Statements, which assign a value or expression to a variable or constant.

This topic describes each category. Also, this topic describes how to combine multiple statements on a single line and how to continue a statement over multiple lines.

Declaration Statements

You use declaration statements to name and define procedures, variables, properties, arrays, and constants. When you declare a programming element, you can also define its data type, access level, and scope. For more information, see Declared Element Characteristics.

The following example contains three declarations.

The first declaration is the statement. Together with its matching statement, it declares a procedure named . It also specifies that is , which means that any code that can refer to it can call it.

The second declaration is the statement, which declares the constant , specifying the data type and a value of 33.

The third declaration is the statement, which declares the variable . The data type is a specific object, namely an object created from the class. You can declare a variable to be of any elementary data type or of any object type that is exposed in the application you are using.

Initial Values

When the code containing a declaration statement runs, Visual Basic reserves the memory required for the declared element. If the element holds a value, Visual Basic initializes it to the default value for its data type. For more information, see "Behavior" in Dim Statement.

You can assign an initial value to a variable as part of its declaration, as the following example illustrates.

If a variable is an object variable, you can explicitly create an instance of its class when you declare it by using the New Operator keyword, as the following example illustrates.

Note that the initial value you specify in a declaration statement is not assigned to a variable until execution reaches its declaration statement. Until that time, the variable contains the default value for its data type.

Executable Statements

An executable statement performs an action. It can call a procedure, branch to another place in the code, loop through several statements, or evaluate an expression. An assignment statement is a special case of an executable statement.

The following example uses an control structure to run different blocks of code based on the value of a variable. Within each block of code, a loop runs a specified number of times.

The statement in the preceding example checks the value of the parameter . If the value is , it calls the method of . If the value is , it calls the method of . The control structure ends with .

The loop within each block calls the appropriate method a number of times equal to the value of the parameter.

Assignment Statements

Assignment statements carry out assignment operations, which consist of taking the value on the right side of the assignment operator () and storing it in the element on the left, as in the following example.

In the preceding example, the assignment statement stores the literal value 42 in the variable .

Eligible Programming Elements

The programming element on the left side of the assignment operator must be able to accept and store a value. This means it must be a variable or property that is not ReadOnly, or it must be an array element. In the context of an assignment statement, such an element is sometimes called an lvalue, for "left value."

The value on the right side of the assignment operator is generated by an expression, which can consist of any combination of literals, constants, variables, properties, array elements, other expressions, or function calls. The following example illustrates this.

The preceding example adds the value held in variable to the value held in variable , and then adds the value returned by the call to function . The total value of this expression is then stored in variable .

Data Types in Assignment Statements

In addition to numeric values, the assignment operator can also assign values, as the following example illustrates.

You can also assign values, using either a literal or a expression, as the following example illustrates.

Similarly, you can assign appropriate values to programming elements of the , , or data type. You can also assign an object instance to an element declared to be of the class from which that instance is created.

Compound Assignment Statements

Compound assignment statements first perform an operation on an expression before assigning it to a programming element. The following example illustrates one of these operators, , which increments the value of the variable on the left side of the operator by the value of the expression on the right.

The preceding example adds 1 to the value of , and then stores that new value in . It is a shorthand equivalent of the following statement:

A variety of compound assignment operations can be performed using operators of this type. For a list of these operators and more information about them, see Assignment Operators.

The concatenation assignment operator () is useful for adding a string to the end of already existing strings, as the following example illustrates.

Type Conversions in Assignment Statements

The value you assign to a variable, property, or array element must be of a data type appropriate to that destination element. In general, you should try to generate a value of the same data type as that of the destination element. However, some types can be converted to other types during assignment.

For information on converting between data types, see Type Conversions in Visual Basic. In brief, Visual Basic automatically converts a value of a given type to any other type to which it widens. A widening conversion is one in that always succeeds at run time and does not lose any data. For example, Visual Basic converts an value to when appropriate, because widens to . For more information, see Widening and Narrowing Conversions.

Narrowing conversions (those that are not widening) carry a risk of failure at run time, or of data loss. You can perform a narrowing conversion explicitly by using a type conversion function, or you can direct the compiler to perform all conversions implicitly by setting . For more information, see Implicit and Explicit Conversions.

Putting Multiple Statements on One Line

You can have multiple statements on a single line separated by the colon () character. The following example illustrates this.

Though occasionally convenient, this form of syntax makes your code hard to read and maintain. Thus, it is recommended that you keep one statement to a line.

Continuing a Statement over Multiple Lines

A statement usually fits on one line, but when it is too long, you can continue it onto the next line using a line-continuation sequence, which consists of a space followed by an underscore character () followed by a carriage return. In the following example, the executable statement is continued over two lines.

Implicit Line Continuation

In many cases, you can continue a statement on the next consecutive line without using the underscore character (_). The following table lists the syntax elements that implicitly continue the statement on the next line of code.

Syntax elementExample
After a comma ().
After an open parenthesis () or before a closing parenthesis ().
After an open curly brace () or before a closing curly brace ().

For more information, see Object Initializers: Named and Anonymous Types or Collection Initializers.
After an open embedded expression () or before the close of an embedded expression () within an XML literal.

For more information, see Embedded Expressions in XML.
After the concatenation operator ().

For more information, see Operators Listed by Functionality.
After assignment operators (, , , , , , , , , , ).

For more information, see Operators Listed by Functionality.
After binary operators (, , , , , , , , , , , , , , , , , , ) within an expression.

For more information, see Operators Listed by Functionality.
After the and operators.

For more information, see Operators Listed by Functionality.
After a member qualifier character () and before the member name. However, you must include a line-continuation character (_) following a member qualifier character when you are using the statement or supplying values in the initialization list for a type. Consider breaking the line after the assignment operator (for example, ) when you are using statements or object initialization lists.


For more information, see With...End With Statement or Object Initializers: Named and Anonymous Types.
After an XML axis property qualifier ( or or ). However, you must include a line-continuation character (_) when you specify a member qualifier when you are using the keyword.

For more information, see XML Axis Properties.
After a less-than sign (<) or before a greater-than sign () when you specify an attribute. Also after a greater-than sign () when you specify an attribute. However, you must include a line-continuation character (_) when you specify assembly-level or module-level attributes.

For more information, see Attributes overview.
Before and after query operators (, , , , , , , , , , , , , , , , , , and ). You cannot break a line between the keywords of query operators that are made up of multiple keywords (, , , and ).

For more information, see Queries.
After the keyword in a statement.

For more information, see For Each...Next Statement.
After the keyword in a collection initializer.

For more information, see Collection Initializers.

Source code is not always self-explanatory, even to the programmer who wrote it. To help document their code, therefore, most programmers make liberal use of embedded comments. Comments in code can explain a procedure or a particular instruction to anyone reading or working with it later. Visual Basic ignores comments during compilation, and they do not affect the compiled code.

Comment lines begin with an apostrophe () or followed by a space. They can be added anywhere in code, except within a string. To append a comment to a statement, insert an apostrophe or after the statement, followed by the comment. Comments can also go on their own separate line. The following example demonstrates these possibilities.

Checking Compilation Errors

If, after you type a line of code, the line is displayed with a wavy blue underline (an error message may appear as well), there is a syntax error in the statement. You must find out what is wrong with the statement (by looking in the task list, or hovering over the error with the mouse pointer and reading the error message) and correct it. Until you have fixed all syntax errors in your code, your program will fail to compile correctly.

Related Sections

0 thoughts on “Simple Assignment Statement

Leave a Reply

Your email address will not be published. Required fields are marked *