Python's Assignment Operator: Write Robust Assignments

Python's Assignment Operator: Write Robust Assignments

Table of Contents

The Assignment Statement Syntax

The assignment operator, assignments and variables, other assignment syntax, initializing and updating variables, making multiple variables refer to the same object, updating lists through indices and slices, adding and updating dictionary keys, doing parallel assignments, unpacking iterables, providing default argument values, augmented mathematical assignment operators, augmented assignments for concatenation and repetition, augmented bitwise assignment operators, annotated assignment statements, assignment expressions with the walrus operator, managed attribute assignments, define or call a function, work with classes, import modules and objects, use a decorator, access the control variable in a for loop or a comprehension, use the as keyword, access the _ special variable in an interactive session, built-in objects, named constants.

Python’s assignment operators allow you to define assignment statements . This type of statement lets you create, initialize, and update variables throughout your code. Variables are a fundamental cornerstone in every piece of code, and assignment statements give you complete control over variable creation and mutation.

Learning about the Python assignment operator and its use for writing assignment statements will arm you with powerful tools for writing better and more robust Python code.

In this tutorial, you’ll:

  • Use Python’s assignment operator to write assignment statements
  • Take advantage of augmented assignments in Python
  • Explore assignment variants, like assignment expressions and managed attributes
  • Become aware of illegal and dangerous assignments in Python

You’ll dive deep into Python’s assignment statements. To get the most out of this tutorial, you should be comfortable with several basic topics, including variables , built-in data types , comprehensions , functions , and Python keywords . Before diving into some of the later sections, you should also be familiar with intermediate topics, such as object-oriented programming , constants , imports , type hints , properties , descriptors , and decorators .

Free Source Code: Click here to download the free assignment operator source code that you’ll use to write assignment statements that allow you to create, initialize, and update variables in your code.

Assignment Statements and the Assignment Operator

One of the most powerful programming language features is the ability to create, access, and mutate variables . In Python, a variable is a name that refers to a concrete value or object, allowing you to reuse that value or object throughout your code.

To create a new variable or to update the value of an existing one in Python, you’ll use an assignment statement . This statement has the following three components:

  • A left operand, which must be a variable
  • The assignment operator ( = )
  • A right operand, which can be a concrete value , an object , or an expression

Here’s how an assignment statement will generally look in Python:

Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal —or an expression that evaluates to a value.

To execute an assignment statement like the above, Python runs the following steps:

  • Evaluate the right-hand expression to produce a concrete value or object . This value will live at a specific memory address in your computer.
  • Store the object’s memory address in the left-hand variable . This step creates a new variable if the current one doesn’t already exist or updates the value of an existing variable.

The second step shows that variables work differently in Python than in other programming languages. In Python, variables aren’t containers for objects. Python variables point to a value or object through its memory address. They store memory addresses rather than objects.

This behavior difference directly impacts how data moves around in Python, which is always by reference . In most cases, this difference is irrelevant in your day-to-day coding, but it’s still good to know.

The central component of an assignment statement is the assignment operator . This operator is represented by the = symbol, which separates two operands:

  • A value or an expression that evaluates to a concrete value

Operators are special symbols that perform mathematical , logical , and bitwise operations in a programming language. The objects (or object) on which an operator operates are called operands .

Unary operators, like the not Boolean operator, operate on a single object or operand, while binary operators act on two. That means the assignment operator is a binary operator.

Note: Like C , Python uses == for equality comparisons and = for assignments. Unlike C, Python doesn’t allow you to accidentally use the assignment operator ( = ) in an equality comparison.

Equality is a symmetrical relationship, and assignment is not. For example, the expression a == 42 is equivalent to 42 == a . In contrast, the statement a = 42 is correct and legal, while 42 = a isn’t allowed. You’ll learn more about illegal assignments later on.

The right-hand operand in an assignment statement can be any Python object, such as a number , list , string , dictionary , or even a user-defined object. It can also be an expression. In the end, expressions always evaluate to concrete objects, which is their return value.

Here are a few examples of assignments in Python:

The first two sample assignments in this code snippet use concrete values, also known as literals , to create and initialize number and greeting . The third example assigns the result of a math expression to the total variable, while the last example uses a Boolean expression.

Note: You can use the built-in id() function to inspect the memory address stored in a given variable.

Here’s a short example of how this function works:

The number in your output represents the memory address stored in number . Through this address, Python can access the content of number , which is the integer 42 in this example.

If you run this code on your computer, then you’ll get a different memory address because this value varies from execution to execution and computer to computer.

Unlike expressions, assignment statements don’t have a return value because their purpose is to make the association between the variable and its value. That’s why the Python interpreter doesn’t issue any output in the above examples.

Now that you know the basics of how to write an assignment statement, it’s time to tackle why you would want to use one.

The assignment statement is the explicit way for you to associate a name with an object in Python. You can use this statement for two main purposes:

  • Creating and initializing new variables
  • Updating the values of existing variables

When you use a variable name as the left operand in an assignment statement for the first time, you’re creating a new variable. At the same time, you’re initializing the variable to point to the value of the right operand.

On the other hand, when you use an existing variable in a new assignment, you’re updating or mutating the variable’s value. Strictly speaking, every new assignment will make the variable refer to a new value and stop referring to the old one. Python will garbage-collect all the values that are no longer referenced by any existing variable.

Assignment statements not only assign a value to a variable but also determine the data type of the variable at hand. This additional behavior is another important detail to consider in this kind of statement.

Because Python is a dynamically typed language, successive assignments to a given variable can change the variable’s data type. Changing the data type of a variable during a program’s execution is considered bad practice and highly discouraged. It can lead to subtle bugs that can be difficult to track down.

Unlike in math equations, in Python assignments, the left operand must be a variable rather than an expression or a value. For example, the following construct is illegal, and Python flags it as invalid syntax:

In this example, you have expressions on both sides of the = sign, and this isn’t allowed in Python code. The error message suggests that you may be confusing the equality operator with the assignment one, but that’s not the case. You’re really running an invalid assignment.

To correct this construct and convert it into a valid assignment, you’ll have to do something like the following:

In this code snippet, you first import the sqrt() function from the math module. Then you isolate the hypotenuse variable in the original equation by using the sqrt() function. Now your code works correctly.

Now you know what kind of syntax is invalid. But don’t get the idea that assignment statements are rigid and inflexible. In fact, they offer lots of room for customization, as you’ll learn next.

Python’s assignment statements are pretty flexible and versatile. You can write them in several ways, depending on your specific needs and preferences. Here’s a quick summary of the main ways to write assignments in Python:

Up to this point, you’ve mostly learned about the base assignment syntax in the above code snippet. In the following sections, you’ll learn about multiple, parallel, and augmented assignments. You’ll also learn about assignments with iterable unpacking.

Read on to see the assignment statements in action!

Assignment Statements in Action

You’ll find and use assignment statements everywhere in your Python code. They’re a fundamental part of the language, providing an explicit way to create, initialize, and mutate variables.

You can use assignment statements with plain names, like number or counter . You can also use assignments in more complicated scenarios, such as with:

  • Qualified attribute names , like user.name
  • Indices and slices of mutable sequences, like a_list[i] and a_list[i:j]
  • Dictionary keys , like a_dict[key]

This list isn’t exhaustive. However, it gives you some idea of how flexible these statements are. You can even assign multiple values to an equal number of variables in a single line, commonly known as parallel assignment . Additionally, you can simultaneously assign the values in an iterable to a comma-separated group of variables in what’s known as an iterable unpacking operation.

In the following sections, you’ll dive deeper into all these topics and a few other exciting things that you can do with assignment statements in Python.

The most elementary use case of an assignment statement is to create a new variable and initialize it using a particular value or expression:

All these statements create new variables, assigning them initial values or expressions. For an initial value, you should always use the most sensible and least surprising value that you can think of. For example, initializing a counter to something different from 0 may be confusing and unexpected because counters almost always start having counted no objects.

Updating a variable’s current value or state is another common use case of assignment statements. In Python, assigning a new value to an existing variable doesn’t modify the variable’s current value. Instead, it causes the variable to refer to a different value. The previous value will be garbage-collected if no other variable refers to it.

Consider the following examples:

These examples run two consecutive assignments on the same variable. The first one assigns the string "Hello, World!" to a new variable named greeting .

The second assignment updates the value of greeting by reassigning it the "Hi, Pythonistas!" string. In this example, the original value of greeting —the "Hello, World!" string— is lost and garbage-collected. From this point on, you can’t access the old "Hello, World!" string.

Even though running multiple assignments on the same variable during a program’s execution is common practice, you should use this feature with caution. Changing the value of a variable can make your code difficult to read, understand, and debug. To comprehend the code fully, you’ll have to remember all the places where the variable was changed and the sequential order of those changes.

Because assignments also define the data type of their target variables, it’s also possible for your code to accidentally change the type of a given variable at runtime. A change like this can lead to breaking errors, like AttributeError exceptions. Remember that strings don’t have the same methods and attributes as lists or dictionaries, for example.

In Python, you can make several variables reference the same object in a multiple-assignment line. This can be useful when you want to initialize several similar variables using the same initial value:

In this example, you chain two assignment operators in a single line. This way, your two variables refer to the same initial value of 0 . Note how both variables hold the same memory address, so they point to the same instance of 0 .

When it comes to integer variables, Python exhibits a curious behavior. It provides a numeric interval where multiple assignments behave the same as independent assignments. Consider the following examples:

To create n and m , you use independent assignments. Therefore, they should point to different instances of the number 42 . However, both variables hold the same object, which you confirm by comparing their corresponding memory addresses.

Now check what happens when you use a greater initial value:

Now n and m hold different memory addresses, which means they point to different instances of the integer number 300 . In contrast, when you use multiple assignments, both variables refer to the same object. This tiny difference can save you small bits of memory if you frequently initialize integer variables in your code.

The implicit behavior of making independent assignments point to the same integer number is actually an optimization called interning . It consists of globally caching the most commonly used integer values in day-to-day programming.

Under the hood, Python defines a numeric interval in which interning takes place. That’s the interning interval for integer numbers. You can determine this interval using a small script like the following:

This script helps you determine the interning interval by comparing integer numbers from -10 to 500 . If you run the script from your command line, then you’ll get an output like the following:

This output means that if you use a single number between -5 and 256 to initialize several variables in independent statements, then all these variables will point to the same object, which will help you save small bits of memory in your code.

In contrast, if you use a number that falls outside of the interning interval, then your variables will point to different objects instead. Each of these objects will occupy a different memory spot.

You can use the assignment operator to mutate the value stored at a given index in a Python list. The operator also works with list slices . The syntax to write these types of assignment statements is the following:

In the first construct, expression can return any Python object, including another list. In the second construct, expression must return a series of values as a list, tuple, or any other sequence. You’ll get a TypeError if expression returns a single value.

Note: When creating slice objects, you can use up to three arguments. These arguments are start , stop , and step . They define the number that starts the slice, the number at which the slicing must stop retrieving values, and the step between values.

Here’s an example of updating an individual value in a list:

In this example, you update the value at index 2 using an assignment statement. The original number at that index was 7 , and after the assignment, the number is 3 .

Note: Using indices and the assignment operator to update a value in a tuple or a character in a string isn’t possible because tuples and strings are immutable data types in Python.

Their immutability means that you can’t change their items in place :

You can’t use the assignment operator to change individual items in tuples or strings. These data types are immutable and don’t support item assignments.

It’s important to note that you can’t add new values to a list by using indices that don’t exist in the target list:

In this example, you try to add a new value to the end of numbers by using an index that doesn’t exist. This assignment isn’t allowed because there’s no way to guarantee that new indices will be consecutive. If you ever want to add a single value to the end of a list, then use the .append() method.

If you want to update several consecutive values in a list, then you can use slicing and an assignment statement:

In the first example, you update the letters between indices 1 and 3 without including the letter at 3 . The second example updates the letters from index 3 until the end of the list. Note that this slicing appends a new value to the list because the target slice is shorter than the assigned values.

Also note that the new values were provided through a tuple, which means that this type of assignment allows you to use other types of sequences to update your target list.

The third example updates a single value using a slice where both indices are equal. In this example, the assignment inserts a new item into your target list.

In the final example, you use a step of 2 to replace alternating letters with their lowercase counterparts. This slicing starts at index 1 and runs through the whole list, stepping by two items each time.

Updating the value of an existing key or adding new key-value pairs to a dictionary is another common use case of assignment statements. To do these operations, you can use the following syntax:

The first construct helps you update the current value of an existing key, while the second construct allows you to add a new key-value pair to the dictionary.

For example, to update an existing key, you can do something like this:

In this example, you update the current inventory of oranges in your store using an assignment. The left operand is the existing dictionary key, and the right operand is the desired new value.

While you can’t add new values to a list by assignment, dictionaries do allow you to add new key-value pairs using the assignment operator. In the example below, you add a lemon key to inventory :

In this example, you successfully add a new key-value pair to your inventory with 100 units. This addition is possible because dictionaries don’t have consecutive indices but unique keys, which are safe to add by assignment.

The assignment statement does more than assign the result of a single expression to a single variable. It can also cope nicely with assigning multiple values to multiple variables simultaneously in what’s known as a parallel assignment .

Here’s the general syntax for parallel assignments in Python:

Note that the left side of the statement can be either a tuple or a list of variables. Remember that to create a tuple, you just need a series of comma-separated elements. In this case, these elements must be variables.

The right side of the statement must be a sequence or iterable of values or expressions. In any case, the number of elements in the right operand must match the number of variables on the left. Otherwise, you’ll get a ValueError exception.

In the following example, you compute the two solutions of a quadratic equation using a parallel assignment:

In this example, you first import sqrt() from the math module. Then you initialize the equation’s coefficients in a parallel assignment.

The equation’s solution is computed in another parallel assignment. The left operand contains a tuple of two variables, x1 and x2 . The right operand consists of a tuple of expressions that compute the solutions for the equation. Note how each result is assigned to each variable by position.

A classical use case of parallel assignment is to swap values between variables:

The highlighted line does the magic and swaps the values of previous_value and next_value at the same time. Note that in a programming language that doesn’t support this kind of assignment, you’d have to use a temporary variable to produce the same effect:

In this example, instead of using parallel assignment to swap values between variables, you use a new variable to temporarily store the value of previous_value to avoid losing its reference.

For a concrete example of when you’d need to swap values between variables, say you’re learning how to implement the bubble sort algorithm , and you come up with the following function:

In the highlighted line, you use a parallel assignment to swap values in place if the current value is less than the next value in the input list. To dive deeper into the bubble sort algorithm and into sorting algorithms in general, check out Sorting Algorithms in Python .

You can use assignment statements for iterable unpacking in Python. Unpacking an iterable means assigning its values to a series of variables one by one. The iterable must be the right operand in the assignment, while the variables must be the left operand.

Like in parallel assignments, the variables must come as a tuple or list. The number of variables must match the number of values in the iterable. Alternatively, you can use the unpacking operator ( * ) to grab several values in a variable if the number of variables doesn’t match the iterable length.

Here’s the general syntax for iterable unpacking in Python:

Iterable unpacking is a powerful feature that you can use all around your code. It can help you write more readable and concise code. For example, you may find yourself doing something like this:

Whenever you do something like this in your code, go ahead and replace it with a more readable iterable unpacking using a single and elegant assignment, like in the following code snippet:

The numbers list on the right side contains four values. The assignment operator unpacks these values into the four variables on the left side of the statement. The values in numbers get assigned to variables in the same order that they appear in the iterable. The assignment is done by position.

Note: Because Python sets are also iterables, you can use them in an iterable unpacking operation. However, it won’t be clear which value goes to which variable because sets are unordered data structures.

The above example shows the most common form of iterable unpacking in Python. The main condition for the example to work is that the number of variables matches the number of values in the iterable.

What if you don’t know the iterable length upfront? Will the unpacking work? It’ll work if you use the * operator to pack several values into one of your target variables.

For example, say that you want to unpack the first and second values in numbers into two different variables. Additionally, you would like to pack the rest of the values in a single variable conveniently called rest . In this case, you can use the unpacking operator like in the following code:

In this example, first and second hold the first and second values in numbers , respectively. These values are assigned by position. The * operator packs all the remaining values in the input iterable into rest .

The unpacking operator ( * ) can appear at any position in your series of target variables. However, you can only use one instance of the operator:

The iterable unpacking operator works in any position in your list of variables. Note that you can only use one unpacking operator per assignment. Using more than one unpacking operator isn’t allowed and raises a SyntaxError .

Dropping away unwanted values from the iterable is a common use case for the iterable unpacking operator. Consider the following example:

In Python, if you want to signal that a variable won’t be used, then you use an underscore ( _ ) as the variable’s name. In this example, useful holds the only value that you need to use from the input iterable. The _ variable is a placeholder that guarantees that the unpacking works correctly. You won’t use the values that end up in this disposable variable.

Note: In the example above, if your target iterable is a sequence data type, such as a list or tuple, then it’s best to access its last item directly.

To do this, you can use the -1 index:

Using -1 gives you access to the last item of any sequence data type. In contrast, if you’re dealing with iterators , then you won’t be able to use indices. That’s when the *_ syntax comes to your rescue.

The pattern used in the above example comes in handy when you have a function that returns multiple values, and you only need a few of these values in your code. The os.walk() function may provide a good example of this situation.

This function allows you to iterate over the content of a directory recursively. The function returns a generator object that yields three-item tuples. Each tuple contains the following items:

  • The path to the current directory as a string
  • The names of all the immediate subdirectories as a list of strings
  • The names of all the files in the current directory as a list of strings

Now say that you want to iterate over your home directory and list only the files. You can do something like this:

This code will issue a long output depending on the current content of your home directory. Note that you need to provide a string with the path to your user folder for the example to work. The _ placeholder variable will hold the unwanted data.

In contrast, the filenames variable will hold the list of files in the current directory, which is the data that you need. The code will print the list of filenames. Go ahead and give it a try!

The assignment operator also comes in handy when you need to provide default argument values in your functions and methods. Default argument values allow you to define functions that take arguments with sensible defaults. These defaults allow you to call the function with specific values or to simply rely on the defaults.

As an example, consider the following function:

This function takes one argument, called name . This argument has a sensible default value that’ll be used when you call the function without arguments. To provide this sensible default value, you use an assignment.

Note: According to PEP 8 , the style guide for Python code, you shouldn’t use spaces around the assignment operator when providing default argument values in function definitions.

Here’s how the function works:

If you don’t provide a name during the call to greet() , then the function uses the default value provided in the definition. If you provide a name, then the function uses it instead of the default one.

Up to this point, you’ve learned a lot about the Python assignment operator and how to use it for writing different types of assignment statements. In the following sections, you’ll dive into a great feature of assignment statements in Python. You’ll learn about augmented assignments .

Augmented Assignment Operators in Python

Python supports what are known as augmented assignments . An augmented assignment combines the assignment operator with another operator to make the statement more concise. Most Python math and bitwise operators have an augmented assignment variation that looks something like this:

Note that $ isn’t a valid Python operator. In this example, it’s a placeholder for a generic operator. This statement works as follows:

  • Evaluate expression to produce a value.
  • Run the operation defined by the operator that prefixes the = sign, using the previous value of variable and the return value of expression as operands.
  • Assign the resulting value back to variable .

In practice, an augmented assignment like the above is equivalent to the following statement:

As you can conclude, augmented assignments are syntactic sugar . They provide a shorthand notation for a specific and popular kind of assignment.

For example, say that you need to define a counter variable to count some stuff in your code. You can use the += operator to increment counter by 1 using the following code:

In this example, the += operator, known as augmented addition , adds 1 to the previous value in counter each time you run the statement counter += 1 .

It’s important to note that unlike regular assignments, augmented assignments don’t create new variables. They only allow you to update existing variables. If you use an augmented assignment with an undefined variable, then you get a NameError :

Python evaluates the right side of the statement before assigning the resulting value back to the target variable. In this specific example, when Python tries to compute x + 1 , it finds that x isn’t defined.

Great! You now know that an augmented assignment consists of combining the assignment operator with another operator, like a math or bitwise operator. To continue this discussion, you’ll learn which math operators have an augmented variation in Python.

An equation like x = x + b doesn’t make sense in math. But in programming, a statement like x = x + b is perfectly valid and can be extremely useful. It adds b to x and reassigns the result back to x .

As you already learned, Python provides an operator to shorten x = x + b . Yes, the += operator allows you to write x += b instead. Python also offers augmented assignment operators for most math operators. Here’s a summary:

Operator Description Example Equivalent
Adds the right operand to the left operand and stores the result in the left operand
Subtracts the right operand from the left operand and stores the result in the left operand
Multiplies the right operand with the left operand and stores the result in the left operand
Divides the left operand by the right operand and stores the result in the left operand
Performs of the left operand by the right operand and stores the result in the left operand
Finds the remainder of dividing the left operand by the right operand and stores the result in the left operand
Raises the left operand to the power of the right operand and stores the result in the left operand

The Example column provides generic examples of how to use the operators in actual code. Note that x must be previously defined for the operators to work correctly. On the other hand, y can be either a concrete value or an expression that returns a value.

Note: The matrix multiplication operator ( @ ) doesn’t support augmented assignments yet.

Consider the following example of matrix multiplication using NumPy arrays:

Note that the exception traceback indicates that the operation isn’t supported yet.

To illustrate how augmented assignment operators work, say that you need to create a function that takes an iterable of numeric values and returns their sum. You can write this function like in the code below:

In this function, you first initialize total to 0 . In each iteration, the loop adds a new number to total using the augmented addition operator ( += ). When the loop terminates, total holds the sum of all the input numbers. Variables like total are known as accumulators . The += operator is typically used to update accumulators.

Note: Computing the sum of a series of numeric values is a common operation in programming. Python provides the built-in sum() function for this specific computation.

Another interesting example of using an augmented assignment is when you need to implement a countdown while loop to reverse an iterable. In this case, you can use the -= operator:

In this example, custom_reversed() is a generator function because it uses yield . Calling the function creates an iterator that yields items from the input iterable in reverse order. To decrement the control variable, index , you use an augmented subtraction statement that subtracts 1 from the variable in every iteration.

Note: Similar to summing the values in an iterable, reversing an iterable is also a common requirement. Python provides the built-in reversed() function for this specific computation, so you don’t have to implement your own. The above example only intends to show the -= operator in action.

Finally, counters are a special type of accumulators that allow you to count objects. Here’s an example of a letter counter:

To create this counter, you use a Python dictionary. The keys store the letters. The values store the counts. Again, to increment the counter, you use an augmented addition.

Counters are so common in programming that Python provides a tool specially designed to facilitate the task of counting. Check out Python’s Counter: The Pythonic Way to Count Objects for a complete guide on how to use this tool.

The += and *= augmented assignment operators also work with sequences , such as lists, tuples, and strings. The += operator performs augmented concatenations , while the *= operator performs augmented repetition .

These operators behave differently with mutable and immutable data types:

Operator Description Example
Runs an augmented concatenation operation on the target sequence. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.
Adds to itself times. Mutable sequences are updated in place. If the sequence is immutable, then a new sequence is created and assigned back to the target name.

Note that the augmented concatenation operator operates on two sequences, while the augmented repetition operator works on a sequence and an integer number.

Consider the following examples and pay attention to the result of calling the id() function:

Mutable sequences like lists support the += augmented assignment operator through the .__iadd__() method, which performs an in-place addition. This method mutates the underlying list, appending new values to its end.

Note: If the left operand is mutable, then x += y may not be completely equivalent to x = x + y . For example, if you do list_1 = list_1 + list_2 instead of list_1 += list_2 above, then you’ll create a new list instead of mutating the existing one. This may be important if other variables refer to the same list.

Immutable sequences, such as tuples and strings, don’t provide an .__iadd__() method. Therefore, augmented concatenations fall back to the .__add__() method, which doesn’t modify the sequence in place but returns a new sequence.

There’s another difference between mutable and immutable sequences when you use them in an augmented concatenation. Consider the following examples:

With mutable sequences, the data to be concatenated can come as a list, tuple, string, or any other iterable. In contrast, with immutable sequences, the data can only come as objects of the same type. You can concatenate tuples to tuples and strings to strings, for example.

Again, the augmented repetition operator works with a sequence on the left side of the operator and an integer on the right side. This integer value represents the number of repetitions to get in the resulting sequence:

When the *= operator operates on a mutable sequence, it falls back to the .__imul__() method, which performs the operation in place, modifying the underlying sequence. In contrast, if *= operates on an immutable sequence, then .__mul__() is called, returning a new sequence of the same type.

Note: Values of n less than 0 are treated as 0 , which returns an empty sequence of the same data type as the target sequence on the left side of the *= operand.

Note that a_list[0] is a_list[3] returns True . This is because the *= operator doesn’t make a copy of the repeated data. It only reflects the data. This behavior can be a source of issues when you use the operator with mutable values.

For example, say that you want to create a list of lists to represent a matrix, and you need to initialize the list with n empty lists, like in the following code:

In this example, you use the *= operator to populate matrix with three empty lists. Now check out what happens when you try to populate the first sublist in matrix :

The appended values are reflected in the three sublists. This happens because the *= operator doesn’t make copies of the data that you want to repeat. It only reflects the data. Therefore, every sublist in matrix points to the same object and memory address.

If you ever need to initialize a list with a bunch of empty sublists, then use a list comprehension :

This time, when you populate the first sublist of matrix , your changes aren’t propagated to the other sublists. This is because all the sublists are different objects that live in different memory addresses.

Bitwise operators also have their augmented versions. The logic behind them is similar to that of the math operators. The following table summarizes the augmented bitwise operators that Python provides:

Operator Operation Example Equivalent
Augmented bitwise AND ( )
Augmented bitwise OR ( )
Augmented bitwise XOR ( )
Augmented bitwise right shift
Augmented bitwise left shift

The augmented bitwise assignment operators perform the intended operation by taking the current value of the left operand as a starting point for the computation. Consider the following example, which uses the & and &= operators:

Programmers who work with high-level languages like Python rarely use bitwise operations in day-to-day coding. However, these types of operations can be useful in some situations.

For example, say that you’re implementing a Unix-style permission system for your users to access a given resource. In this case, you can use the characters "r" for reading, "w" for writing, and "x" for execution permissions, respectively. However, using bit-based permissions could be more memory efficient:

You can assign permissions to your users with the OR bitwise operator or the augmented OR bitwise operator. Finally, you can use the bitwise AND operator to check if a user has a certain permission, as you did in the final two examples.

You’ve learned a lot about augmented assignment operators and statements in this and the previous sections. These operators apply to math, concatenation, repetition, and bitwise operations. Now you’re ready to look at other assignment variants that you can use in your code or find in other developers’ code.

Other Assignment Variants

So far, you’ve learned that Python’s assignment statements and the assignment operator are present in many different scenarios and use cases. Those use cases include variable creation and initialization, parallel assignments, iterable unpacking, augmented assignments, and more.

In the following sections, you’ll learn about a few variants of assignment statements that can be useful in your future coding. You can also find these assignment variants in other developers’ code. So, you should be aware of them and know how they work in practice.

In short, you’ll learn about:

  • Annotated assignment statements with type hints
  • Assignment expressions with the walrus operator
  • Managed attribute assignments with properties and descriptors
  • Implicit assignments in Python

These topics will take you through several interesting and useful examples that showcase the power of Python’s assignment statements.

PEP 526 introduced a dedicated syntax for variable annotation back in Python 3.6 . The syntax consists of the variable name followed by a colon ( : ) and the variable type:

Even though these statements declare three variables with their corresponding data types, the variables aren’t actually created or initialized. So, for example, you can’t use any of these variables in an augmented assignment statement:

If you try to use one of the previously declared variables in an augmented assignment, then you get a NameError because the annotation syntax doesn’t define the variable. To actually define it, you need to use an assignment.

The good news is that you can use the variable annotation syntax in an assignment statement with the = operator:

The first statement in this example is what you can call an annotated assignment statement in Python. You may ask yourself why you should use type annotations in this type of assignment if everybody can see that counter holds an integer number. You’re right. In this example, the variable type is unambiguous.

However, imagine what would happen if you found a variable initialization like the following:

What would be the data type of each user in users ? If the initialization of users is far away from the definition of the User class, then there’s no quick way to answer this question. To clarify this ambiguity, you can provide the appropriate type hint for users :

Now you’re clearly communicating that users will hold a list of User instances. Using type hints in assignment statements that initialize variables to empty collection data types—such as lists, tuples, or dictionaries—allows you to provide more context about how your code works. This practice will make your code more explicit and less error-prone.

Up to this point, you’ve learned that regular assignment statements with the = operator don’t have a return value. They just create or update variables. Therefore, you can’t use a regular assignment to assign a value to a variable within the context of an expression.

Python 3.8 changed this by introducing a new type of assignment statement through PEP 572 . This new statement is known as an assignment expression or named expression .

Note: Expressions are a special type of statement in Python. Their distinguishing characteristic is that expressions always have a return value, which isn’t the case with all types of statements.

Unlike regular assignments, assignment expressions have a return value, which is why they’re called expressions in the first place. This return value is automatically assigned to a variable. To write an assignment expression, you must use the walrus operator ( := ), which was named for its resemblance to the eyes and tusks of a walrus lying on its side.

The general syntax of an assignment statement is as follows:

This expression looks like a regular assignment. However, instead of using the assignment operator ( = ), it uses the walrus operator ( := ). For the expression to work correctly, the enclosing parentheses are required in most use cases. However, there are certain situations in which these parentheses are superfluous. Either way, they won’t hurt you.

Assignment expressions come in handy when you want to reuse the result of an expression or part of an expression without using a dedicated assignment to grab this value beforehand.

Note: Assignment expressions with the walrus operator have several practical use cases. They also have a few restrictions. For example, they’re illegal in certain contexts, such as lambda functions, parallel assignments, and augmented assignments.

For a deep dive into this special type of assignment, check out The Walrus Operator: Python’s Assignment Expressions .

A particularly handy use case for assignment expressions is when you need to grab the result of an expression used in the context of a conditional statement. For example, say that you need to write a function to compute the mean of a sample of numeric values. Without the walrus operator, you could do something like this:

In this example, the sample size ( n ) is a value that you need to reuse in two different computations. First, you need to check whether the sample has data points or not. Then you need to use the sample size to compute the mean. To be able to reuse n , you wrote a dedicated assignment statement at the beginning of your function to grab the sample size.

You can avoid this extra step by combining it with the first use of the target value, len(sample) , using an assignment expression like the following:

The assignment expression introduced in the conditional computes the sample size and assigns it to n . This way, you guarantee that you have a reference to the sample size to use in further computations.

Because the assignment expression returns the sample size anyway, the conditional can check whether that size equals 0 or not and then take a certain course of action depending on the result of this check. The return statement computes the sample’s mean and sends the result back to the function caller.

Python provides a few tools that allow you to fine-tune the operations behind the assignment of attributes. The attributes that run implicit operations on assignments are commonly referred to as managed attributes .

Properties are the most commonly used tool for providing managed attributes in your classes. However, you can also use descriptors and, in some cases, the .__setitem__() special method.

To understand what fine-tuning the operation behind an assignment means, say that you need a Point class that only allows numeric values for its coordinates, x and y . To write this class, you must set up a validation mechanism to reject non-numeric values. You can use properties to attach the validation functionality on top of x and y .

Here’s how you can write your class:

In Point , you use properties for the .x and .y coordinates. Each property has a getter and a setter method . The getter method returns the attribute at hand. The setter method runs the input validation using a try … except block and the built-in float() function. Then the method assigns the result to the actual attribute.

Here’s how your class works in practice:

When you use a property-based attribute as the left operand in an assignment statement, Python automatically calls the property’s setter method, running any computation from it.

Because both .x and .y are properties, the input validation runs whenever you assign a value to either attribute. In the first example, the input values are valid numbers and the validation passes. In the final example, "one" isn’t a valid numeric value, so the validation fails.

If you look at your Point class, you’ll note that it follows a repetitive pattern, with the getter and setter methods looking quite similar. To avoid this repetition, you can use a descriptor instead of a property.

A descriptor is a class that implements the descriptor protocol , which consists of four special methods :

  • .__get__() runs when you access the attribute represented by the descriptor.
  • .__set__() runs when you use the attribute in an assignment statement.
  • .__delete__() runs when you use the attribute in a del statement.
  • .__set_name__() sets the attribute’s name, creating a name-aware attribute.

Here’s how your code may look if you use a descriptor to represent the coordinates of your Point class:

You’ve removed repetitive code by defining Coordinate as a descriptor that manages the input validation in a single place. Go ahead and run the following code to try out the new implementation of Point :

Great! The class works as expected. Thanks to the Coordinate descriptor, you now have a more concise and non-repetitive version of your original code.

Another way to fine-tune the operations behind an assignment statement is to provide a custom implementation of .__setitem__() in your class. You’ll use this method in classes representing mutable data collections, such as custom list-like or dictionary-like classes.

As an example, say that you need to create a dictionary-like class that stores its keys in lowercase letters:

In this example, you create a dictionary-like class by subclassing UserDict from collections . Your class implements a .__setitem__() method, which takes key and value as arguments. The method uses str.lower() to convert key into lowercase letters before storing it in the underlying dictionary.

Python implicitly calls .__setitem__() every time you use a key as the left operand in an assignment statement. This behavior allows you to tweak how you process the assignment of keys in your custom dictionary.

Implicit Assignments in Python

Python implicitly runs assignments in many different contexts. In most cases, these implicit assignments are part of the language syntax. In other cases, they support specific behaviors.

Whenever you complete an action in the following list, Python runs an implicit assignment for you:

  • Define or call a function
  • Define or instantiate a class
  • Use the current instance , self
  • Import modules and objects
  • Use a decorator
  • Use the control variable in a for loop or a comprehension
  • Use the as qualifier in with statements , imports, and try … except blocks
  • Access the _ special variable in an interactive session

Behind the scenes, Python performs an assignment in every one of the above situations. In the following subsections, you’ll take a tour of all these situations.

When you define a function, the def keyword implicitly assigns a function object to your function’s name. Here’s an example:

From this point on, the name greet refers to a function object that lives at a given memory address in your computer. You can call the function using its name and a pair of parentheses with appropriate arguments. This way, you can reuse greet() wherever you need it.

If you call your greet() function with fellow as an argument, then Python implicitly assigns the input argument value to the name parameter on the function’s definition. The parameter will hold a reference to the input arguments.

When you define a class with the class keyword, you’re assigning a specific name to a class object . You can later use this name to create instances of that class. Consider the following example:

In this example, the name User holds a reference to a class object, which was defined in __main__.User . Like with a function, when you call the class’s constructor with the appropriate arguments to create an instance, Python assigns the arguments to the parameters defined in the class initializer .

Another example of implicit assignments is the current instance of a class, which in Python is called self by convention. This name implicitly gets a reference to the current object whenever you instantiate a class. Thanks to this implicit assignment, you can access .name and .job from within the class without getting a NameError in your code.

Import statements are another variant of implicit assignments in Python. Through an import statement, you assign a name to a module object, class, function, or any other imported object. This name is then created in your current namespace so that you can access it later in your code:

In this example, you import the sys module object from the standard library and assign it to the sys name, which is now available in your namespace, as you can conclude from the second call to the built-in dir() function.

You also run an implicit assignment when you use a decorator in your code. The decorator syntax is just a shortcut for a formal assignment like the following:

Here, you call decorator() with a function object as an argument. This call will typically add functionality on top of the existing function, func() , and return a function object, which is then reassigned to the func name.

The decorator syntax is syntactic sugar for replacing the previous assignment, which you can now write as follows:

Even though this new code looks pretty different from the above assignment, the code implicitly runs the same steps.

Another situation in which Python automatically runs an implicit assignment is when you use a for loop or a comprehension. In both cases, you can have one or more control variables that you then use in the loop or comprehension body:

The memory address of control_variable changes on each iteration of the loop. This is because Python internally reassigns a new value from the loop iterable to the loop control variable on each cycle.

The same behavior appears in comprehensions:

In the end, comprehensions work like for loops but use a more concise syntax. This comprehension creates a new list of strings that mimic the output from the previous example.

The as keyword in with statements, except clauses, and import statements is another example of an implicit assignment in Python. This time, the assignment isn’t completely implicit because the as keyword provides an explicit way to define the target variable.

In a with statement, the target variable that follows the as keyword will hold a reference to the context manager that you’re working with. As an example, say that you have a hello.txt file with the following content:

You want to open this file and print each of its lines on your screen. In this case, you can use the with statement to open the file using the built-in open() function.

In the example below, you accomplish this. You also add some calls to print() that display information about the target variable defined by the as keyword:

This with statement uses the open() function to open hello.txt . The open() function is a context manager that returns a text file object represented by an io.TextIOWrapper instance.

Since you’ve defined a hello target variable with the as keyword, now that variable holds a reference to the file object itself. You confirm this by printing the object and its memory address. Finally, the for loop iterates over the lines and prints this content to the screen.

When it comes to using the as keyword in the context of an except clause, the target variable will contain an exception object if any exception occurs:

In this example, you run a division that raises a ZeroDivisionError . The as keyword assigns the raised exception to error . Note that when you print the exception object, you get only the message because exceptions have a custom .__str__() method that supports this behavior.

There’s a final detail to remember when using the as specifier in a try … except block like the one in the above example. Once you leave the except block, the target variable goes out of scope , and you can’t use it anymore.

Finally, Python’s import statements also support the as keyword. In this context, you can use as to import objects with a different name:

In these examples, you use the as keyword to import the numpy package with the np name and pandas with the name pd . If you call dir() , then you’ll realize that np and pd are now in your namespace. However, the numpy and pandas names are not.

Using the as keyword in your imports comes in handy when you want to use shorter names for your objects or when you need to use different objects that originally had the same name in your code. It’s also useful when you want to make your imported names non-public using a leading underscore, like in import sys as _sys .

The final implicit assignment that you’ll learn about in this tutorial only occurs when you’re using Python in an interactive session. Every time you run a statement that returns a value, the interpreter stores the result in a special variable denoted by a single underscore character ( _ ).

You can access this special variable as you’d access any other variable:

These examples cover several situations in which Python internally uses the _ variable. The first two examples evaluate expressions. Expressions always have a return value, which is automatically assigned to the _ variable every time.

When it comes to function calls, note that if your function returns a fruitful value, then _ will hold it. In contrast, if your function returns None , then the _ variable will remain untouched.

The next example consists of a regular assignment statement. As you already know, regular assignments don’t return any value, so the _ variable isn’t updated after these statements run. Finally, note that accessing a variable in an interactive session returns the value stored in the target variable. This value is then assigned to the _ variable.

Note that since _ is a regular variable, you can use it in other expressions:

In this example, you first create a list of values. Then you call len() to get the number of values in the list. Python automatically stores this value in the _ variable. Finally, you use _ to compute the mean of your list of values.

Now that you’ve learned about some of the implicit assignments that Python runs under the hood, it’s time to dig into a final assignment-related topic. In the following few sections, you’ll learn about some illegal and dangerous assignments that you should be aware of and avoid in your code.

Illegal and Dangerous Assignments in Python

In Python, you’ll find a few situations in which using assignments is either forbidden or dangerous. You must be aware of these special situations and try to avoid them in your code.

In the following sections, you’ll learn when using assignment statements isn’t allowed in Python. You’ll also learn about some situations in which using assignments should be avoided if you want to keep your code consistent and robust.

You can’t use Python keywords as variable names in assignment statements. This kind of assignment is explicitly forbidden. If you try to use a keyword as a variable name in an assignment, then you get a SyntaxError :

Whenever you try to use a keyword as the left operand in an assignment statement, you get a SyntaxError . Keywords are an intrinsic part of the language and can’t be overridden.

If you ever feel the need to name one of your variables using a Python keyword, then you can append an underscore to the name of your variable:

In this example, you’re using the desired name for your variables. Because you added a final underscore to the names, Python doesn’t recognize them as keywords, so it doesn’t raise an error.

Note: Even though adding an underscore at the end of a name is an officially recommended practice , it can be confusing sometimes. Therefore, try to find an alternative name or use a synonym whenever you find yourself using this convention.

For example, you can write something like this:

In this example, using the name booking_class for your variable is way clearer and more descriptive than using class_ .

You’ll also find that you can use only a few keywords as part of the right operand in an assignment statement. Those keywords will generally define simple statements that return a value or object. These include lambda , and , or , not , True , False , None , in , and is . You can also use the for keyword when it’s part of a comprehension and the if keyword when it’s used as part of a ternary operator .

In an assignment, you can never use a compound statement as the right operand. Compound statements are those that require an indented block, such as for and while loops, conditionals, with statements, try … except blocks, and class or function definitions.

Sometimes, you need to name variables, but the desired or ideal name is already taken and used as a built-in name. If this is your case, think harder and find another name. Don’t shadow the built-in.

Shadowing built-in names can cause hard-to-identify problems in your code. A common example of this issue is using list or dict to name user-defined variables. In this case, you override the corresponding built-in names, which won’t work as expected if you use them later in your code.

Consider the following example:

The exception in this example may sound surprising. How come you can’t use list() to build a list from a call to map() that returns a generator of square numbers?

By using the name list to identify your list of numbers, you shadowed the built-in list name. Now that name points to a list object rather than the built-in class. List objects aren’t callable, so your code no longer works.

In Python, you’ll have nothing that warns against using built-in, standard-library, or even relevant third-party names to identify your own variables. Therefore, you should keep an eye out for this practice. It can be a source of hard-to-debug errors.

In programming, a constant refers to a name associated with a value that never changes during a program’s execution. Unlike other programming languages, Python doesn’t have a dedicated syntax for defining constants. This fact implies that Python doesn’t have constants in the strict sense of the word.

Python only has variables. If you need a constant in Python, then you’ll have to define a variable and guarantee that it won’t change during your code’s execution. To do that, you must avoid using that variable as the left operand in an assignment statement.

To tell other Python programmers that a given variable should be treated as a constant, you must write your variable’s name in capital letters with underscores separating the words. This naming convention has been adopted by the Python community and is a recommendation that you’ll find in the Constants section of PEP 8 .

In the following examples, you define some constants in Python:

The problem with these constants is that they’re actually variables. Nothing prevents you from changing their value during your code’s execution. So, at any time, you can do something like the following:

These assignments modify the value of two of your original constants. Python doesn’t complain about these changes, which can cause issues later in your code. As a Python developer, you must guarantee that named constants in your code remain constant.

The only way to do that is never to use named constants in an assignment statement other than the constant definition.

You’ve learned a lot about Python’s assignment operators and how to use them for writing assignment statements . With this type of statement, you can create, initialize, and update variables according to your needs. Now you have the required skills to fully manage the creation and mutation of variables in your Python code.

In this tutorial, you’ve learned how to:

  • Write assignment statements using Python’s assignment operators
  • Work with augmented assignments in Python
  • Explore assignment variants, like assignment expression and managed attributes
  • Identify illegal and dangerous assignments in Python

Learning about the Python assignment operator and how to use it in assignment statements is a fundamental skill in Python. It empowers you to write reliable and effective Python code.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python's Assignment Operator: Write Robust Assignments (Source Code)

🔒 No spam. We take your privacy seriously.

assignment statement function

  • Python »
  • 3.12.5 Documentation »
  • The Python Language Reference »
  • 7. Simple statements
  • Theme Auto Light Dark |

7. Simple statements ¶

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:

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 None ). Other uses of expression statements are allowed and occasionally useful. The syntax for an expression statement is:

An expression statement evaluates the expression list (which may be a single expression).

In interactive mode, if the value is not None , it is converted to a string using the built-in repr() function and the resulting string is written to standard output on a line by itself (except if the result is None , so that procedure calls do not cause any output.)

7.2. Assignment statements ¶

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

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

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

If the target list contains one target prefixed with an asterisk, called a “starred” target: The object must be an iterable with at least as many items as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred target. The final items of the iterable are assigned to the targets after the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty).

Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

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 global or nonlocal 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 global namespace or the outer namespace determined by nonlocal , respectively.

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 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, TypeError 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 AttributeError ).

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The left-hand side target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment:

This description does not necessarily apply to descriptor attributes, such as properties created with property() .

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If the primary is a mutable sequence object (such as a list), the subscript must yield an 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, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list).

If the primary is a mapping object (such as 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/value 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).

For user-defined objects, the __setitem__() method is called with appropriate arguments.

If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as 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 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 target sequence allows it.

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 a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2] :

The specification for the *target feature.

7.2.1. Augmented assignment statements ¶

Augmented assignment is the combination, in a single statement, of a binary operation and an assignment statement:

(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 statement like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place , meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i] , then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i] .

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:

The difference from normal Assignment statements is that only a single target is allowed.

The assignment target is considered “simple” if it consists of a single name that is not enclosed in parentheses. For simple assignment targets, if in class or module scope, the annotations are evaluated and stored in a special class or module attribute __annotations__ that is a dictionary mapping from variable names (mangled if private) to evaluated annotations. This attribute is writable and is automatically created at the start of class or module body execution, if annotations are found statically.

If the assignment target is not simple (an attribute, subscript node, or parenthesized name), the annotation is 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 __setitem__() or __setattr__() call.

The proposal that added syntax for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments.

The proposal that added the typing module to provide a standard syntax for type annotations that can be used in static analysis tools and IDEs.

Changed in version 3.8: Now annotated assignments allow the same expressions in the right hand side as 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:

The simple form, assert expression , is equivalent to

The extended form, assert expression1, expression2 , is equivalent to

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O ). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

7.4. The pass statement ¶

pass is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

7.5. The del statement ¶

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 global statement in the same code block. If the name is unbound, a NameError exception will be raised.

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 may only occur syntactically nested in a function definition, not within a nested class definition.

If an expression list is present, it is evaluated, else None is substituted.

return leaves the current function call with the expression list (or None ) as return value.

When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.

In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.

In an asynchronous generator function, an empty return statement indicates that the asynchronous generator is done and will cause StopAsyncIteration to be raised. A non-empty return statement is a syntax error in an asynchronous generator function.

7.7. The yield statement ¶

A yield statement is semantically equivalent to a yield expression . The yield statement can be used to omit the parentheses that would otherwise be required in the equivalent yield expression statement. For example, the yield statements

are equivalent to the yield expression statements

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 yield semantics, refer to the Yield expressions section.

7.8. The raise statement ¶

If no expressions are present, raise re-raises the exception that is currently being handled, which is also known as the active exception . If there isn’t currently an active exception, a RuntimeError exception is raised indicating that this is an error.

Otherwise, raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException . If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

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 __traceback__ attribute. You can create an exception and set your own traceback in one step using the with_traceback() exception method (which returns the same exception instance, with its traceback set to its argument), like so:

The from clause is used for exception chaining: if given, the second expression must be another exception class or instance. If the second expression is an exception instance, it will be attached to the raised exception as the __cause__ attribute (which is writable). If the expression is an exception class, the class will be instantiated and the resulting exception instance will be attached to the raised exception as the __cause__ attribute. If the raised exception is not handled, both exceptions will be printed:

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 except or finally clause, or a with statement, is used. The previous exception is then attached as the new exception’s __context__ attribute:

Exception chaining can be explicitly suppressed by specifying None in the from clause:

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: None is now permitted as Y in raise X from Y .

Added the __suppress_context__ attribute to suppress automatic display of the exception context.

Changed in version 3.11: If the traceback of the active exception is modified in an except clause, a subsequent raise statement re-raises the exception with the modified traceback. Previously, the exception was re-raised with the traceback it had when it was caught.

7.9. The break statement ¶

break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.

It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

If a for loop is terminated by break , the loop control target keeps its current value.

When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

7.10. The continue statement ¶

continue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. It continues with the next cycle of the nearest enclosing loop.

When continue passes control out of a try statement with a finally clause, that finally clause is executed before really starting the next loop cycle.

7.11. The import statement ¶

The basic import statement (no from clause) is executed in two steps:

find a module, loading and initializing it if necessary

define a name or names in the local namespace for the scope where the import statement occurs.

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:

If the module name is followed by as , then the name following as is bound directly to the imported module.

If no other name is specified, and the module being imported is a top level module, the module’s name is bound in the local namespace as a reference to the imported module

If the module being imported is not a top level module, then the name of the top level package that contains the module is bound in the local namespace as a reference to the top level package. The imported module must be accessed using its full qualified name rather than directly

The from form uses a slightly more complex process:

find the module specified in the from clause, loading and initializing it if necessary;

for each of the identifiers specified in the import clauses:

check if the imported module has an attribute by that name

if not, attempt to import a submodule with that name and then check the imported module again for that attribute

if the attribute is not found, ImportError is raised.

otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

If the list of identifiers is replaced by a star ( '*' ), all public names defined in the module are bound in the local namespace for the scope where the import statement occurs.

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__ ; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ( '_' ). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

The wild card form of import — from module import * — is only allowed at the module level. Attempting to use it in class or function definitions will raise a SyntaxError .

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 from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod . If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod . The specification for relative imports is contained in the Package Relative Imports section.

importlib.import_module() is provided to support applications that determine dynamically the modules to be loaded.

Raises an auditing event import with arguments module , filename , sys.path , sys.meta_path , sys.path_hooks .

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.

A future statement must appear near the top of the module. The only lines that can appear before a future statement are:

the module docstring (if any),

blank lines, and

other future statements.

The only feature that requires using the future statement is annotations (see PEP 563 ).

All historical features enabled by the future statement are still recognized by Python 3. The list includes absolute_import , division , generators , generator_stop , unicode_literals , print_function , nested_scopes and with_statement . They are all redundant because they are always enabled, and only kept for backwards compatibility.

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 __future__ , described later, and it will be imported in the usual way at the time the future statement is executed.

The interesting runtime semantics depend on the specific feature enabled by the future statement.

Note that there is nothing special about the statement:

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 exec() and compile() that occur in a module M containing a future statement will, by default, use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to compile() — see the documentation of that function for details.

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 -i option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed.

The original proposal for the __future__ mechanism.

7.12. The global statement ¶

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global , although free variables may refer to globals without being declared global.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.

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: global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. The same applies to the eval() and compile() functions.

7.13. The nonlocal statement ¶

When the definition of a function or class is nested (enclosed) within the definitions of other functions, its nonlocal scopes are the local scopes of the enclosing functions. The nonlocal statement causes the listed identifiers to refer to names previously bound in nonlocal scopes. It allows encapsulated code to rebind such nonlocal identifiers. If a name is bound in more than one nonlocal scope, the nearest binding is used. If a name is not bound in any nonlocal scope, or if there is no nonlocal scope, a SyntaxError is raised.

The nonlocal statement applies to the entire scope of a function or class body. A SyntaxError is raised if a variable is used or assigned to prior to its nonlocal declaration in the scope.

The specification for the nonlocal statement.

Programmer’s note: nonlocal is a directive to the parser and applies only to code parsed along with it. See the note for the global statement.

7.14. The type statement ¶

The type statement declares a type alias, which is an instance of typing.TypeAliasType .

For example, the following statement creates a type alias:

This code is roughly equivalent to:

annotation-def indicates an annotation scope , which behaves mostly like a function, but with several small differences.

The value of the type alias is evaluated in the annotation scope. It is not evaluated when the type alias is created, but only when the value is accessed through the type alias’s __value__ attribute (see Lazy evaluation ). This allows the type alias to refer to names that are not yet defined.

Type aliases may be made generic by adding a type parameter list after the name. See Generic type aliases for more.

type is a soft keyword .

Added in version 3.12.

Introduced the type statement and syntax for generic classes and functions.

Table of Contents

  • 7.1. Expression statements
  • 7.2.1. Augmented assignment statements
  • 7.2.2. Annotated assignment statements
  • 7.3. The assert statement
  • 7.4. The pass statement
  • 7.5. The del statement
  • 7.6. The return statement
  • 7.7. The yield statement
  • 7.8. The raise statement
  • 7.9. The break statement
  • 7.10. The continue statement
  • 7.11.1. Future statements
  • 7.12. The global statement
  • 7.13. The nonlocal statement
  • 7.14. The type statement

Previous topic

6. Expressions

8. Compound statements

  • Report a Bug
  • Show Source

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 572 – Assignment Expressions

The importance of real code, exceptional cases, scope of the target, relative precedence of :=, change to evaluation order, differences between assignment expressions and assignment statements, specification changes during implementation, _pydecimal.py, datetime.py, sysconfig.py, simplifying list comprehensions, capturing condition values, changing the scope rules for comprehensions, alternative spellings, special-casing conditional statements, special-casing comprehensions, lowering operator precedence, allowing commas to the right, always requiring parentheses, why not just turn existing assignment into an expression, with assignment expressions, why bother with assignment statements, why not use a sublocal scope and prevent namespace pollution, style guide recommendations, acknowledgements, a numeric example, appendix b: rough code translations for comprehensions, appendix c: no changes to scope semantics.

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr .

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally).

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

During the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other.

The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”.

The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”).

Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below.

However, in order to be compelling , examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code.

Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines.

Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing:

they would write:

Another example illustrates that programmers sometimes do more work to save an extra level of indentation:

This code tries to match pattern2 even if pattern1 has a match (in which case the match on pattern2 is never used). The more efficient rewrite would have been:

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

Again, this rule is included to avoid two visually similar ways of saying the same thing.

This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

This allows lambda to always bind less tightly than := ; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an any() expression, or a counterexample for all() , for example:

Second, it allows a compact way of updating mutable state from a comprehension, for example:

However, an assignment expression target name cannot be the same as a for -target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

While it’s technically possible to assign consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation [1] will ensure that such cases raise SyntaxError , rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword):

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is expressly invalid. This case also raises SyntaxError :

(The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code.

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or , and , not , and conditional expressions ( A if C else B ). As follows from section “Exceptional cases” above, it is never allowed at the same level as = . In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what’s technically valid or invalid:

Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable:

This PEP recommends always putting spaces around := , similar to PEP 8 ’s recommendation for = when used for assignment, whereas the latter disallows spaces around = used for keyword arguments.)

In order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:

  • In a dict comprehension {X: Y for ...} , Y is currently evaluated before X . We propose to change this so that X is evaluated before Y . (In a dict display like {X: Y} this is already the case, and also in dict((X, Y) for ...) which should clearly be equivalent to the dict comprehension.)

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don’t support the advanced features found in assignment statements:

  • Multiple targets are not directly supported: x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
  • Single assignment targets other than a single NAME are not supported: # No equivalent a [ i ] = x self . rest = []
  • Priority around commas is different: x = 1 , 2 # Sets x to (1, 2) ( x := 1 , 2 ) # Sets x to 1
  • Iterable packing and unpacking (both regular or extended forms) are not supported: # Equivalent needs extra parentheses loc = x , y # Use (loc := (x, y)) info = name , phone , * rest # Use (info := (name, phone, *rest)) # No equivalent px , py , pz = position name , phone , email , * other_info = contact
  • Inline type annotations are not supported: # Closest equivalent is "p: Optional[int]" as a separate declaration p : Optional [ int ] = None
  • Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax)

The following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:

  • for consistency with other similar exceptions, and to avoid locking in an exception name that is not necessarily going to improve clarity for end users, the originally proposed TargetScopeError subclass of SyntaxError was dropped in favour of just raising SyntaxError directly. [3]
  • due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.

Examples from the Python standard library

env_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.

  • Current: env_base = os . environ . get ( "PYTHONUSERBASE" , None ) if env_base : return env_base
  • Improved: if env_base := os . environ . get ( "PYTHONUSERBASE" , None ): return env_base

Avoid nested if and remove one indentation level.

  • Current: if self . _is_special : ans = self . _check_nans ( context = context ) if ans : return ans
  • Improved: if self . _is_special and ( ans := self . _check_nans ( context = context )): return ans

Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)

  • Current: reductor = dispatch_table . get ( cls ) if reductor : rv = reductor ( x ) else : reductor = getattr ( x , "__reduce_ex__" , None ) if reductor : rv = reductor ( 4 ) else : reductor = getattr ( x , "__reduce__" , None ) if reductor : rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )
  • Improved: if reductor := dispatch_table . get ( cls ): rv = reductor ( x ) elif reductor := getattr ( x , "__reduce_ex__" , None ): rv = reductor ( 4 ) elif reductor := getattr ( x , "__reduce__" , None ): rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )

tz is only used for s += tz , moving its assignment inside the if helps to show its scope.

  • Current: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) tz = self . _tzstr () if tz : s += tz return s
  • Improved: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) if tz := self . _tzstr (): s += tz return s

Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without making it harder to understand.

  • Current: while True : line = fp . readline () if not line : break m = define_rx . match ( line ) if m : n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v else : m = undef_rx . match ( line ) if m : vars [ m . group ( 1 )] = 0
  • Improved: while line := fp . readline (): if m := define_rx . match ( line ): n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v elif m := undef_rx . match ( line ): vars [ m . group ( 1 )] = 0

A list comprehension can map and filter efficiently by capturing the condition:

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff ).

Assignment expressions can be used to good effect in the header of an if or while statement:

Particularly with the while loop, this can remove the need to have an infinite loop, an assignment, and a condition. It also creates a smooth parallel between a loop which simply uses a function call as its condition, and one which uses that as its condition but also uses the actual value.

An example from the low-level UNIX world:

Rejected alternative proposals

Proposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above.

A previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions.

Broadly the same semantics as the current proposal, but spelled differently.

Since EXPR as NAME already has meaning in import , except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR – it calls EXPR.__enter__() and assigns the result of that to VAR .)

Additional reasons to prefer := over this spelling include:

  • In if f(x) as y the assignment target doesn’t jump out at you – it just reads like if f x blah blah and it is too similar visually to if f(x) and y .
  • import foo as bar
  • except Exc as var
  • with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

  • NAME = EXPR
  • if NAME := EXPR

reinforces the visual recognition of assignment expressions.

This syntax is inspired by languages such as R and Haskell, and some programmable calculators. (Note that a left-facing arrow y <- f(x) is not possible in Python, as it would be interpreted as less-than and unary minus.) This syntax has a slight advantage over ‘as’ in that it does not conflict with with , except and import , but otherwise is equivalent. But it is entirely unrelated to Python’s other use of -> (function return type annotations), and compared to := (which dates back to Algol-58) it has a much weaker tradition.

This has the advantage that leaked usage can be readily detected, removing some forms of syntactic ambiguity. However, this would be the only place in Python where a variable’s scope is encoded into its name, making refactoring harder.

Execution order is inverted (the indented body is performed first, followed by the “header”). This requires a new keyword, unless an existing keyword is repurposed (most likely with: ). See PEP 3150 for prior discussion on this subject (with the proposed keyword being given: ).

This syntax has fewer conflicts than as does (conflicting only with the raise Exc from Exc notation), but is otherwise comparable to it. Instead of paralleling with expr as target: (which can be useful but can also be confusing), this has no parallels, but is evocative.

One of the most popular use-cases is if and while statements. Instead of a more general solution, this proposal enhances the syntax of these two statements to add a means of capturing the compared value:

This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return '' when done), and completely useless in more complicated cases (e.g. where the condition is f(x) < 0 and you want to capture the value of f(x) ). It also has no benefit to list comprehensions.

Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible use-cases, even in if / while statements.

Another common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.

This brings the subexpression to a location in between the ‘for’ loop and the expression. It introduces an additional language keyword, which creates conflicts. Of the three, where reads the most cleanly, but also has the greatest potential for conflict (e.g. SQLAlchemy and numpy have where methods, as does tkinter.dnd.Icon in the standard library).

As above, but reusing the with keyword. Doesn’t read too badly, and needs no additional language keyword. Is restricted to comprehensions, though, and cannot as easily be transformed into “longhand” for-loop syntax. Has the C problem that an equals sign in an expression can now create a name binding, rather than performing a comparison. Would raise the question of why “with NAME = EXPR:” cannot be used as a statement on its own.

As per option 2, but using as rather than an equals sign. Aligns syntactically with other uses of as for name binding, but a simple transformation to for-loop longhand would create drastically different semantics; the meaning of with inside a comprehension would be completely different from the meaning as a stand-alone statement, while retaining identical syntax.

Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name bindings. The only keyword that can be repurposed to this task is with , thus giving it sneakily different semantics in a comprehension than in a statement; alternatively, a new keyword is needed, with all the costs therein.

There are two logical precedences for the := operator. Either it should bind as loosely as possible, as does statement-assignment; or it should bind more tightly than comparison operators. Placing its precedence between the comparison and arithmetic operators (to be precise: just lower than bitwise OR) allows most uses inside while and if conditions to be spelled without parentheses, as it is most likely that you wish to capture the value of something, then perform a comparison on it:

Once find() returns -1, the loop terminates. If := binds as loosely as = does, this would capture the result of the comparison (generally either True or False ), which is less useful.

While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for := has been made as close as possible to that of = (with the exception that it binds tighter than comma).

Some critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent:

(With the current version of the proposal, the latter would be equivalent to ((point := x), y) .)

However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence:

The less confusing option is to make := bind more tightly than comma.

It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant:

Frequently Raised Objections

C and its derivatives define the = operator as an expression, rather than a statement as is Python’s way. This allows assignments in more contexts, including contexts where comparisons are more common. The syntactic similarity between if (x == y) and if (x = y) belies their drastically different semantics. Thus this proposal uses := to clarify the distinction.

The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create externally-visible names. This is no different from for loops or other constructs, and can be solved the same way: del the name once it is no longer needed, or prefix it with an underscore.

(The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2] )

As expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8 , two recommendations are suggested.

  • If either assignment statements or assignment expressions can be used, prefer statements; they are a clear declaration of intent.
  • If using assignment expressions would lead to ambiguity about execution order, restructure it to use statements instead.

The authors wish to thank Alyssa Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation.

Appendix A: Tim Peters’s findings

Here’s a brief essay Tim Peters wrote on the topic.

I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of:

instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled:

is a vast improvement over the briefer:

The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane.

In other cases, combining related logic made it harder to understand, such as rewriting:

as the briefer:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isn’t wired that way.

But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better than sparse”. For example, I have many functions that return None or 0 to communicate “I have nothing useful to return in this case, but since that’s expected often I’m not going to annoy you with an exception”. This is essentially the same as regular expression search functions returning None when there is no match. So there was lots of code of the form:

I find that clearer, and certainly a bit less typing and pattern-matching reading, as:

It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me!

There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s copy() function in copy.py :

The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”:

Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it.

A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level:

That if is about as long as I want my lines to get, but remains easy to follow.

So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d certainly use it more often than ternary if , but significantly less often than augmented assignment.

I have another example that quite impressed me at the time.

Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration):

It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding.

If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression.

To my eyes, the original form is harder to understand:

This appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding.

Since [x for ...] is equivalent to list(x for ...) these examples all use list comprehensions without loss of generality. And since these examples are meant to clarify edge cases of the rules, they aren’t trying to look like real code.

Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope).

Let’s start with a reminder of what code is generated for a generator expression without assignment expression.

  • Original code (EXPR usually references VAR): def f (): a = [ EXPR for VAR in ITERABLE ]
  • Translation (let’s not worry about name conflicts): def f (): def genexpr ( iterator ): for VAR in iterator : yield EXPR a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a simple assignment expression.

  • Original code: def f (): a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): if False : TARGET = None # Dead code to ensure TARGET is a local variable def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a global TARGET declaration in f() .

  • Original code: def f (): global TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): global TARGET def genexpr ( iterator ): global TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Or instead let’s add a nonlocal TARGET declaration in f() .

  • Original code: def g (): TARGET = ... def f (): nonlocal TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def g (): TARGET = ... def f (): nonlocal TARGET def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Finally, let’s nest two comprehensions.

  • Original code: def f (): a = [[ TARGET := i for i in range ( 3 )] for j in range ( 2 )] # I.e., a = [[0, 1, 2], [0, 1, 2]] print ( TARGET ) # prints 2
  • Translation: def f (): if False : TARGET = None def outer_genexpr ( outer_iterator ): nonlocal TARGET def inner_generator ( inner_iterator ): nonlocal TARGET for i in inner_iterator : TARGET = i yield i for j in outer_iterator : yield list ( inner_generator ( range ( 3 ))) a = list ( outer_genexpr ( range ( 2 ))) print ( TARGET )

Because it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example:

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0572.rst

Last modified: 2023-10-11 12:05:51 GMT

logo

Python Numerical Methods

../_images/book_cover.jpg

This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists , the content is also available at Berkeley Python Numerical Methods .

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license . If you find this content useful, please consider supporting the work on Elsevier or Amazon !

< 2.0 Variables and Basic Data Structures | Contents | 2.2 Data Structure - Strings >

Variables and Assignment ¶

When programming, it is useful to be able to store information in variables. A variable is a string of characters and numbers associated with a piece of information. The assignment operator , denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable. Until the value is changed or the variable deleted, the character x behaves like the value 1.

TRY IT! Assign the value 2 to the variable y. Multiply y by 3 to show that it behaves like the value 2.

A variable is more like a container to store the data in the computer’s memory, the name of the variable tells the computer where to find this value in the memory. For now, it is sufficient to know that the notebook has its own memory space to store all the variables in the notebook. As a result of the previous example, you will see the variable “x” and “y” in the memory. You can view a list of all the variables in the notebook using the magic command %whos .

TRY IT! List all the variables in this notebook

Note that the equal sign in programming is not the same as a truth statement in mathematics. In math, the statement x = 2 declares the universal truth within the given framework, x is 2 . In programming, the statement x=2 means a known value is being associated with a variable name, store 2 in x. Although it is perfectly valid to say 1 = x in mathematics, assignments in Python always go left : meaning the value to the right of the equal sign is assigned to the variable on the left of the equal sign. Therefore, 1=x will generate an error in Python. The assignment operator is always last in the order of operations relative to mathematical, logical, and comparison operators.

TRY IT! The mathematical statement x=x+1 has no solution for any value of x . In programming, if we initialize the value of x to be 1, then the statement makes perfect sense. It means, “Add x and 1, which is 2, then assign that value to the variable x”. Note that this operation overwrites the previous value stored in x .

There are some restrictions on the names variables can take. Variables can only contain alphanumeric characters (letters and numbers) as well as underscores. However, the first character of a variable name must be a letter or underscores. Spaces within a variable name are not permitted, and the variable names are case-sensitive (e.g., x and X will be considered different variables).

TIP! Unlike in pure mathematics, variables in programming almost always represent something tangible. It may be the distance between two points in space or the number of rabbits in a population. Therefore, as your code becomes increasingly complicated, it is very important that your variables carry a name that can easily be associated with what they represent. For example, the distance between two points in space is better represented by the variable dist than x , and the number of rabbits in a population is better represented by nRabbits than y .

Note that when a variable is assigned, it has no memory of how it was assigned. That is, if the value of a variable, y , is constructed from other variables, like x , reassigning the value of x will not change the value of y .

EXAMPLE: What value will y have after the following lines of code are executed?

WARNING! You can overwrite variables or functions that have been stored in Python. For example, the command help = 2 will store the value 2 in the variable with name help . After this assignment help will behave like the value 2 instead of the function help . Therefore, you should always be careful not to give your variables the same name as built-in functions or values.

TIP! Now that you know how to assign variables, it is important that you learn to never leave unassigned commands. An unassigned command is an operation that has a result, but that result is not assigned to a variable. For example, you should never use 2+2 . You should instead assign it to some variable x=2+2 . This allows you to “hold on” to the results of previous commands and will make your interaction with Python must less confusing.

You can clear a variable from the notebook using the del function. Typing del x will clear the variable x from the workspace. If you want to remove all the variables in the notebook, you can use the magic command %reset .

In mathematics, variables are usually associated with unknown numbers; in programming, variables are associated with a value of a certain type. There are many data types that can be assigned to variables. A data type is a classification of the type of information that is being stored in a variable. The basic data types that you will utilize throughout this book are boolean, int, float, string, list, tuple, dictionary, set. A formal description of these data types is given in the following sections.

logo

Learning Python by doing

  • suggest edit

Variables, Expressions, and Assignments

Variables, expressions, and assignments 1 #, introduction #.

In this chapter, we introduce some of the main building blocks needed to create programs–that is, variables, expressions, and assignments. Programming related variables can be intepret in the same way that we interpret mathematical variables, as elements that store values that can later be changed. Usually, variables and values are used within the so-called expressions. Once again, just as in mathematics, an expression is a construct of values and variables connected with operators that result in a new value. Lastly, an assignment is a language construct know as an statement that assign a value (either as a constant or expression) to a variable. The rest of this notebook will dive into the main concepts that we need to fully understand these three language constructs.

Values and Types #

A value is the basic unit used in a program. It may be, for instance, a number respresenting temperature. It may be a string representing a word. Some values are 42, 42.0, and ‘Hello, Data Scientists!’.

Each value has its own type : 42 is an integer ( int in Python), 42.0 is a floating-point number ( float in Python), and ‘Hello, Data Scientists!’ is a string ( str in Python).

The Python interpreter can tell you the type of a value: the function type takes a value as argument and returns its corresponding type.

Observe the difference between type(42) and type('42') !

Expressions and Statements #

On the one hand, an expression is a combination of values, variables, and operators.

A value all by itself is considered an expression, and so is a variable.

When you type an expression at the prompt, the interpreter evaluates it, which means that it calculates the value of the expression and displays it.

In boxes above, m has the value 27 and m + 25 has the value 52 . m + 25 is said to be an expression.

On the other hand, a statement is an instruction that has an effect, like creating a variable or displaying a value.

The first statement initializes the variable n with the value 17 , this is a so-called assignment statement .

The second statement is a print statement that prints the value of the variable n .

The effect is not always visible. Assigning a value to a variable is not visible, but printing the value of a variable is.

Assignment Statements #

We have already seen that Python allows you to evaluate expressions, for instance 40 + 2 . It is very convenient if we are able to store the calculated value in some variable for future use. The latter can be done via an assignment statement. An assignment statement creates a new variable with a given name and assigns it a value.

The example in the previous code contains three assignments. The first one assigns the value of the expression 40 + 2 to a new variable called magicnumber ; the second one assigns the value of π to the variable pi , and; the last assignment assigns the string value 'Data is eatig the world' to the variable message .

Programmers generally choose names for their variables that are meaningful. In this way, they document what the variable is used for.

Do It Yourself!

Let’s compute the volume of a cube with side \(s = 5\) . Remember that the volume of a cube is defined as \(v = s^3\) . Assign the value to a variable called volume .

Well done! Now, why don’t you print the result in a message? It can say something like “The volume of the cube with side 5 is \(volume\) ”.

Beware that there is no checking of types ( type checking ) in Python, so a variable to which you have assigned an integer may be re-used as a float, even if we provide type-hints .

Names and Keywords #

Names of variable and other language constructs such as functions (we will cover this topic later), should be meaningful and reflect the purpose of the construct.

In general, Python names should adhere to the following rules:

It should start with a letter or underscore.

It cannot start with a number.

It must only contain alpha-numeric (i.e., letters a-z A-Z and digits 0-9) characters and underscores.

They cannot share the name of a Python keyword.

If you use illegal variable names you will get a syntax error.

By choosing the right variables names you make the code self-documenting, what is better the variable v or velocity ?

The following are examples of invalid variable names.

These basic development principles are sometimes called architectural rules . By defining and agreeing upon architectural rules you make it easier for you and your fellow developers to understand and modify your code.

If you want to read more on this, please have a look at Code complete a book by Steven McConnell [ McC04 ] .

Every programming language has a collection of reserved keywords . They are used in predefined language constructs, such as loops and conditionals . These language concepts and their usage will be explained later.

The interpreter uses keywords to recognize these language constructs in a program. Python 3 has the following keywords:

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass break

except in raise

Reassignments #

It is allowed to assign a new value to an existing variable. This process is called reassignment . As soon as you assign a value to a variable, the old value is lost.

The assignment of a variable to another variable, for instance b = a does not imply that if a is reassigned then b changes as well.

You have a variable salary that shows the weekly salary of an employee. However, you want to compute the monthly salary. Can you reassign the value to the salary variable according to the instruction?

Updating Variables #

A frequently used reassignment is for updating puposes: the value of a variable depends on the previous value of the variable.

This statement expresses “get the current value of x , add one, and then update x with the new value.”

Beware, that the variable should be initialized first, usually with a simple assignment.

Do you remember the salary excercise of the previous section (cf. 13. Reassignments)? Well, if you have not done it yet, update the salary variable by using its previous value.

Updating a variable by adding 1 is called an increment ; subtracting 1 is called a decrement . A shorthand way of doing is using += and -= , which stands for x = x + ... and x = x - ... respectively.

Order of Operations #

Expressions may contain multiple operators. The order of evaluation depends on the priorities of the operators also known as rules of precedence .

For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3 - 1) is 4 , and (1 + 1)**(5 - 2) is 8 . You can also use parentheses to make an expression easier to read, even if it does not change the result.

Exponentiation has the next highest precedence, so 1 + 2**3 is 9 , not 27 , and 2 * 3**2 is 18 , not 36 .

Multiplication and division have higher precedence than addition and subtraction . So 2 * 3 - 1 is 5 , not 4 , and 6 + 4 / 2 is 8 , not 5 .

Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi , the division happens first and the result is multiplied by pi . To divide by 2π, you can use parentheses or write: degrees / 2 / pi .

In case of doubt, use parentheses!

Let’s see what happens when we evaluate the following expressions. Just run the cell to check the resulting value.

Floor Division and Modulus Operators #

The floor division operator // divides two numbers and rounds down to an integer.

For example, suppose that driving to the south of France takes 555 minutes. You might want to know how long that is in hours.

Conventional division returns a floating-point number.

Hours are normally not represented with decimal points. Floor division returns the integer number of hours, dropping the fraction part.

You spend around 225 minutes every week on programming activities. You want to know around how many hours you invest to this activity during a month. Use the \(//\) operator to give the answer.

The modulus operator % works on integer values. It computes the remainder when dividing the first integer by the second one.

The modulus operator is more useful than it seems.

For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y .

String Operations #

In general, you cannot perform mathematical operations on strings, even if the strings look like numbers, so the following operations are illegal: '2'-'1' 'eggs'/'easy' 'third'*'a charm'

But there are two exceptions, + and * .

The + operator performs string concatenation, which means it joins the strings by linking them end-to-end.

The * operator also works on strings; it performs repetition.

Speedy Gonzales is a cartoon known to be the fastest mouse in all Mexico . He is also famous for saying “Arriba Arriba Andale Arriba Arriba Yepa”. Can you use the following variables, namely arriba , andale and yepa to print the mentioned expression? Don’t forget to use the string operators.

Asking the User for Input #

The programs we have written so far accept no input from the user.

To get data from the user through the Python prompt, we can use the built-in function input .

When input is called your whole program stops and waits for the user to enter the required data. Once the user types the value and presses Return or Enter , the function returns the input value as a string and the program continues with its execution.

Try it out!

You can also print a message to clarify the purpose of the required input as follows.

The resulting string can later be translated to a different type, like an integer or a float. To do so, you use the functions int and float , respectively. But be careful, the user might introduce a value that cannot be converted to the type you required.

We want to know the name of a user so we can display a welcome message in our program. The message should say something like “Hello \(name\) , welcome to our hello world program!”.

Script Mode #

So far we have run Python in interactive mode in these Jupyter notebooks, which means that you interact directly with the interpreter in the code cells . The interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy. The alternative is to save code in a file called a script and then run the interpreter in script mode to execute the script. By convention, Python scripts have names that end with .py .

Use the PyCharm icon in Anaconda Navigator to create and execute stand-alone Python scripts. Later in the course, you will have to work with Python projects for the assignments, in order to get acquainted with another way of interacing with Python code.

This Jupyter Notebook is based on Chapter 2 of the books Python for Everybody [ Sev16 ] and Think Python (Sections 5.1, 7.1, 7.2, and 5.12) [ Dow15 ] .

Lesson 4: Assignment Statements and Numeric Functions

Once you've read your data into a SAS data set, surely you want to do something with it. A common thing to do is to change the original data in some way in an attempt to answer a research question of interest to you. You can change the data in one of two ways:

  • You can use a basic assignment statement in which you add some information to all of the observations in the data set. Some assignment statements may take advantage of the numerous SAS functions that are available to make programming certain calculations easier ( e.g. , taking an average).
  • Alternatively, you can use an if-then-else statement to add some information to some but not all of the observations. In this lesson, we will learn how to use assignment statements and numeric SAS functions to change your data. In the next lesson, we will learn how to use if-then-else statements to change a subset of your data.

Modifying your data may involve not only changing the values of a particular variable but also the type of the variable. That is, you might need to change a character variable to a numeric variable. For that reason, we'll investigate how to use the INPUT function to convert character data values to numeric values. (We'll learn how to use the PUT function to convert numeric values to character values in Stat 481 when we study character functions in depth.)

Upon completing this lesson, you should be able to do the following:

  • write a basic assignment statement involving a numeric variable
  • write an assignment statement that involves an arithmetic calculation
  • write an assignment statement that utilizes one of the many numeric SAS functions that are available
  • describe how SAS handles missing values for various arithmetic calculations and functions
  • write an assignment statement involving nested functions
  • write a basic assignment statement involving a character variable
  • convert character data values to numeric values using the INPUT function

4.1 - Assignment Statement Basics

The fundamental method of modifying the data in a data set is by way of a basic assignment statement. Such a statement always takes the form:

variable = expression;

where the variable is any valid SAS name and the expression is the calculation that is necessary to give the variable its values. The variable must always appear to the left of the equal sign and the expression must always appear to the right of the equal sign. As always, the statement must end with a semicolon (;).

Because assignment statements involve changing the values of variables, in the process of learning about assignment statements we'll get practice with working with both numeric and character variables. We'll also learn how using numeric SAS functions can help to simplify some of our calculations.

Example 4.1

Throughout this lesson, we'll work on modifying various aspects of the temporary data set grades that are created in the following DATA step:

The data set contains student names ( name ), each of their four exam grades ( e1 , e2 , e3 , e4 ), their project grade ( p1 ), and their final exam grade ( f1 ).

A couple of comments. For the sake of the examples that follow, we'll use the DATALINES statement to read in the data. We could have just as easily used the INFILE statement. Additionally, for the sake of ease, we'll create temporary data sets rather than permanent ones. Finally, after each SAS DATA step, we'll use the PRINT procedure to print all or part of the resulting SAS data set for your perusal.

Example 4.2

The following SAS program illustrates a very simple assignment statement in which SAS adds up the four exam scores of each student and stores the result in a new numeric variable called examtotal .

Note that, as previously described, the new variable name examtotal appears to the left of the equal sign, while the expression that adds up the four exam scores ( e1 + e2 + e3 + e4 ) appears to the right of the equal sign.

Launch and run    the SAS program. Review the output from the PRINT procedure to convince yourself that the new numeric variable examtotal is indeed the sum of the four exam scores for each student appearing in the data set. Also, note what SAS does when it is asked to calculate something when some of the data are missing. Rather than add up the three exam scores that do exist for John Simon, SAS instead assigns a missing value to his examtotal . If you think about it, that's a good thing! Otherwise, you'd have no way of knowing that his examtotal differed in some fundamental way from that of the other students. The important lesson here is to always be aware of how SAS is going to handle the missing values in your data set when you perform various calculations!

Example 4.3

In the previous example, the assignment statement created a new variable in the data set by simply using a variable name that didn't already exist in the data set. You need not always use a new variable name. Instead, you could modify the values of a variable that already exists. The following SAS program illustrates how the instructor would modify the variable e2 , say for example, if she wanted to modify the grades of the second exam by adding 8 points to each student's grade:

Note again that the name of the variable being modified ( e2 ) appears to the left of the equal sign, while the arithmetic expression that tells SAS to add 8 to the second exam score ( e2 +8) appears to the right of the equal sign. In general, when a variable name appears on both sides of the equal sign, the original value on the right side is used to evaluate the expression. The result of the expression is then assigned to the variable on the left side of the equal sign.

Launch and run    the SAS program. Review the output from the print procedure to convince yourself that the values of the numeric variable e2 are indeed eight points higher than the values in the original data set.

4.2 - Arithmetic Calculations Using Arithmetic Operators

All we've done so far is add variables together. Of course, we could also subtract, multiply, divide, or exponentiate variables. We just have to make sure that we use the symbols that SAS recognizes. They are:

Operation

Symbol

Assignment Statement

Action Taken

addition

+

= + ;

add and

subtraction

-

= - ;

subtract from

multiplication

*

= * ;

multiply and

division

/

= / ;

divide by

exponentiation

**

= ** ;

raise to the power of

negative prefix

-

= - ;

take the negative of

As is the case in other programming languages, you can perform more than one operation in an assignment statement. The operations are performed as they are for any mathematical expression, namely:

  • exponentiation is performed first, then multiplication and division, and finally addition and subtraction
  • if multiple instances of addition, multiple instances of subtraction, or addition and subtraction appear together in the same expression, the operations are performed from left to right
  • if multiple instances of multiplication, multiple instances of division, or multiplication and division appear together in the same expression, the operations are performed from left to right
  • if multiple instances of exponentiation occur in the same expression, the operations are performed right to left
  • operations in parentheses are performed first

It's that last bullet that I think is the most helpful to know. If you use parentheses to specifically tell SAS what you want to be calculated first, then you needn't worry as much about the other rules. Let's take a look at two examples.

Example 4.4

The following example contains a calculation that illustrates the standard order of operations. Suppose a statistics instructor calculates the final grade by weighting the average exam score by 0.6, the project score by 0.2, and the final exam by 0.2. The following SAS program illustrates how the instructor (incorrectly) calculates the students' final grades:

Well, okay, so the instructor should stick to statistics and not mathematics. As you can see in the assignment statement, the instructor is attempting to tell SAS to average the four exam scores by adding them up and dividing by 4, and then multiplying the result by 0.6. Let's see what SAS does instead. Launch and run    the SAS program, and review the output to see if you can figure out what SAS did, say, for the first student Alexander Smith. If you're still not sure, review the rules for the order of the operations again. The rules tell us that SAS first:

  • takes Alexander's first exam score of 78 and multiples it by 0.6 to get 46.8
  • takes Alexander's fourth exam score of 69 and divides it by 4 to get 17.25
  • takes Alexander's project score of 97 and multiplies it by 0.2 to get 19.4
  • takes Alexander's final exam score of 80 and multiplies it by 0.2 to get 16.0

Then, SAS performs all of the addition:

to get his final score of 267.45. Now, maybe that's the final score that Alexander wants, but it is still fundamentally wrong. Let's see if we can help set the statistics instructor straight by taking advantage of that last rule that says operations in parentheses are performed first.

Example 4.5

The following example contains a calculation that illustrates the standard order of operations. Suppose a statistics instructor calculates the final grade by weighting the average exam score by 0.6, the project score by 0.2, and the final exam by 0.2. The following SAS program illustrates how the instructor (correctly) calculates the students' final grades:

Let's dissect the calculation of Alexander's final score again. The assignment statement for final tells SAS:

  • to first add Alexander's four exam scores (78, 82, 86, 69) to get 315
  • and then divide that total 315 by 4 to get an average exam score of 78.75
  • and then multiply the average exam score of 78.75 by 0.6 to get 47.25
  • and then take Alexander's project score of 97 and multiply it by 0.2 to get 19.4
  • and then take Alexander's final exam score of 80 and multiply it by 0.2 to get 16.0

Then, SAS performs the addition of the last three items:

to get his final score of 82.65. There, that sounds much better. Sorry, Alexander.

Launch and run    the SAS program to see how we did. Review the output from the print procedure to convince yourself that the final grades have been calculated as the instructor wishes. By the way, note again that SAS assigns a missing value to the final grade for John Simon.

In this last example, we calculated the students' average exam scores by adding up their four exam grades and dividing them by 4. We could have instead taken advantage of one of the many numeric functions that are available in SAS, namely that of the MEAN function.

4.3 - Numeric Functions

Just as is the case for other programming languages, such as C++ or S-Plus, a SAS function is a pre-programmed routine that returns a value computed from one or more arguments. The standard form of any SAS function is:

For example, if we want to add three variables, a , b, and c , using the SAS function SUM and assign the resulting value to a variable named d , the correct form of our assignment statement is:

In this case, sum is the name of the function, d is the target variable to which the result of the SUM function is assigned, and a , b , and c are the function's arguments. Some functions require a specific number of arguments, whereas other functions, such as SUM, can contain any number of arguments. Some functions require no arguments. As you'll see in the examples that follow, the arguments can be variable names, constants, or even expressions.

SAS offers arithmetic, financial, statistical, and probability functions. There are far too many of these functions to explore them all in detail, but let's take a look at some examples.

Example 4.6

In the previous example, we calculated students' average exam scores by adding up their four exam grades and dividing by 4. Alternatively, we could use the MEAN function. The following SAS program illustrates the calculation of the average exam scores in two ways — by definition and by using the MEAN function:

Launch and run    the SAS program. Review the output from the PRINT procedure to convince yourself that the two methods of calculating the average exam scores do indeed yield the same results:

The SAS System

Obs

name

e1

e2

e3

e4

avg1

avg2

1

Alexander Smith

78

82

86

69

78.75

78.75

2

John Simon

88

72

86

.

.

82.00

3

Patricia Jones

98

92

92

99

95.25

95.25

4

Jack Benedict

54

63

71

49

59.25

59.25

5

Rene Porter

10

62

88

74

81.00

81.00

Oooops! What happened? SAS reports that the average exam score for John Simon is 82 when the average is calculated using the MEAN function, but reports a missing value when the average is calculated using the definition. If you study the results, you'll soon figure out that when calculating an average using the MEAN function, SAS ignores the missing values and goes ahead and calculates the average based on the available values.

We can't really make some all-conclusive statement about which method is more appropriate, as it really depends on the situation and the intent of the programmer. Instead, the (very) important lesson here is to know how missing values are handled for the various methods that are available in SAS! We can't possibly address all of the possible calculations and functions in this course. So ... you would be wise to always check your calculations out on a few representative observations to make sure that your SAS programming is doing exactly as you intended. This is another one of those good programming practices to jot down.

Although you can refer to SAS Help and Documentation (under " functions , by category ") for a full accounting of the built-in numeric functions that are available in SAS, here is a list of just some of the numeric functions that can be helpful when performing statistical analyses:

 

: the integer portion of a numeric value

: the absolute value of the argument

= ( );

: the square root of the argument

= ( );

: the minimum value of the arguments

= ( , , );

: the maximum value of the arguments

= ( , , );

: the sum of the arguments

= ( , , );

: the mean of the arguments

= ( , , );

: round the argument to the specified unit

= ( , 1);

: the log (base ) of the argument

= ( );

: the value of the argument in the previous observation

= ( );

: the difference between the values of the argument in the current and previous observations

= ( );

: the number of non-missing values of the argument

= ( )

: the number of missing values of the argument

= ( )

I have used the INT function a number of times when dealing with numbers whose first few digits contain some additional information that I need. For example, the area code in this part of Pennsylvania is 814. If I have phone numbers that are stored as numbers, say, as 8142341230, then I can use the INT function to extract the area code from the number. Let's take a look at an example of this use of the INT function.

Example 4.7

The following SAS program uses the INT function to extract the area codes from a set of ten-digit telephone numbers:

In short, the INT function returns the integer part of the expression contained within parentheses. So, if the phone number is 8145562314, then int ( phone /10000000) becomes int (814.5562314) which becomes, as claimed, the area code 814. Now, launch and run    the SAS program, and review the output from the PRINT procedure to convince yourself that the area codes are calculated as claimed.

Example 4.8

One really cool thing is that you can nest functions in SAS (as you can in most programming languages). That is, you can compute a function within another function. When you nest functions, SAS works from the inside out. That is, SAS performs the action in the innermost function first. It uses the result of that function as the argument of the next function, and so on. You can nest any function as long as the function that is used as the argument meets the requirements for the argument.The following SAS program illustrates nested functions when it rounds the students' exam average to the nearest unit:

For example, the average of Alexander's four exams is 78.75 (the sum of 78, 82, 86, and 69 all divided by 4). Thus, in calculating the avg for Alexander, 78.75 becomes the argument for the ROUND function. That is, 78.75 is rounded to the nearest one unit to get 79. Launch and run    the SAS program, and review the output from the PRINT procedure to convince yourself that the exam averages avg are rounded as claimed.

4.4 - Assigning Character Variables

So far, all of our examples have pertained to numeric variables. Now, let's take a look at adding a new character variable to your data set or modifying an existing characteristic variable in your data set. In the previous lessons, we learned how to read the values of a character variable by putting a dollar sign ($) after the variable's name in the INPUT statement. Now, you can update a character variable (or create a new character variable!) by specifying the variable's values in an assignment statement.

Example 4.9

When creating a new character variable in a data set, most often you will want to assign the values based on certain conditions. For example, suppose an instructor wants to create a character variable called status which indicates whether a student "passed" or "failed" based on their overall final grade. A grade below 65, say, might be considered a failing grade, while a grade of 65 or higher might be considered a passing grade. In this case, we would need to make use of an if-then-else statement . We'll learn more about this kind of statement in the next lesson, but you'll get the basic idea here. The following SAS program illustrates the creation of a new character variable called status using an assignment statement in conjunction with an if-then-else statement:

Launch and run    the SAS program. Review the output from the PRINT procedure to convince yourself that the values of the character variable status have been assigned correctly. As you can see, to specify a character variable's value using an assignment statement, you enclose the value in quotes. Some comments:

  • You can use either single quotes or double quotes. Change the single quotes in the above program to double quotes, and re-run    the SAS program to convince yourself that the character values are similarly assigned.
  • If you forget to specify the closing quote, it is typically a show-stopper as SAS continues to scan the program looking for the closing quote. Delete the closing quote in the above program, and re-run    the SAS program to convince yourself that the program fails to accomplish what is intended. Check your log window to see what kind of a warning statement is generated.

4.5 - Converting Data

Suppose you are asked to calculate sales income using the price and the number of units sold. Pretty straightforward, eh? As long as price and units are stored in your data set as numeric variables, then you could just use the assignment statement:

It may be the case, however, that price and units are instead stored as character variables. Then, you can imagine it being a little odd trying to multiply price by units . In that case, the character variables price and units first need to be converted to numeric variables price and units . How SAS helps us do that is the subject of this section. To be specific, we'll learn how the INPUT function converts character values to numeric values.

The reality though is that SAS is a pretty smart application. If you try to do something to a character variable that should only be done to a numeric variable, SAS automatically tries first to convert the character variable to a numeric variable for you. The problem with taking this lazy person's approach is that it doesn't always work the way you'd hoped. That's why, by the end of our discussion, you'll appreciate that the moral of the story is that it is always best for you to perform the conversions yourself using the INPUT function.

Example 4.11

The following SAS program illustrates how SAS tries to perform an automatic character-to-numeric conversion of standtest and e1 , e2 , e3 , and e4 so that arithmetic operations can be performed on them:

Okay, first note that for some crazy reason, all of the data in the data set have been read in as character data. That is, even the exam scores ( e1 , e2 , e3 , e4 ) and the standardized test scores ( standtest ) are stored as character variables. Then, when SAS goes to calculate the average exam score ( avg ), SAS first attempts to convert e1 , e2 , e3 , and e4 to numeric variables. Likewise, when SAS calculates a new standardized test score ( std ), SAS first attempts to convert standtest to a numeric variable. Let's see how it does. Launch and run    the SAS program, and before looking at the output window, take a look at the log window. You should see something that looks like this:

The first NOTE that you see is a standard message that SAS prints in the log to warn you that it performed an automatic character-to-numeric conversion on your behalf. Then, you see three NOTES about invalid numeric data concerning the standtest values 1,210, 1,010, and 1,180. In case you haven't figured it out yourself, it's the commas in those numbers that is throwing SAS for a loop. In general, the automatic conversion produces a numeric missing value from any character value that does not conform to standard numeric values (containing only digits 0, 1, ..., 9, a decimal point, and plus or minus signs). That's why that fifth NOTE is there about missing values being generated. The output itself:

Obs

name

e1

e2

e3

e4

standtest

avg

std

1

Alexander Smith

78

82

86

69

1,210

79

.

2

John Simon

88

72

86

 

990

82

247.50

3

Patricia Jones

98

92

92

99

1,010

95

.

4

Jack Benedict

54

63

71

49

875

59

218.75

5

Rene Porter

100

62

88

74

1,180

81

.

shows the end result of the attempted automatic conversion. The calculation of avg went off without a hitch because e1 , e2 , e3 , and e4 contain standard numeric values, whereas the calculation of std did not because standtest contains nonstandard numeric values. Let's take this character-to-numeric conversion into our own hands.

Example 4.12

The following SAS program illustrates the use of the INPUT function to convert the character variable standtest to a numeric variable explicitly so that an arithmetic operation can be performed on it:

The only difference between the calculation of std here and that in the previous example is that the standtest variable has been inserted here into the INPUT function. The general form of the INPUT function is:

  • source is the character variable, constant or expression to be converted to a numeric variable
  • informat is a numeric informat that allows you to read the values stored in source

In our case, standtest is the character variable we are trying to convert to a numeric variable. The values in standtest conform to the comma5 . informat, and hence its specification in the INPUT function.

Let's see how we did. Launch and run    the SAS program, and again before looking at the output window, take a look at the log window. You should see something that now looks like this:

Ahhaa! No warnings about SAS taking over our program and performing automatic conversions. That's because we are in control this time! Now, looking at the output:

Obs

name

standtest

std

1

Alexander Smith

1,210

302.50

2

John Simon

990

247.50

3

Patricia Jones

1,010

252.50

4

Jack Benedict

875

218.75

5

Rene Porter

1,180

295.00

we see that we successfully calculated std this time around. That's much better!

A couple of closing comments. First, I might use our discussion here to add another item to your growing list of good programming practices. Whenever possible, make sure that you are the one who is in control of your program. That is, know what your program is doing at all times, and if it's not doing what you'd expect it to do for all situations , then rewrite it in such a way to make sure that it does.

Second, you might be wondering "geez, we just spent all this time talking about character-to-numeric conversions, but what happens if I have to do a numeric-to-character conversion instead?" Don't worry ... SAS doesn't let you down. If you try to do something to a character variable that should only be done to a numeric variable, SAS automatically tries first to convert the character variable to a numeric variable. If that doesn't work, then you'll want to use the PUT function to convert your numeric values to character values explicitly. We'll address the PUT function in Stat 481 when we learn about character functions in depth.

4.6 - Summary

In this lesson, we learned how to write basic assignment statements, as well as use numeric SAS functions, in order to change the contents of our SAS data set. One thing you might have noticed is that almost all of our examples involved assignment statements that changed every observation in our data set. There may be situations, however, when you don't want to change every observation, but rather want to change just a subset of observations, those that meet a certain condition. To do so, you have to use if-then-else statements, which we'll learn about in the next lesson. In doing so, we'll also learn a few more good programming practices.

The homework for this lesson will give you practice with assignment statements and numeric functions so that you become even more familiar with how they work and can use them in your own SAS programming.

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Assignment Operators in Programming

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in Python
  • Assignment Operators in C#
  • Assignment Operators in JavaScript
  • Application of Assignment Operators

Assignment operators are used in programming to  assign values  to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

OperatorDescriptionExamples
= (Assignment)Assigns the value on the right to the variable on the left.  assigns the value 10 to the variable x.
+= (Addition Assignment)Adds the value on the right to the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
-= (Subtraction Assignment)Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
*= (Multiplication Assignment)Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
/= (Division Assignment)Divides the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
%= (Modulo Assignment)Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable.  is equivalent to 

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Please Login to comment...

Similar reads.

  • Programming
  • SUMIF in Google Sheets with formula examples
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

TutorialsTonight Logo

Python Conditional Assignment

When you want to assign a value to a variable based on some condition, like if the condition is true then assign a value to the variable, else assign some other value to the variable, then you can use the conditional assignment operator.

In this tutorial, we will look at different ways to assign values to a variable based on some condition.

1. Using Ternary Operator

The ternary operator is very special operator in Python, it is used to assign a value to a variable based on some condition.

It goes like this:

Here, the value of variable will be value_if_true if the condition is true, else it will be value_if_false .

Let's see a code snippet to understand it better.

You can see we have conditionally assigned a value to variable c based on the condition a > b .

2. Using if-else statement

if-else statements are the core part of any programming language, they are used to execute a block of code based on some condition.

Using an if-else statement, we can assign a value to a variable based on the condition we provide.

Here is an example of replacing the above code snippet with the if-else statement.

3. Using Logical Short Circuit Evaluation

Logical short circuit evaluation is another way using which you can assign a value to a variable conditionally.

The format of logical short circuit evaluation is:

It looks similar to ternary operator, but it is not. Here the condition and value_if_true performs logical AND operation, if both are true then the value of variable will be value_if_true , or else it will be value_if_false .

Let's see an example:

But if we make condition True but value_if_true False (or 0 or None), then the value of variable will be value_if_false .

So, you can see that the value of c is 20 even though the condition a < b is True .

So, you should be careful while using logical short circuit evaluation.

While working with lists , we often need to check if a list is empty or not, and if it is empty then we need to assign some default value to it.

Let's see how we can do it using conditional assignment.

Here, we have assigned a default value to my_list if it is empty.

Assign a value to a variable conditionally based on the presence of an element in a list.

Now you know 3 different ways to assign a value to a variable conditionally. Any of these methods can be used to assign a value when there is a condition.

The cleanest and fastest way to conditional value assignment is the ternary operator .

if-else statement is recommended to use when you have to execute a block of code based on some condition.

Happy coding! 😊

assignment statement function

IFS function

The IFS function checks whether one or more conditions are met, and returns a value that corresponds to the first TRUE condition. IFS can take the place of multiple nested IF statements, and is much easier to read with multiple conditions.

Note:  This feature is available on Windows or Mac if you have Office 2019, or if you have a  Microsoft 365 subscription . If you are a Microsoft 365 subscriber, make sure you have the latest version .

Simple syntax

Generally, the syntax for the IFS function is: =IFS([Something is True1, Value if True1,Something is True2,Value if True2,Something is True3,Value if True3)  

Please note that the IFS function allows you to test up to 127 different conditions. However, we don't recommend nesting too many conditions with IF or IFS statements. This is because multiple conditions need to be entered in the correct order, and can be very difficult to build, test and update.

Technical details

IFS(logical_test1, value_if_true1, [logical_test2, value_if_true2], [logical_test3, value_if_true3],…)

(required)

Condition that evaluates to TRUE or FALSE.

(required)

Result to be returned if logical_test1 evaluates to TRUE. Can be empty.

(optional)

Condition that evaluates to TRUE or FALSE.

(optional)

Result to be returned if evaluates to TRUE. Each corresponds with a condition . Can be empty.

assignment statement function

The formula for cells A2:A6 is:

=IFS(A2>89,"A",A2>79,"B",A2>69,"C",A2>59,"D",TRUE,"F")

Which says IF(A2 is Greater Than 89, then return a "A", IF A2 is Greater Than 79, then return a "B", and so on and for all other values less than 59, return an "F").

IFS function - Days of the Week example - Formula in cell G2 is 	=IFS(F2=1,D2,F2=2,D3,F2=3,D4,F2=4,D5,F2=5,D6,F2=6,D7,F2=7,D8)

The formula in cell G7 is:

=IFS(F2=1,D2,F2=2,D3,F2=3,D4,F2=4,D5,F2=5,D6,F2=6,D7,F2=7,D8)

Which says IF(the value in cell F2 equals 1, then return the value in cell D2, IF the value in cell F2 equals 2, then return the value in cell D3, and so on, finally ending with the value in cell D8 if none of the other conditions are met).

To specify a default result, enter TRUE for your final logical_test argument. If none of the other conditions are met, the corresponding value will be returned. In Example 1, rows 6 and 7 (with the 58 grade) demonstrate this.

If a logical_test argument is supplied without a corresponding value_if_true , this function shows a "You've entered too few arguments for this function" error message.

If a logical_test argument is evaluated and resolves to a value other than TRUE or FALSE, this function returns a #VALUE! error.

If no TRUE conditions are found, this function returns #N/A error.

Need more help?

You can always ask an expert in the Excel Tech Community  or get support in  Communities .

Related Topics

IF function Advanced IF functions - Working with nested formulas and avoiding pitfalls Training videos: Advanced IF functions The COUNTIF function will count values based on a single criteria The COUNTIFS function will count values based on multiple criteria The SUMIF function will sum values based on a single criteria The SUMIFS function will sum values based on multiple criteria AND function OR function VLOOKUP function Overview of formulas in Excel How to avoid broken formulas Detect errors in formulas Logical functions Excel functions (alphabetical) Excel functions (by category)

Facebook

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

assignment statement function

Microsoft 365 subscription benefits

assignment statement function

Microsoft 365 training

assignment statement function

Microsoft security

assignment statement function

Accessibility center

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

assignment statement function

Ask the Microsoft Community

assignment statement function

Microsoft Tech Community

assignment statement function

Windows Insiders

Microsoft 365 Insiders

Was this information helpful?

Thank you for your feedback.

  • Environment
  • Science & Technology
  • Business & Industry
  • Health & Public Welfare
  • Topics (CFR Indexing Terms)
  • Public Inspection
  • Presidential Documents
  • Document Search
  • Advanced Document Search
  • Public Inspection Search
  • Reader Aids Home
  • Office of the Federal Register Announcements
  • Using FederalRegister.Gov
  • Understanding the Federal Register
  • Recent Site Updates
  • Federal Register & CFR Statistics
  • Videos & Tutorials
  • Developer Resources
  • Government Policy and OFR Procedures
  • Congressional Review
  • My Clipboard
  • My Comments
  • My Subscriptions
  • Sign In / Sign Up
  • Site Feedback
  • Search the Federal Register

This site displays a prototype of a “Web 2.0” version of the daily Federal Register. It is not an official legal edition of the Federal Register, and does not replace the official print version or the official electronic version on GPO’s govinfo.gov.

The documents posted on this site are XML renditions of published Federal Register documents. Each document posted on the site includes a link to the corresponding official PDF file on govinfo.gov. This prototype edition of the daily Federal Register on FederalRegister.gov will remain an unofficial informational resource until the Administrative Committee of the Federal Register (ACFR) issues a regulation granting it official legal status. For complete information about, and access to, our official publications and services, go to About the Federal Register on NARA's archives.gov.

The OFR/GPO partnership is committed to presenting accurate and reliable regulatory information on FederalRegister.gov with the objective of establishing the XML-based Federal Register as an ACFR-sanctioned publication in the future. While every effort has been made to ensure that the material on FederalRegister.gov is accurately displayed, consistent with the official SGML-based PDF version on govinfo.gov, those relying on it for legal research should verify their results against an official edition of the Federal Register. Until the ACFR grants it official status, the XML rendition of the daily Federal Register on FederalRegister.gov does not provide legal notice to the public or judicial notice to the courts.

Design Updates: As part of our ongoing effort to make FederalRegister.gov more accessible and easier to use we've enlarged the space available to the document content and moved all document related data into the utility bar on the left of the document. Read more in our feature announcement .

Statement of Organization, Functions, and Delegations of Authority

A Notice by the Refugee Resettlement Office on 06/12/2024

This document has been published in the Federal Register . Use the PDF linked in the document sidebar for the official electronic format.

  • Document Details Published Content - Document Details Agencies Department of Health and Human Services Office of Refugee Resettlement Document Citation 89 FR 49889 Document Number 2024-12806 Document Type Notice Pages 49889-49894 (6 pages) Publication Date 06/12/2024 Published Content - Document Details
  • View printed version (PDF)

This table of contents is a navigational tool, processed from the headings within the legal text of Federal Register documents. This repetition of headings to form internal navigation links has no substantive legal effect.

FOR FURTHER INFORMATION CONTACT:

Supplementary information:, division of refugee assistance (krb1), division of refugee services (krb2), division of refugee health (krb3), division of refugee children services (krb4), division of refugee policy (krb5), division of monitoring, evaluation and learning (krb6), division of refugee data and information (krb7), division of interagency outreach and response (krb8), division of unaccompanied children services (krc1), division of planning and logistics (krc2), division of health of unaccompanied children (krc3), division of unaccompanied children field operations (krc4), division of unaccompanied children policy (krc5), division of child protection investigations (krc6), division of grants management (krc7), division of unaccompanied children placements (krc8), division of quality improvement and performance management (krc9), division of unaccompanied children data analytics and information management (krc10), the division of office operations, the division of budget planning and analysis, the division of acquisitions requirements, the division of technology.

This feature is not available for this document.

Additional information is not currently available for this document.

  • Sharing Enhanced Content - Sharing Shorter Document URL https://www.federalregister.gov/d/2024-12806 Email Email this document to a friend Enhanced Content - Sharing
  • Print this document

Document page views are updated periodically throughout the day and are cumulative counts for this document. Counts are subject to sampling, reprocessing and revision (up or down) throughout the day.

This document is also available in the following formats:

More information and documentation can be found in our developer tools pages .

This PDF is the current document as it appeared on Public Inspection on 06/11/2024 at 8:45 am.

It was viewed 0 times while on Public Inspection.

If you are using public inspection listings for legal research, you should verify the contents of the documents against a final, official edition of the Federal Register. Only official editions of the Federal Register provide legal notice of publication to the public and judicial notice to the courts under 44 U.S.C. 1503 & 1507 . Learn more here .

Document headings vary by document type but may contain the following:

  • the agency or agencies that issued and signed a document
  • the number of the CFR title and the number of each part the document amends, proposes to amend, or is directly related to
  • the agency docket number / agency internal file number
  • the RIN which identifies each regulatory action listed in the Unified Agenda of Federal Regulatory and Deregulatory Actions

See the Document Drafting Handbook for more details.

Department of Health and Human Services

Office of refugee resettlement.

Office of Refugee Resettlement, Administration for Children and Families, HHS.

Notice; realignment of the Office of Refugee Resettlement.

The Administration for Children and Families (ACF) has realigned the Office of Refugee Resettlement (ORR). This notice makes ORR's Refugee Program and Unaccompanied Children Program the Refugee Program Bureau and the Unaccompanied Children Bureau, respectively; creates the Bureau of Operations; and aligns divisions with the bureau they support.

Michael Smith, Chief Operating Officer, Office of Refugee Resettlement, 330 C Street SW, Washington, DC 20201, phone 202-401-4657.

This notice amends Part K of the Statement of Organization, Functions, and Delegations of Authority of the Department of Health and Human Services (HHS), Administration for Children and Families (ACF), as follows: Chapter KR, Office of Refugee Resettlement, as last amended by 85 FR 85643 , 2020-28706 (December 29, 2020).

I. Under Chapter KR, Office of Refugee Resettlement, delete KR.10 Organization in its entirety and replace with the following:

KR.10 Organization. The Office of Refugee Resettlement (ORR) is headed by a Deputy Assistant Secretary for Humanitarian Services and Director, who reports directly to the Assistant Secretary for Children and Families. The office is organized as follows:

Office of the Director/Deputy Assistant Secretary for Humanitarian Services (KRA)

Refugee Program Bureau (KRB)

Division of Monitoring, Evaluation, and Learning (KRB6)

Unaccompanied Children Bureau (KRC)

Division of Health for Unaccompanied Children (KRC3)

Division of Unaccompanied Child Protection Investigations (KRC6)

Bureau of Operations (KRD)

Division of Budget Planning and Analysis (KRD1)

Division of Office Operations (KRD2)

Division of Acquisitions Requirements (KRD3)

Division of Technology (KRD4)

II. Under Chapter KR, Office of Refugee Resettlement, deletes KR.20 Functions in its entirety and replaces it with the following:

KR.20 Function. A. The Office of the Director/Deputy Assistant Secretary for Humanitarian Services (ORR Director/DAS-HS) is directly responsible to the Assistant Secretary for Children and Families for carrying out ORR's statutory mandates and mission and providing guidance and general supervision to the components of ORR. The ORR Director/DAS-HS has specific legal authorities provided by section 411 of the Refugee Act of 1980, section 462 of the Homeland Security Act of 2002, and delegated per section 235 of the William Wilberforce Trafficking Victims Protection Reauthorization Act of 2008, and provides executive level leadership and direction on national policy and programming. The Principal Deputy Director, in coordination with the ORR Director/DAS-HS, oversees overall program effectiveness. Program administration and management is carried out by the Director of the Refugee Program Bureau, the Director of the Unaccompanied Children Bureau, and the Chief Operating Officer.

The ORR Director/DAS-HS coordinates with the lead refugee and entrant program offices of other Federal departments; provides leadership in representing refugee and entrant programs, policies, and administration to a variety of governmental entities and other public and private interests; and acts as the coordinator of the refugee and entrant resettlement efforts for ACF and the Department. The ORR Director/DAS-HS oversees the care and custody of unaccompanied children, grants specific consent for those who wish to invoke the jurisdiction of a state court for a dependency order to seek Special Immigrant Juvenile (SIJ) status, and makes placement determinations for those eligible for the Unaccompanied Refugee Minors (URM) Program. The Office of the Director/DAS-HS develops regulations, legislative proposals, and routine interpretations of policy; implements strategic initiatives and management priorities; and oversees communications for the office, including responses to media requests, congressional inquiries, and stakeholder engagements. In the absence of the ORR Director/DAS-HS, the Principal Deputy Director serves as head of office. Within the Office of the Director, the Strategic Initiatives team, the Enterprise Analytics team, the Integrity and Accountability team, and the Communications and Partnerships team provide direct support to the Office of the Director/DAS-HS.

The Strategic Initiatives team oversees the development and monitoring of office-wide and bureau-specific strategic priorities and provides periodic reviews of progress. The Enterprise Analytics team provides ORR leadership with analytics-related programmatic briefs, leads data analysis on projects in collaboration with supporting divisions across the ORR bureaus, and supports the office of the ORR Director/DAS-HS. The Integrity and Accountability team is responsible for the mitigation, identification, and reporting of attempted fraud. The Communications and Partnerships team monitors and responds to media outlets; provides support for stakeholder engagement; manages digital communication channels; oversees the clearance processes for communication materials, rollout plans, and reports and documents that ORR is required to publicly post; and manages both internal and external communications.

B. The Refugee Program Bureau is responsible for carrying out programs that assist all populations deemed eligible by Congress for Refugee Program services, including refugees, asylees, Cuban and Haitian entrants, certain Amerasians, certain Humanitarian Parolees and Special Immigrants, Survivors of Torture, and certified victims of severe forms of trafficking in persons. The Refugee Program Bureau consists of the Division of Refugee Assistance; the Division of Refugee Services; the Division of Refugee Health; the Division of Refugee Children Services; the Division of Refugee Policy; the Division of Monitoring, Evaluation, and Learning; the Division of Refugee Data and Information; and the Division of Interagency Outreach and Response. The Director of the Refugee Program Bureau reports directly to the ORR Director/DAS-HS.

The Division of Refugee Assistance represents ORR nationally and regionally in coordinating services and capacity for refugees in a manner that helps refugees become employed and economically self-sufficient and integrated into their local communities soon after they arrive in the United States. The Division oversees and provides technical assistance to the state- administered domestic assistance programs and Wilson/Fish projects. The Division works closely with each state in designing a resettlement program specific to the needs of incoming populations. The Division develops guidance and procedures for their implementation and manages special initiatives to increase refugee self-sufficiency, such as through state-funded discretionary grants or pilot programs. The Division assists in coordinating and planning refugee support services among public and private agencies and supports the flow of information on refugee profiles and community resources in support of effective placement at the state and local levels. The Division manages the effective allocation of formula social services and targeted assistance in support of newly arriving populations. The Division tracks all state costs related to refugee assistance.

The Division of Refugee Services manages effective refugee resettlement through the programmatic implementation of grants, contracts, and special initiatives of transitional services. The Division initiates, publishes, oversees, and manages most Refugee Program Bureau discretionary grants; develops program guidelines; recommends grantee allocation; coordinates with the grants management office to review the financial expenditures under discretionary grant programs; provides data in support of apportionment requests; and provides technical assistance on discretionary grant operations. The Division coordinates and provides liaison with other Federal entities on discretionary grant operational issues and other activities as specified by the Bureau Director or required by Congressional mandate. The Division responds to unanticipated refugee and entrant arrivals or significant increases in arrivals to communities where adequate or appropriate services do not exist through supplemental initiatives. The Division works to promote economic independence among refugees through employment-related services, social services, educational services, and intensive case management and community development initiatives.

The Division of Refugee Health provides direction for ensuring that refugees are provided medical assistance and mental health services through state-administered programs and alternative programs. The Division ensures the quality of medical screening and initial medical treatment of refugees through its administration of grant programs, development of program guidance, technical assistance, and interagency agreements in support of comprehensive medical and mental health services. The Division also supports mental health services for ( print page 49891) victims of torture. The Division works closely with State Refugee Health Coordinators in the planning and provision of medical and mental health services to meet the individual needs of incoming populations through the Refugee Health Promotion Program and other behavioral health discretionary grant initiatives. The Division oversees the provision of psychosocial and rehabilitative services through Survivors of Torture programs. The Division tracks all state costs related to refugee medical assistance and screening.

The Division of Refugee Children Services provides oversight of foster care placement and services to unaccompanied refugee minors and other special populations of youth in the United States. The Division has two primary components: (1) the Unaccompanied Refugee Minors (URM) Program, which focuses on the safety, education, well-being, permanency, and self-sufficiency of youth in foster care, and (2) coordination of services through technical assistance and capacity building across ORR programs with a child-protection lens to ensure the safety and well-being of children and youth as they navigate the refugee resettlement and integration process. The Division oversees the work of the URM Program, working closely with states to ensure sufficient capacity to serve all URM-eligible populations. The Division provides oversight to the state administered URM Program, develops guidance for program administration and implementation, and provides technical assistance on a variety of administrative, case, programmatic, financial, and policy matters. The Division also manages all data collected on youth served in the URM Program and through other refugee-related programs.

The Division of Refugee Policy develops clearance and informational memoranda, briefing materials, and summary statements for ORR, ACF, and department leadership on complex and sensitive matters. The Division collaborates with other ORR divisions and regional staff to clarify and enhance existing policies and guidance, particularly in areas where the work of two or more divisions and the regions overlaps. The Division's main activities include: interpreting and developing statutory and regulatory guidance, reviewing legislation and its impacts on the Refugee Program Bureau, coordinating with the Office of General Counsel on all relevant legal issues, drafting and publishing policy letters and other forms of responsive guidance in collaboration with ORR leadership and other ORR divisions, clarifying eligibility for ORR services, enhancing existing guidance and procedures, providing technical assistance and training on policy, and reviewing OMB-approved data collections and interagency data-sharing agreements. The Division also serves as the Refugee Program Bureau's point of contact for other ACF and HHS offices related to legal and congressional coordination, such as the Government Accountability Office (GAO), Office of the Inspector General (OIG), Office of the General Counsel (OGC), Office of Legislative Affairs and Budget (OLAB), and others, and takes the lead in coordinating the development of the Annual Report to Congress and responding to congressional inquiries.

The Division of Monitoring, Evaluation and Learning leads cross-divisional monitoring of all refugee programs and services, including the development of monitoring instruments, conducting monitoring reviews, investigating grievances, maintaining dashboards to visualize monitoring results, and tracking programmatic outcomes and grantee performance. The Division leads the development of learning agendas and oversight of research and evaluation projects, such as the Annual Survey of Refugees. The Division also coordinates cross-divisional assessment and utilization of ORR refugee-related data to ensure it is being leveraged in a unified and effective manner and that it is supporting data-informed decision making and learning.

The Division of Refugee Data and Information provides integrated governance and data management for all new and existing tools and technologies designed to capture, track, and analyze refugee program data. The Division develops data sharing agreements to ensure the receipt of arrival data from key Federal sources. The Division identifies data needs to support best-in-class data services for the Refugee Program Bureau and oversees relevant data strategy and governance policies. The Division tracks the different populations served by the Refugee Program Bureau for planning and estimation purposes, and creates dashboards to organize data and address information, reporting, and quality control needs. The Division collaborates with other ORR divisions to analyze, interpret, and leverage data for enhanced efficiency, transparency, and integrity. The Division ensures that the Refugee Program Bureau is compliant with the National Archives and Records Administration's regulations. The Division works with stakeholders and partners to establish and maintain secure linkages between data sources and provides account management and training to the Refugee Program Bureau data users.

The Division of Interagency Outreach and Response has three key components: leading the Refugee Program Bureau's work on emergency preparedness and response, conducting national outreach to partners and stakeholders, and coordinating with other Federal partners to improve access to refugee program services and benefits for all eligible populations. The Division serves as the subject matter expert on responding to increases in non-traditional eligible populations and emergency scenarios involving eligible populations already in the United States; coordinates with interagency partners to ensure ORR presence in response planning and implementation for events that impact refugee communities; and develops state interagency plans and capabilities to support preparedness for potential emergency events. The Division develops national partnerships to facilitate regional and local collaboration in support of the Refugee Program Bureau and develops and implements education and training initiatives to improve partners' understanding of ORR and its services and populations. Through outreach, the Division solicits, designs, and integrates the lived experience of refugees and diaspora communities into ORR programs, policies, and partnerships; develops and launches advisory councils in support of refugee community outreach; and conducts listening sessions and information sessions with refugee communities to better understand their needs and share available resources.

C. The Unaccompanied Children Bureau is directly responsible for providing care and services to unaccompanied children who are in Federal custody by reason of their immigration status and are referred to ORR for care and custody, pursuant to the Homeland Security Act of 2002 and the William Wilberforce Trafficking ( print page 49892) Victims Protections Reauthorization Act of 2008. The Unaccompanied Children Bureau consists of the Division of Unaccompanied Children Services, Division of Planning and Logistics, Division of Health for Unaccompanied Children, Division of Unaccompanied Children Field Operations, Division of Unaccompanied Children Policy, Division of Child Protection Investigations, Division of Grants Management, Division of Unaccompanied Children Placements, Division of Quality Improvement and Performance Management, and Division of Unaccompanied Children Data Analytics and Information Management. The Bureau maintains statistical information and data on each child and any actions concerning the child while the child is under the Director's care; oversees receipt and investigations of allegations of abuse; and monitors and inspects facilities and placement locations in which unaccompanied children reside. Further, Unaccompanied Children Bureau staff ensure that services are administered in a manner that supports child welfare standards of care and services, ensuring consideration of the child's best interest in care and custody decisions. The Director of the Unaccompanied Children Bureau reports directly to the ORR Director/DAS-HS.

The Division of Unaccompanied Children Services oversees the provision of culturally appropriate legal, language, advocacy, and educational services to children in ORR facilities, which are funded through contracts and grants. The Division manages the integration of lived experience and youth voice into ORR's practices and recommendations for policies to the Division of Unaccompanied Children Policy. The Division has a regional component with staff who serve as liaisons of the Unaccompanied Children Bureau in local communities, in order to foster communication and collaboration with state and local governments, as well as community level stakeholders. The regional staff provide best practices training and technical assistance to post-release service providers and community partners who work with unaccompanied children and their sponsors.

The Division of Planning and Logistics oversees the development of comprehensive plans relating to influx care shelters and assists in the development and review of the annual plan to ensure that the Unaccompanied Children Bureau can accommodate the number of referrals of children to ORR care. The Division prepares plans for anticipated influx or emergency shelter capacity and staffing needs, as well as shipping and storage of materials. When ORR requires emergency or influx facilities to care for unaccompanied children, the Division leads the operational and logistical support of that incident response and coordination with other Federal agencies.

The Division of Health for Unaccompanied Children oversees the provision of medical and mental health services for unaccompanied children in ORR care, including vaccinations and medical examinations. The Division manages relevant public health responses to communicable diseases in collaboration with local public health authorities.

The Division of Unaccompanied Children Field Operations is responsible for working directly with unaccompanied children provider programs to ensure the safety of children in ORR care and the compliance with ORR regulations and policy guidance. The Division works with provider programs to deliver technical assistance and/or corrective action plans to ensure compliance with all program requirements. The Division also reviews, approves, or denies potential sponsors for the safe and timely release of children under the care and custody of ORR.

The Division of Unaccompanied Children Policy is responsible for drafting, researching, developing, reviewing, coordinating, and implementing program regulations and other Federal Register publications, policies, procedures, guidance, and information collections; interpreting program authorities, including statutes; coordinating relevant legal matters with the OGC; representing ORR in unaccompanied children redetermination hearings; assisting with the organization and management of administrative hearings and matters; ensuring the Unaccompanied Children Bureau's compliance with court orders, settlements, and court mandated reporting; responding to congressional inquiries and correspondence; reviewing proposed legislation and reports to Congress; and coordinating responses to oversight requests, including audits and investigations by the OIG, congressional committees, and the GAO. The Division advises ACF, ORR, and the Unaccompanied Children Bureau leadership, deputies, division directors, and staff on program authorities and requirements. The Division prepares formal, written memoranda; briefings with executive and legislative branch officials and state and local government officials; hearing documents; and litigation documents for ORR, the Unaccompanied Children Bureau leadership, and others as directed.

The Unaccompanied Children Bureau, Division of Child Protection Investigations investigates certain allegations of child abuse or neglect at ORR care provider facilities, where the Division has jurisdiction. The Division receives reports of alleged abuse or neglect involving unaccompanied children in ORR custody; investigates those claims where it has jurisdiction; initiates and conducts investigations to establish findings in relation to alleged abuse or neglect, including examining evidence and conducting interviews; issues reports; follows administrative processes as required; and submits final reports or findings to appropriate Federal, state, and local officials. The Division issues recommended corrective actions or other disciplinary actions following their investigation to ORR officials and others, as appropriate.

The Division of Grants Management supports specialized care through grants and conducts grants compliance and administration monitoring and oversight of facilities and services where unaccompanied children reside, as well as grants for services provided to children after their release from ORR care. The Division also ensures staff working with unaccompanied children, while in care and post-release, meet minimum qualifications and background check requirements.

The Division of Unaccompanied Children Placements implements intake and placement decisions for all unaccompanied children referred to ORR. The Division provides interagency coordination between ORR and Federal agencies referring placement into ORR care and custody. The Division is also ( print page 49893) responsible for transfers within the ORR provider network of programs and the placement of unaccompanied children who qualify for long-term placements within ORR care.

The Division of Quality Improvement and Performance Management includes the following teams: Prevention of Child Abuse and Neglect, Monitoring, Provider Performance Management, and Continuous Quality Improvement. The Division supports and promotes a continuous quality improvement approach by focusing on the prevention of abuse and neglect, monitoring Unaccompanied Children programs for quality and compliance, addressing concerns, and supporting the capacity of care providers to ensure the safety and well-being of unaccompanied children.

The Division of Unaccompanied Children Data Analytics and Information Management provides real-time situational awareness for the Unaccompanied Children Bureau and enables data-driven decision-making and planning through data analytics, predictive modeling, and information sharing. The Division monitors and analyzes internal and external data and statistical information on funded programs, service providers, and on specific cases, as applicable.

D. The Bureau of Operations oversees the resourcing of operational requirements in support of ORR's mission. The Bureau of Operations receives mission requirements (budget, acquisitions, human resource requirements, and technology) and provides resources as directed by the ORR Director/DAS-HS. The team coordinates with ORR, ACF, and HHS counterparts to ensure regulatory compliance and timely response to requirements and maintains a customer service focus in meeting needs. The Chief Operating Officer reports directly to the Office of the ORR Director/DAS-HS.

In collaboration and coordination with ACF, the Division of Office Operations provides advice and assistance to ORR managers in their personnel management activities, including recruitment, selection, position management, performance management, designated performance and incentive awards, employee assistance programs, and other services. The Division provides management, direction, and oversight of the following personnel administrative services: the exercise of appointing authority, position classification, awards authorization, performance management evaluation, personnel action processing and record keeping, merit promotion, special hiring, and placement programs. The Division serves as liaison between ORR, ACF, HHS, the Staffing, Recruitment and Operations Center (SROC), and the Office of Personnel Management (OPM). The Division provides technical advice and assistance on personnel policy, regulations, and laws. The Division formulates and interprets policies pertaining to existing personnel administration and management matters and formulates and interprets new human resource programs and strategies.

The Division of Budget Planning and Analysis leads ORR in the development, analysis, formulation, planning, tracking, execution, and implementation of budgetary resources and fiscal compliance functions for the office. The Division prepares annual budget estimates and related materials, coordinates technical assistance for appropriations committees and other budget stakeholders, and performs allocation and tracking of funds for all programs. The Division performs analysis on the changing needs of the populations served by ORR, provides leadership to identify budget resources, and formulates fiscal impact estimates for regulatory requirements and other policy proposals. The team certifies funding availability for grants, contracts, travel, and other expenses; oversees inter-agency agreement execution; and facilitates compliance with congressional appropriations report requirements to ensure timely mission execution. As projects end, the Division reviews unliquidated obligations to identify potential for recoupment of any funds remaining to be re-allocated.

The Division of Acquisitions Requirements oversees the development and coordination of contracting solutions to meet programmatic needs across ORR. It drives and develops acquisition forecasts for ORR programs with program directors and works with ORR project managers and technical representatives to define needs and develop requirements. The Division coordinates review of acquisition documents with ORR stakeholders and coordinates program and contract management reviews with ORR project managers and ACF, HHS, and other contract offices.

The Division works closely with the Division of Budget Planning and Analysis to align procurement needs against funding plans and constraints. Post-award, the Division performs delegated contract administration functions to ensure the full range of contract performance oversight, including but not limited to performance monitoring and assessment, quality assurance surveillance, and contract modification and follow-on action planning as appropriate. The Division develops ORR acquisition requirement processes and procedures and coordinates contractor corrective action with program managers, subject matter experts, and ORR monitoring and other teams.

The Division of Technology oversees the development and implementation of technological solutions to enhance the efficiency and effectiveness across all three ORR bureaus. The Division takes program requirements and works within the development teams to design or procure systems to meet ORR requirements. The Division also analyzes cybersecurity requirements to ensure sensitive data and information is safeguarded against unauthorized access and ensures a customer service focus to meet operational needs.

III. Continuation of Policy. Except as inconsistent with this reorganization, all statements of policy and interpretations with respect to organizational components affected by this notice within ACF, heretofore issued and in effect on this date of this reorganization, are continued in full force and effect.

IV. Delegation of Authority. All delegations and re-delegations of authority made to officials and employees of affected organizational components will continue in them or their successors pending further re-delegations, provided they are consistent with this reorganization.

V. Funds, Personnel, and Equipment. Transfer of organizations and functions affected by this reorganization shall be accompanied in each instance by direct and support funds, positions, personnel, records, equipment, supplies, and other resources. ( print page 49894)

This reorganization will be effective upon date of signature.

Steven J. Hild,

Principal Deputy Assistant Secretary for the Administration for Children and Families, performing the delegable duties of the Assistant Secretary for Children and Families.

[ FR Doc. 2024-12806 Filed 6-11-24; 8:45 am]

BILLING CODE 4184-45-P

  • Executive Orders

Reader Aids

Information.

  • About This Site
  • Legal Status
  • Accessibility
  • No Fear Act
  • Continuity Information

Log in using your username and password

  • Search More Search for this keyword Advanced search
  • Latest content
  • Current issue
  • For authors
  • New editors
  • BMJ Journals

You are here

  • Online First
  • Effects of reducing sedentary behaviour by increasing physical activity, on cognitive function, brain function and structure across the lifespan: a systematic review and meta-analysis
  • Article Text
  • Article info
  • Citation Tools
  • Rapid Responses
  • Article metrics

Download PDF

  • http://orcid.org/0000-0001-6295-9792 Natan Feter 1 ,
  • http://orcid.org/0000-0002-2420-7204 Tomasz S Ligeza 2 ,
  • Neha Bashir 3 , 4 ,
  • Ramiya J Shanmugam 3 , 4 ,
  • Bryan Montero Herrera 3 , 5 ,
  • Tamara Aldabbagh 3 , 6 ,
  • Anne-Farah Usman 3 , 4 ,
  • Ayumi Yonezawa 3 , 4 ,
  • Shane McCarthy 3 , 7 ,
  • Danielle Herrera 3 , 8 ,
  • Denise Vargas 3 , 4 ,
  • Emaad M Mir 3 , 4 ,
  • Talha Syed 3 , 9 ,
  • Sanam Desai 3 ,
  • Hector Shi 3 , 9 ,
  • William Kim 3 , 10 ,
  • Natalie Puhar 3 , 9 ,
  • Kushi Gowda 3 , 11 ,
  • Olivia Nowak 3 , 12 ,
  • Jin Kuang 3 , 13 ,
  • Flor Quiroz 3 , 9 ,
  • Eduardo L Caputo 14 ,
  • http://orcid.org/0000-0001-8882-1994 Qian Yu 13 ,
  • JJ Pionke 15 ,
  • http://orcid.org/0000-0001-6411-5710 Liye Zou 13 ,
  • http://orcid.org/0000-0002-6679-9551 Lauren B Raine 16 , 17 ,
  • Gabriele Gratton 9 , 18 ,
  • Monica Fabiani 9 , 18 ,
  • http://orcid.org/0000-0002-0204-8257 David R Lubans 19 , 20 , 21 ,
  • Pedro C Hallal 3 ,
  • http://orcid.org/0000-0001-7288-7921 Dominika M Pindus 3 , 18 , 22
  • 1 Postgraduate Program in Epidemiology , Universidade Federal do Rio Grande do Sul , Porto Alegre , Brazil
  • 2 Institute of Psychology , Jagiellonian University , Krakow , Poland
  • 3 Department of Health and Kinesiology , University of Illinois Urbana-Champaign , Urbana , Illinois , USA
  • 4 The School of Cellular and Molecular Biology , University of Illinois Urbana-Champaign , Urbana , Illinois , USA
  • 5 Department of Kinesiology , University of North Carolina at Greensboro , Greensboro , North Carolina , USA
  • 6 School of Integrative Biology , University of Illinois Urbana-Champaign , Urbana , Illinois , USA
  • 7 Department of Physiology and Biophysics , University of Illinois College of Medicine , Chicago , Illinois , USA
  • 8 Department of Surgery , Ann and Robert Lurie Children’s Hospital , Chicago , Illinois , USA
  • 9 Department of Psychology , University of Illinois Urbana-Champaign , Urbana , Illinois , USA
  • 10 Department of Economics , University of Illinois Urbana-Champaign , Urbana , Illinois , USA
  • 11 College of Medicine Peoria , University of Illinois , Peoria , Illinois , USA
  • 12 Research & Development Solutions , IQVIA , Overland Park , Kansas , USA
  • 13 School of Psychology , Shenzhen University , Shenzhen , People's Republic of China
  • 14 School of Public Health , Brown University , Providence , Rhode Island , USA
  • 15 iSchool , Syracuse University , Syracuse , New York , USA
  • 16 Department of Physical Therapy, Movement & Rehabilitation Sciences , Northeastern University , Boston , Massachusetts , USA
  • 17 Department of Medical Sciences , Northeastern University , Boston , Massachusetts , USA
  • 18 Beckman Institute for Advanced Science and Technology , University of Illinois Urbana-Champaign , Urbana , Illinois , USA
  • 19 College of Human and Social Futures , University of Newcastle Australia , Callaghan , New South Wales , Australia
  • 20 Hunter Medical Research Institute , New Lambton Heights , New South Wales , Australia
  • 21 Faculty of Sport and Health Sciences , University of Jyväskylä , Jyväskylä , Finland
  • 22 Neuroscience Program , University of Illinois Urbana-Champaign , Urbana , Illinois , USA
  • Correspondence to Dr Dominika M Pindus; pindus{at}illinois.edu

Objective To examine the acute and chronic effects of reducing prolonged sedentary time (ST) with physical activity (PA) on cognitive and brain health.

Design Systematic review and meta-analysis.

Data sources PubMed, Scopus, CINAHL, PsycINFO, SPORTDiscus, Web of Science, and ProQuest Dissertation and Theses.

Eligibility criteria Randomised controlled trials (RCTs) published from inception to 17 June 2024, with healthy participants without cognitive impairment or neurological conditions that affect cognitive functioning, aged ≥4 years, testing acute and chronic effects of reducing ST and/or prolonged ST by reallocating ST to PA on cognitive function, brain function, and structure.

Results We included 25 RCTs (n=1289) investigating acute (21 studies) and chronic (4 studies) effects on cognitive function (acute: n=20, chronic: n=4) and brain function (acute: n=7, chronic: n=1); there were no studies on brain structure. Acutely interrupting continuous ST with either multiple or a single PA bout improved cognitive function measured from 3 hours to three consecutive days based on 91 effect sizes ( g =0.17, 95% CI: 0.05 to 0.29, p=0.005, I 2 =45.5%). When comparing single versus multiple PA bouts, only multiple PA bouts yielded a positive effect on cognitive function based on 72 effect sizes ( g =0.20, 95% CI: 0.06 to 0.35, p=0.006; I 2 =48.8%). Chronic studies reported null findings on cognitive function (n=4), with some evidence of improved neural efficiency of the hippocampus (n=1).

Conclusion Interrupting ST with PA acutely improves cognitive function. The evidence from chronic studies remains inconclusive.

Systematic review registration PROSPERO CRD42020200998.

  • sedentary behavior
  • physical activity

Data availability statement

Data are available in a public, open access repository. All data used in this study are publicly available in the Open Science Framework: https://osf.io/wkyrb/?view_only=53fcae98b76b4f9e91f9208694512415 .

https://doi.org/10.1136/bjsports-2024-108444

Statistics from Altmetric.com

Request permissions.

If you wish to reuse any or all of this article please use the link below which will take you to the Copyright Clearance Center’s RightsLink service. You will be able to get a quick price and instant permission to reuse the content in many different ways.

X @davidlubans

Contributors NF: drafted the manuscript and performed data analysis; TSL: acquired the data and performed qualitative data analysis; NB, RJS: screened and acquired the data; NP, TA, A-FU, AY, SM, DH, DV, EMM, TS, SD, HS, WK, KG, ON, FQ, ELC: screened the data; JJP: codesigned search strategies; TSL, LR, PCH: contributed to data interpretation; DMMP conceived of the work presented in the manuscript, designed search strategies, acquired the data, drafted the manuscript. All authors have critically reviewed the manuscript for important intellectual content. DP acts as a guarantor for the study.

Funding This research received no specific grant from any funding agency in the public, commercial, or not-for-profit sectors. NF is funded by the CNPq (150161/2023-9). TSL is funded by the National Science Centre, Poland (2021/43/D/HS6/02959). LY was supported by Shenzhen Educational Research Funding [grant number zdzb2014], Shenzhen Science and Technology Innovation Commission [grant number 202307313000096], Social Science Foundation from the China’s Ministry of Education [grant number 23YJA880093], The Post-doctoral Fellowship [grant number 2022M711174], The National Center for Mental Health [grant number Z014], and Research Excellence Scholarships of Shenzhen University [grant number ZYZD2305] MF and GG are funded by the National Institute on Aging [grant numbers R01AG059878 and RF1AG062666]. DMP is funded by the National Institute on Aging [grant numbers R21AG080411-01A1 and R01AG059878].

Competing interests None declared.

Provenance and peer review Not commissioned; externally peer reviewed.

Supplemental material This content has been supplied by the author(s). It has not been vetted by BMJ Publishing Group Limited (BMJ) and may not have been peer-reviewed. Any opinions or recommendations discussed are solely those of the author(s) and are not endorsed by BMJ. BMJ disclaims all liability and responsibility arising from any reliance placed on the content. Where the content includes any translated material, BMJ does not warrant the accuracy and reliability of the translations (including but not limited to local regulations, clinical guidelines, terminology, drug names and drug dosages), and is not responsible for any error and/or omissions arising from translation and adaptation or otherwise.

Read the full text or download the PDF:

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

assignment operator for a function return

Clearly, it may not make that much sense to make an assignment to a function return, yet I've just encountered a strange situation and could not find a proper rule for that. The code below does not run:

works perfectly. It is not clear to me what is going on here. It looks to me that there is an inconsistency here...

Thanks a lot.

ai-py's user avatar

  • why do you want to make a function assign a value? –  Marc Commented Oct 17, 2022 at 18:37
  • 2 @Marc to learn. I am saying over there that "it may not make sense"... –  ai-py Commented Oct 17, 2022 at 18:38

2 Answers 2

It is not clear to me what is going on here.

It's fairly simple, really; the left-hand-side of an assignment statement is not allowed to just be any kind of expression, but some "kinds" of expression are valid assignment targets, and for those kinds of expression it doesn't matter what kinds of sub-expressions they may have . In your example, the left-hand-side is a subscription , which is a valid assignment target, so it's a syntactically valid assignment statement.

In particular, a subscription has two sub-expressions but it doesn't matter what lexical form those sub-expressions have. For example, the below may look perfectly normal to you, where the first sub-expression foo.bar is an attributeref and the second sub-expression index + 5 is an a_expr :

This example probably also looks perfectly normal: the first sub-expression baz[get_x()] is another subscription, and the second sub-expression get_y() is a call .

As for why it's allowed, the simple reason is that it would be a bit silly and arbitrary for the Python developers to decide on a list of restrictions on the sub-expressions. The meaning of the assignment statement is well-defined so long as the left-hand-side is one of the required lexical forms, so the only reason to impose further restrictions on the sub-expressions of those lexical forms would be to try to prevent mistakes by the programmer.

On the other hand, code like func_call()[index] = value is not necessarily a mistake anyway, because the list that func_call() returns might well be referenced elsewhere, so the mutation will be visible through other references to that list.

kaya3's user avatar

In python, not every value can be used of the left side of the assignment (so called lvalue). Basically, only 3 things can be lvalues:

  • a name, like abc
  • an attribute any_expression.name
  • a subscript any_expression[slice]

Other values, like literals, arithmetic expressions, function calls etc cannot be used on the left side:

See assignment in the grammar spec: https://docs.python.org/3/reference/grammar.html

gog's user avatar

  • That makes sense. I couldn't find these in the The Python Language Reference. –  ai-py Commented Oct 17, 2022 at 19:05
  • 1 @quasimodo: added a link to the docs –  gog Commented Oct 17, 2022 at 19:12
  • For completeness, you missed target lists. The full list of things you can assign to is given in the documentation for assignment statements . –  chepner Commented Oct 17, 2022 at 20:46

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Is it possible to have a planet that's gaslike in some areas and rocky in others?
  • Why doesn't the world fill with time travelers?
  • How do we reconcile the story of the woman caught in adultery in John 8 and the man stoned for picking up sticks on Sabbath in Numbers 15?
  • Stuck on Sokoban
  • `Drop` for list of elements of different dimensions
  • Correct Expression for Centripetal Force
  • How does the summoned monster know who is my enemy?
  • Are carbon fiber parts riveted, screwed or bolted?
  • A View over java.lang.String - improved take II
  • MetaPost: Get text width in a narrower environment
  • Can a rope thrower act as a propulsion method for land based craft?
  • Meaning of "blunk"
  • Does Vexing Bauble counter taxed 0 mana spells?
  • The meaning of "by" in "swear by God"
  • Walk or Drive to school?
  • Is there a faster way of expanding multiple polynomials with power?
  • Topology on a module over a topological ring
  • Using conditionals within \tl_put_right from latex3 explsyntax
  • Who was the "Dutch author", "Bumstone Bumstone"?
  • The size of elementary particles
  • Integral concerning the floor function
  • Parody of Fables About Authenticity
  • How does \vdotswithin work?
  • My Hydraulic brakes are seizing up and I have tried everything. Help

assignment statement function

Press Club Statement on Death of Reuters' Ryan Evans in Ukraine

PRESS RELEASE

August 28, 2024

WASHINGTON, Aug. 28 – Following is a statement from National Press Club President Emily Wilkins on the death of Reuters safety adviser Ryan Evans while on assignment in Ukraine.

“Our hearts go out to the family of Ryan Evans who died when a Russia rocket struck the hotel where he was staying with Reuters personnel in Ukraine. Two Reuters journalists were badly injured in the blast as well, and we are hoping for a quick and full recovery. “Covering war is an extremely dangerous business and journalists like this Reuters team do so with courage but also they take every precaution to stay safe so they can bring us the story. Professionals like Ryan Evans are a vital part of the planning required for journalists to safely function in dangerous areas and deliver important information. During his distinguished career he kept Reuters teams safe in war zones and most recently secure at the Olympics. We know his colleagues will miss him and all he has done to keep them safe. People like Ryan make journalism possible in today’s world.”

Founded in 1908, The National Press Club is the world’s leading professional organization for journalists. The Club has 3,00 members representing nearly every major news organization and is a leading voice for press freedom in the United States and worldwide.

529 14th Street NW, Washington, DC 20045

OPERATING HOURS 7am-11pm Monday-Friday

>> Visitor Info

IMAGES

  1. PPT

    assignment statement function

  2. What are Assignment Statement: Definition, Assignment Statement Forms

    assignment statement function

  3. Python Assignment Statement and Types

    assignment statement function

  4. PPT

    assignment statement function

  5. PPT

    assignment statement function

  6. PPT

    assignment statement function

VIDEO

  1. Python

  2. FINANCIAL STATEMENT ANALYSIS GROUP ASSIGNMENT

  3. 43 Augmented Assignment statement

  4. 6 storing values in variable, assignment statement

  5. If statement function|Excel tricks #viral #windows #excel #microsoftoffice #spreadsheettips #shorts

  6. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

COMMENTS

  1. Python's Assignment Operator: Write Robust Assignments

    In this code snippet, you first import the sqrt() function from the math module. Then you isolate the hypotenuse variable in the original equation by using the sqrt() function. Now your code works correctly. Now you know what kind of syntax is invalid. But don't get the idea that assignment statements are rigid and inflexible.

  2. 7. Simple statements

    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. ... its nonlocal scopes are the local scopes of the enclosing functions. The nonlocal statement ...

  3. Different Forms of Assignment Statements in Python

    Multiple- target assignment: x = y = 75. print(x, y) In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left. OUTPUT. 75 75. 7. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment.

  4. Assignment (computer science)

    Assignment (computer science) In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location (s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages, the assignment statement (or expression) is a fundamental construct.

  5. How To Use Assignment Expressions in Python

    Some familiarity with while loops, if statements, list comprehensions, and functions in Python 3 is useful, but not necessary. You can review our How To Code in Python 3 tutorial series for background knowledge. Using Assignment Expressions in if Statements. Let's start with an example of how you can use assignment expressions in an if statement.

  6. Assignment Statement in Python

    Learn the basics of assignment statements in Python in this tutorial. We'll cover the syntax and usage of the assignment operator, including multiple assignm...

  7. PEP 572

    Differences between assignment expressions and assignment statements. Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions. Conversely, assignment expressions don't support the advanced features found in assignment statements:

  8. Assignment Statements · Pythonium

    To store this value, we use an assignment statement. A simple assignment statement consists of a variable name, an equal sign ( assignment operator) and the value to be stored. a in the above expression is assigned the value 7. Here we see that the variable a has 2 added to it's previous value. The resulting number is 9, the addition of 7 and 2.

  9. Variables and Assignment

    Variables and Assignment¶. When programming, it is useful to be able to store information in variables. A variable is a string of characters and numbers associated with a piece of information. The assignment operator, denoted by the "=" symbol, is the operator that is used to assign values to variables in Python.The line x=1 takes the known value, 1, and assigns that value to the variable ...

  10. Variables, Expressions, and Assignments

    The first statement initializes the variable n with the value 17, this is a so-called assignment statement. The second statement is a print statement that prints the value of the variable n. ... the function returns the input value as a string and the program continues with its execution. Try it out! inp = input() inp * 3 45

  11. What is the difference between an expression and a statement in Python

    An assignment statement evaluates an expression and assigns its value to one or more targets. It is identified by the use of = outside of the context of a function call. An assert statement evaluates an expression and raises an exception if the expression's value is false. It is identified by the assert keyword.

  12. Lesson 4: Assignment Statements and Numeric Functions

    Upon completing this lesson, you should be able to do the following: write a basic assignment statement involving a numeric variable. write an assignment statement that involves an arithmetic calculation. write an assignment statement that utilizes one of the many numeric SAS functions that are available.

  13. Assignment Operators in Python

    Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand. Python. # Assigning values using # Assignment Operator a = 3 b = 5 c = a + b # Output print(c) Output.

  14. The Assignment Statement

    The meaning of the first assignment is computing the sum of the value in Counter and 1, and saves it back to Counter. Since Counter 's current value is zero, Counter + 1 is 1+0 = 1 and hence 1 is saved into Counter. Therefore, the new value of Counter becomes 1 and its original value 0 disappears. The second assignment statement computes the ...

  15. Fundamentals of Python: Functions, Formatting & Assignment Statements

    Lesson 1: Visualizing Assignment Statements. The most important note in this lesson is understanding that assignment of variables does not mean that a variable is *equal* to the value or function it is assigned to represent. Here are the rules for Executing an Assignment Statement: Evaluate the expression on the right side of the equals sign to ...

  16. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. ... Conditional Statements: Assigning different values based on conditions in conditional statements. Function Return Values: Storing the return values of functions in variables. Data Manipulation: ...

  17. What are Assignment Statement: Definition, Assignment Statement ...

    An Assignment statement is a statement that is used to set a value to the variable name in a program. Assignment statement allows a variable to hold different types of values during its program lifespan. ... expression = it could be either a direct value or a math expression/formula or a function call. Few programming languages such as Java, C ...

  18. Python Conditional Assignment (in 3 Ways)

    Let's see a code snippet to understand it better. a = 10. b = 20 # assigning value to variable c based on condition. c = a if a > b else b. print(c) # output: 20. You can see we have conditionally assigned a value to variable c based on the condition a > b. 2. Using if-else statement.

  19. IFS function

    The IFS function checks whether one or more conditions are met and returns a value that corresponds to the first TRUE condition. IFS will allow you to include up to 127 pairs of conditions (the test if something is True and the result if something is true). IFS can take the place of multiple nested IF statements.

  20. Using assignment operator in the parameter of a function call

    The built-in assignment operator =. is right-associative which means it groups to right, e.g. a = b = c means a = (b = c), is an lvalue expression that refers to the left hand side.. Note that in C an assignment produces a pure value, while in C++ it produces a reference (in the common language meaning of referring).. This means that you can assign a value to multiple variables:

  21. Federal Register :: Statement of Organization, Functions, and

    SUPPLEMENTARY INFORMATION: This notice amends Part K of the Statement of Organization, Functions, and Delegations of Authority of the Department of Health and Human Services (HHS), Administration for Children and Families (ACF), as follows: Chapter KR, Office of Refugee Resettlement, as last amended by 85 FR 85643, 2020-28706 (December 29, 2020).. I.

  22. Effects of reducing sedentary behaviour by increasing physical activity

    Objective To examine the acute and chronic effects of reducing prolonged sedentary time (ST) with physical activity (PA) on cognitive and brain health. Design Systematic review and meta-analysis. Data sources PubMed, Scopus, CINAHL, PsycINFO, SPORTDiscus, Web of Science, and ProQuest Dissertation and Theses. Eligibility criteria Randomised controlled trials (RCTs) published from inception to ...

  23. Delaware State Housing Authority Financial Statement Audit FY23

    The Delaware State Housing Authority is a component unit of the State of Delaware and is a public corporation that functions to provide home ownership, affordable rental housing and rehabilitation assistance in housing. The Authority's programs are funded through mortgage-backed security purchases, State & Federal grants and through the State sponsored Housing Development Fund.

  24. assignment operator for a function return

    It is not clear to me what is going on here. It's fairly simple, really; the left-hand-side of an assignment statement is not allowed to just be any kind of expression, but some "kinds" of expression are valid assignment targets, and for those kinds of expression it doesn't matter what kinds of sub-expressions they may have.In your example, the left-hand-side is a subscription, which is a ...

  25. Press Club Statement on Death of Reuters' Ryan Evans in Ukraine

    WASHINGTON, Aug. 28 - Following is a statement from National Press Club President Emily Wilkins on the death of Reuters safety adviser Ryan Evans while on assignment in Ukraine. "Our hearts go out to the family of Ryan Evans who died when a Russia rocket struck the hotel where he was staying with Reuters personnel in Ukraine. Two Reuters journalists were badly injured in the blast as well ...