Learn C++

1.4 — Variable assignment and initialization

In the previous lesson ( 1.3 -- Introduction to objects and variables ), we covered how to define a variable that we can use to store values. In this lesson, we’ll explore how to actually put values into variables and use those values.

As a reminder, here’s a short snippet that first allocates a single integer variable named x , then allocates two more integer variables named y and z :

Variable assignment

After a variable has been defined, you can give it a value (in a separate statement) using the = operator . This process is called assignment , and the = operator is called the assignment operator .

By default, assignment copies the value on the right-hand side of the = operator to the variable on the left-hand side of the operator. This is called copy assignment .

Here’s an example where we use assignment twice:

This prints:

When we assign value 7 to variable width , the value 5 that was there previously is overwritten. Normal variables can only hold one value at a time.

One of the most common mistakes that new programmers make is to confuse the assignment operator ( = ) with the equality operator ( == ). Assignment ( = ) is used to assign a value to a variable. Equality ( == ) is used to test whether two operands are equal in value.

Initialization

One downside of assignment is that it requires at least two statements: one to define the variable, and another to assign the value.

These two steps can be combined. When an object is defined, you can optionally give it an initial value. The process of specifying an initial value for an object is called initialization , and the syntax used to initialize an object is called an initializer .

In the above initialization of variable width , { 5 } is the initializer, and 5 is the initial value.

Different forms of initialization

Initialization in C++ is surprisingly complex, so we’ll present a simplified view here.

There are 6 basic ways to initialize variables in C++:

You may see the above forms written with different spacing (e.g. int d{7}; ). Whether you use extra spaces for readability or not is a matter of personal preference.

Default initialization

When no initializer is provided (such as for variable a above), this is called default initialization . In most cases, default initialization performs no initialization, and leaves a variable with an indeterminate value.

We’ll discuss this case further in lesson ( 1.6 -- Uninitialized variables and undefined behavior ).

Copy initialization

When an initial value is provided after an equals sign, this is called copy initialization . This form of initialization was inherited from C.

Much like copy assignment, this copies the value on the right-hand side of the equals into the variable being created on the left-hand side. In the above snippet, variable width will be initialized with value 5 .

Copy initialization had fallen out of favor in modern C++ due to being less efficient than other forms of initialization for some complex types. However, C++17 remedied the bulk of these issues, and copy initialization is now finding new advocates. You will also find it used in older code (especially code ported from C), or by developers who simply think it looks more natural and is easier to read.

For advanced readers

Copy initialization is also used whenever values are implicitly copied or converted, such as when passing arguments to a function by value, returning from a function by value, or catching exceptions by value.

Direct initialization

When an initial value is provided inside parenthesis, this is called direct initialization .

Direct initialization was initially introduced to allow for more efficient initialization of complex objects (those with class types, which we’ll cover in a future chapter). Just like copy initialization, direct initialization had fallen out of favor in modern C++, largely due to being superseded by list initialization. However, we now know that list initialization has a few quirks of its own, and so direct initialization is once again finding use in certain cases.

Direct initialization is also used when values are explicitly cast to another type.

One of the reasons direct initialization had fallen out of favor is because it makes it hard to differentiate variables from functions. For example:

List initialization

The modern way to initialize objects in C++ is to use a form of initialization that makes use of curly braces. This is called list initialization (or uniform initialization or brace initialization ).

List initialization comes in three forms:

As an aside…

Prior to the introduction of list initialization, some types of initialization required using copy initialization, and other types of initialization required using direct initialization. List initialization was introduced to provide a more consistent initialization syntax (which is why it is sometimes called “uniform initialization”) that works in most cases.

Additionally, list initialization provides a way to initialize objects with a list of values (which is why it is called “list initialization”). We show an example of this in lesson 16.2 -- Introduction to std::vector and list constructors .

List initialization has an added benefit: “narrowing conversions” in list initialization are ill-formed. This means that if you try to brace initialize a variable using a value that the variable can not safely hold, the compiler is required to produce a diagnostic (usually an error). For example:

In the above snippet, we’re trying to assign a number (4.5) that has a fractional part (the .5 part) to an integer variable (which can only hold numbers without fractional parts).

Copy and direct initialization would simply drop the fractional part, resulting in the initialization of value 4 into variable width . Your compiler may optionally warn you about this, since losing data is rarely desired. However, with list initialization, your compiler is required to generate a diagnostic in such cases.

Conversions that can be done without potential data loss are allowed.

To summarize, list initialization is generally preferred over the other initialization forms because it works in most cases (and is therefore most consistent), it disallows narrowing conversions, and it supports initialization with lists of values (something we’ll cover in a future lesson). While you are learning, we recommend sticking with list initialization (or value initialization).

Best practice

Prefer direct list initialization (or value initialization) for initializing your variables.

Author’s note

Bjarne Stroustrup (creator of C++) and Herb Sutter (C++ expert) also recommend using list initialization to initialize your variables.

In modern C++, there are some cases where list initialization does not work as expected. We cover one such case in lesson 16.2 -- Introduction to std::vector and list constructors .

Because of such quirks, some experienced developers now advocate for using a mix of copy, direct, and list initialization, depending on the circumstance. Once you are familiar enough with the language to understand the nuances of each initialization type and the reasoning behind such recommendations, you can evaluate on your own whether you find these arguments persuasive.

Value initialization and zero initialization

When a variable is initialized using empty braces, value initialization takes place. In most cases, value initialization will initialize the variable to zero (or empty, if that’s more appropriate for a given type). In such cases where zeroing occurs, this is called zero initialization .

Q: When should I initialize with { 0 } vs {}?

Use an explicit initialization value if you’re actually using that value.

Use value initialization if the value is temporary and will be replaced.

Initialize your variables

Initialize your variables upon creation. You may eventually find cases where you want to ignore this advice for a specific reason (e.g. a performance critical section of code that uses a lot of variables), and that’s okay, as long the choice is made deliberately.

Related content

For more discussion on this topic, Bjarne Stroustrup (creator of C++) and Herb Sutter (C++ expert) make this recommendation themselves here .

We explore what happens if you try to use a variable that doesn’t have a well-defined value in lesson 1.6 -- Uninitialized variables and undefined behavior .

Initialize your variables upon creation.

Initializing multiple variables

In the last section, we noted that it is possible to define multiple variables of the same type in a single statement by separating the names with a comma:

We also noted that best practice is to avoid this syntax altogether. However, since you may encounter other code that uses this style, it’s still useful to talk a little bit more about it, if for no other reason than to reinforce some of the reasons you should be avoiding it.

You can initialize multiple variables defined on the same line:

Unfortunately, there’s a common pitfall here that can occur when the programmer mistakenly tries to initialize both variables by using one initialization statement:

In the top statement, variable “a” will be left uninitialized, and the compiler may or may not complain. If it doesn’t, this is a great way to have your program intermittently crash or produce sporadic results. We’ll talk more about what happens if you use uninitialized variables shortly.

The best way to remember that this is wrong is to consider the case of direct initialization or brace initialization:

Because the parenthesis or braces are typically placed right next to the variable name, this makes it seem a little more clear that the value 5 is only being used to initialize variable b and d , not a or c .

Unused initialized variables warnings

Modern compilers will typically generate warnings if a variable is initialized but not used (since this is rarely desirable). And if “treat warnings as errors” is enabled, these warnings will be promoted to errors and cause the compilation to fail.

Consider the following innocent looking program:

When compiling this with the g++ compiler, the following error is generated:

and the program fails to compile.

There are a few easy ways to fix this.

  • If the variable really is unused, then the easiest option is to remove the defintion of x (or comment it out). After all, if it’s not used, then removing it won’t affect anything.
  • Another option is to simply use the variable somewhere:

But this requires some effort to write code that uses it, and has the downside of potentially changing your program’s behavior.

The [[maybe_unused]] attribute C++17

In some cases, neither of the above options are desirable. Consider the case where we have a bunch of math/physics values that we use in many different programs:

If we use these a lot, we probably have these saved somewhere and copy/paste/import them all together.

However, in any program where we don’t use all of these values, the compiler will complain about each variable that isn’t actually used. While we could go through and remove/comment out the unused ones for each program, this takes time and energy. And later if we need one that we’ve previously removed, we’ll have to go back and re-add it.

To address such cases, C++17 introduced the [[maybe_unused]] attribute, which allows us to tell the compiler that we’re okay with a variable being unused. The compiler will not generate unused variable warnings for such variables.

The following program should generate no warnings/errors:

Additionally, the compiler will likely optimize these variables out of the program, so they have no performance impact.

In future lessons, we’ll often define variables we don’t use again, in order to demonstrate certain concepts. Making use of [[maybe_unused]] allows us to do so without compilation warnings/errors.

Question #1

What is the difference between initialization and assignment?

Show Solution

Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.

Question #2

What form of initialization should you prefer when you want to initialize a variable with a specific value?

Direct list initialization (aka. direct brace initialization).

Question #3

What are default initialization and value initialization? What is the behavior of each? Which should you prefer?

Default initialization is when a variable initialization has no initializer (e.g. int x; ). In most cases, the variable is left with an indeterminate value.

Value initialization is when a variable initialization has an empty brace (e.g. int x{}; ). In most cases this will perform zero-initialization.

You should prefer value initialization to default initialization.

guest

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.

previous episode

Python for absolute beginners, next episode, variables and assignment.

Overview Teaching: 15 min Exercises: 15 min Questions How can I store data in programs? Objectives Write scripts that assign values to variables and perform calculations with those values. Correctly trace value changes in scripts that use assignment.

Use variables to store values

Variables are one of the fundamental building blocks of Python. A variable is like a tiny container where you store values and data, such as filenames, words, numbers, collections of words and numbers, and more.

The variable name will point to a value that you “assign” it. You might think about variable assignment like putting a value “into” the variable, as if the variable is a little box 🎁

(In fact, a variable is not a container as such but more like an adress label that points to a container with a given value. This difference will become relevant once we start talking about lists and mutable data types.)

You assign variables with an equals sign ( = ). In Python, a single equals sign = is the “assignment operator.” (A double equals sign == is the “real” equals sign.)

  • Variables are names for values.
  • In Python the = symbol assigns the value on the right to the name on the left.
  • The variable is created when a value is assigned to it.
  • Here, Python assigns an age to a variable age and a name in quotation marks to a variable first_name :

Variable names

Variable names can be as long or as short as you want, but there are certain rules you must follow.

  • Cannot start with a digit.
  • Cannot contain spaces, quotation marks, or other punctuation.
  • May contain an underscore (typically used to separate words in long variable names).
  • Having an underscore at the beginning of a variable name like _alistairs_real_age has a special meaning. So we won’t do that until we understand the convention.
  • The standard naming convention for variable names in Python is the so-called “snake case”, where each word is separated by an underscore. For example my_first_variable . You can read more about naming conventions in Python here .

Use meaningful variable names

Python doesn’t care what you call variables as long as they obey the rules (alphanumeric characters and the underscore). As you start to code, you will almost certainly be tempted to use extremely short variables names like f . Your fingers will get tired. Your coffee will wear off. You will see other people using variables like f . You’ll promise yourself that you’ll definitely remember what f means. But you probably won’t.

So, resist the temptation of bad variable names! Clear and precisely-named variables will:

  • Make your code more readable (both to yourself and others).
  • Reinforce your understanding of Python and what’s happening in the code.
  • Clarify and strengthen your thinking.

Use meaningful variable names to help other people understand what the program does. The most important “other person” is your future self!

Python is case-sensitive

Python thinks that upper- and lower-case letters are different, so Name and name are different variables. There are conventions for using upper-case letters at the start of variable names so we will use lower-case letters for now.

Off-Limits Names

The only variable names that are off-limits are names that are reserved by, or built into, the Python programming language itself — such as print , True , and list . Some of these you can overwrite into variable names (not ideal!), but Jupyter Lab (and many other environments and editors) will catch this by colour coding your variable. If your would-be variable is colour-coded green, rethink your name choice. This is not something to worry too much about. You can get the object back by resetting your kernel.

Use print() to display values

We can check to see what’s “inside” variables by running a cell with the variable’s name. This is one of the handiest features of a Jupyter notebook. Outside the Jupyter environment, you would need to use the print() function to display the variable.

You can run the print() function inside the Jupyter environment, too. This is sometimes useful because Jupyter will only display the last variable in a cell, while print() can display multiple variables. Additionally, Jupyter will display text with \n characters (which means “new line”), while print() will display the text appropriately formatted with new lines.

  • Python has a built-in function called print() that prints things as text.
  • Provide values to the function (i.e., the things to print) in parentheses.
  • To add a string to the printout, wrap the string in single or double quotations.
  • The values passed to the function are called ‘arguments’ and are separated by commas.
  • When using the print() function, we can also separate with a ‘+’ sign. However, when using ‘+’ we have to add spaces in between manually.
  • print() automatically puts a single space between items to separate them.
  • And wraps around to a new line at the end.

Variables must be created before they are used

If a variable doesn’t exist yet, or if the name has been misspelled, Python reports an error (unlike some languages, which “guess” a default value).

The last line of an error message is usually the most informative. This message lets us know that there is no variable called eye_color in the script.

Variables Persist Between Cells Variables defined in one cell exist in all other cells once executed, so the relative location of cells in the notebook do not matter (i.e., cells lower down can still affect those above). Notice the number in the square brackets [ ] to the left of the cell. These numbers indicate the order, in which the cells have been executed. Cells with lower numbers will affect cells with higher numbers as Python runs the cells chronologically. As a best practice, we recommend you keep your notebook in chronological order so that it is easier for the human eye to read and make sense of, as well as to avoid any errors if you close and reopen your project, and then rerun what you have done. Remember: Notebook cells are just a way to organize a program! As far as Python is concerned, all of the source code is one long set of instructions.

Variables can be used in calculations

  • We can use variables in calculations just as if they were values. Remember, we assigned 42 to age a few lines ago.

This code works in the following way. We are reassigning the value of the variable age by taking its previous value (42) and adding 3, thus getting our new value of 45.

Use an index to get a single character from a string

  • The characters (individual letters, numbers, and so on) in a string are ordered. For example, the string ‘AB’ is not the same as ‘BA’. Because of this ordering, we can treat the string as a list of characters.
  • Each position in the string (first, second, etc.) is given a number. This number is called an index or sometimes a subscript.
  • Indices are numbered from 0 rather than 1.
  • Use the position’s index in square brackets to get the character at that position.

Use a slice to get a substring

A part of a string is called a substring. A substring can be as short as a single character. A slice is a part of a string (or, more generally, any list-like thing). We take a slice by using [start:stop] , where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want. Mathematically, you might say that a slice selects [start:stop] . The difference between stop and start is the slice’s length. Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string.

Use the built-in function len() to find the length of a string

The built-in function len() is used to find the length of a string (and later, of other data types, too).

Note that the result is 6 and not 7. This is because it is the length of the value of the variable (i.e. 'helium' ) that is being counted and not the name of the variable (i.e. element )

Also note that nested functions are evaluated from the inside out, just like in mathematics. Thus, Python first reads the len() function, then the print() function.

Choosing a Name Which is a better variable name, m , min , or minutes ? Why? Hint: think about which code you would rather inherit from someone who is leaving the library: ts = m * 60 + s tot_sec = min * 60 + sec total_seconds = minutes * 60 + seconds Solution minutes is better because min might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).
Swapping Values Draw a table showing the values of the variables in this program after each statement is executed. In simple terms, what do the last three lines of this program do? x = 1.0 y = 3.0 swap = x x = y y = swap Solution swap = x # x->1.0 y->3.0 swap->1.0 x = y # x->3.0 y->3.0 swap->1.0 y = swap # x->3.0 y->1.0 swap->1.0 These three lines exchange the values in x and y using the swap variable for temporary storage. This is a fairly common programming idiom.
Predicting Values What is the final value of position in the program below? (Try to predict the value without running the program, then check your prediction.) initial = "left" position = initial initial = "right" Solution initial = "left" # Initial is assigned the string "left" position = initial # Position is assigned the variable initial, currently "left" initial = "right" # Initial is assigned the string "right" print(position) left The last assignment to position was “left”
Can you slice integers? If you assign a = 123 , what happens if you try to get the second digit of a ? Solution Numbers are not stored in the written representation, so they can’t be treated like strings. a = 123 print(a[1]) TypeError: 'int' object is not subscriptable
Slicing What does the following program print? library_name = 'social sciences' print('library_name[1:3] is:', library_name[1:3]) What does thing[low:high] do? What does thing[low:] (without a value after the colon) do? What does thing[:high] (without a value before the colon) do? What does thing[:] (just a colon) do? What does thing[number:negative-number] do? Solution library_name[1:3] is: oc It will slice the string, starting at the low index and ending an element before the high index It will slice the string, starting at the low index and stopping at the end of the string It will slice the string, starting at the beginning on the string, and ending an element before the high index It will print the entire string It will slice the string, starting the number index, and ending a distance of the absolute value of negative-number elements from the end of the string
Key Points Use variables to store values. Use meaningful variable names. Python is case-sensitive. Use print() to display values. Variables must be created before they are used. Variables persist between cells. Variables can be used in calculations. Use an index to get a single character from a string. Use a slice to get a substring. Use the built-in function len to find the length of a string.

Python Variables and Assignment

Python variables, variable assignment rules, every value has a type, memory and the garbage collector, variable swap, variable names are superficial labels, assignment = is shallow, decomp by var.

  • Hands-on Python Tutorial »
  • 1. Beginning With Python »

1.6. Variables and Assignment ¶

Each set-off line in this section should be tried in the Shell.

Nothing is displayed by the interpreter after this entry, so it is not clear anything happened. Something has happened. This is an assignment statement , with a variable , width , on the left. A variable is a name for a value. An assignment statement associates a variable name on the left of the equal sign with the value of an expression calculated from the right of the equal sign. Enter

Once a variable is assigned a value, the variable can be used in place of that value. The response to the expression width is the same as if its value had been entered.

The interpreter does not print a value after an assignment statement because the value of the expression on the right is not lost. It can be recovered if you like, by entering the variable name and we did above.

Try each of the following lines:

The equal sign is an unfortunate choice of symbol for assignment, since Python’s usage is not the mathematical usage of the equal sign. If the symbol ↤ had appeared on keyboards in the early 1990’s, it would probably have been used for assignment instead of =, emphasizing the asymmetry of assignment. In mathematics an equation is an assertion that both sides of the equal sign are already, in fact, equal . A Python assignment statement forces the variable on the left hand side to become associated with the value of the expression on the right side. The difference from the mathematical usage can be illustrated. Try:

so this is not equivalent in Python to width = 10 . The left hand side must be a variable, to which the assignment is made. Reversed, we get a syntax error . Try

This is, of course, nonsensical as mathematics, but it makes perfectly good sense as an assignment, with the right-hand side calculated first. Can you figure out the value that is now associated with width? Check by entering

In the assignment statement, the expression on the right is evaluated first . At that point width was associated with its original value 10, so width + 5 had the value of 10 + 5 which is 15. That value was then assigned to the variable on the left ( width again) to give it a new value. We will modify the value of variables in a similar way routinely.

Assignment and variables work equally well with strings. Try:

Try entering:

Note the different form of the error message. The earlier errors in these tutorials were syntax errors: errors in translation of the instruction. In this last case the syntax was legal, so the interpreter went on to execute the instruction. Only then did it find the error described. There are no quotes around fred , so the interpreter assumed fred was an identifier, but the name fred was not defined at the time the line was executed.

It is both easy to forget quotes where you need them for a literal string and to mistakenly put them around a variable name that should not have them!

Try in the Shell :

There fred , without the quotes, makes sense.

There are more subtleties to assignment and the idea of a variable being a “name for” a value, but we will worry about them later, in Issues with Mutable Objects . They do not come up if our variables are just numbers and strings.

Autocompletion: A handy short cut. Idle remembers all the variables you have defined at any moment. This is handy when editing. Without pressing Enter, type into the Shell just

Assuming you are following on the earlier variable entries to the Shell, you should see f autocompleted to be

This is particularly useful if you have long identifiers! You can press Alt-/ several times if more than one identifier starts with the initial sequence of characters you typed. If you press Alt-/ again you should see fred . Backspace and edit so you have fi , and then and press Alt-/ again. You should not see fred this time, since it does not start with fi .

1.6.1. Literals and Identifiers ¶

Expressions like 27 or 'hello' are called literals , coming from the fact that they literally mean exactly what they say. They are distinguished from variables, whose value is not directly determined by their name.

The sequence of characters used to form a variable name (and names for other Python entities later) is called an identifier . It identifies a Python variable or other entity.

There are some restrictions on the character sequence that make up an identifier:

The characters must all be letters, digits, or underscores _ , and must start with a letter. In particular, punctuation and blanks are not allowed.

There are some words that are reserved for special use in Python. You may not use these words as your own identifiers. They are easy to recognize in Idle, because they are automatically colored orange. For the curious, you may read the full list:

There are also identifiers that are automatically defined in Python, and that you could redefine, but you probably should not unless you really know what you are doing! When you start the editor, we will see how Idle uses color to help you know what identifies are predefined.

Python is case sensitive: The identifiers last , LAST , and LaSt are all different. Be sure to be consistent. Using the Alt-/ auto-completion shortcut in Idle helps ensure you are consistent.

What is legal is distinct from what is conventional or good practice or recommended. Meaningful names for variables are important for the humans who are looking at programs, understanding them, and revising them. That sometimes means you would like to use a name that is more than one word long, like price at opening , but blanks are illegal! One poor option is just leaving out the blanks, like priceatopening . Then it may be hard to figure out where words split. Two practical options are

  • underscore separated: putting underscores (which are legal) in place of the blanks, like price_at_opening .
  • using camel-case : omitting spaces and using all lowercase, except capitalizing all words after the first, like priceAtOpening

Use the choice that fits your taste (or the taste or convention of the people you are working with).

Table Of Contents

  • 1.6.1. Literals and Identifiers

Previous topic

1.5. Strings, Part I

1.7. Print Function, Part I

  • Show Source

Quick search

Enter search terms or a module, class or function name.

How to assign a variable in Python

Trey Hunner smiling in a t-shirt against a yellow wall

Sign in to change your settings

Sign in to your Python Morsels account to save your screencast settings.

Don't have an account yet? Sign up here .

How can you assign a variable in Python?

An equals sign assigns in Python

In Python, the equal sign ( = ) assigns a variable to a value :

This is called an assignment statement . We've pointed the variable count to the value 4 .

We don't have declarations or initializations

Some programming languages have an idea of declaring variables .

Declaring a variable says a variable exists with this name, but it doesn't have a value yet . After you've declared the variable, you then have to initialize it with a value.

Python doesn't have the concept of declaring a variable or initializing variables . Other programming languages sometimes do, but we don't.

In Python, a variable either exists or it doesn't:

If it doesn't exist, assigning to that variable will make it exist:

Valid variable names in Python

Variables in Python can be made up of letters, numbers, and underscores:

The first character in a variable cannot be a number :

And a small handful of names are reserved , so they can't be used as variable names (as noted in SyntaxError: invalid syntax ):

Reassigning a variable in Python

What if you want to change the value of a variable ?

The equal sign is used to assign a variable to a value, but it's also used to reassign a variable:

In Python, there's no distinction between assignment and reassignment .

Whenever you assign a variable in Python, if a variable with that name doesn't exist yet, Python makes a new variable with that name . But if a variable does exist with that name, Python points that variable to the value that we're assigning it to .

Variables don't have types in Python

Note that in Python, variables don't care about the type of an object .

Our amount variable currently points to an integer:

But there's nothing stopping us from pointing it to a string instead:

Variables in Python don't have types associated with them. Objects have types but variables don't . You can point a variable to any object that you'd like.

Type annotations are really type hints

You might have seen a variable that seems to have a type. This is called a type annotation (a.k.a. a "type hint"):

But when you run code like this, Python pretty much ignores these type hints. These are useful as documentation , and they can be introspected at runtime. But type annotations are not enforced by Python . Meaning, if we were to assign this variable to a different type, Python won't care:

What's the point of that?

Well, there's a number of code analysis tools that will check type annotations and show errors if our annotations don't match.

One of these tools is called MyPy .

Type annotations are something that you can opt into in Python, but Python won't do type-checking for you . If you want to enforce type annotations in your code, you'll need to specifically run a type-checker (like MyPy) before your code runs.

Use = to assign a variable in Python

Assignment in Python is pretty simple on its face, but there's a bit of complexity below the surface.

For example, Python's variables are not buckets that contain objects : Python's variables are pointers . Also you can assign into data structures in Python.

Also, it's actually possible to assign without using an equal sign in Python. But the equal sign ( = ) is the quick and easy way to assign a variable in Python.

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts .

Sign up below and I'll explain concepts that new Python programmers often overlook .

Series: Assignment and Mutation

Python's variables aren't buckets that contain things; they're pointers that reference objects.

The way Python's variables work can often confuse folks new to Python, both new programmers and folks moving from other languages like C++ or Java.

To track your progress on this Python Morsels topic trail, sign in or sign up .

Sign up below and I'll share ideas new Pythonistas often overlook .

Python's variables are not buckets that contain objects; they're pointers. Assignment statements don't copy: they point a variable to a value (and multiple variables can "point" to the same value).

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

4.6: Assignment Operator

  • Last updated
  • Save as PDF
  • Page ID 29038

  • Patrick McClanahan
  • San Joaquin Delta College

Assignment Operator

The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol. But bite your tongue, when you see the = symbol you need to start thinking: assignment. The assignment operator has two operands. The one to the left of the operator is usually an identifier name for a variable. The one to the right of the operator is a value.

The value 21 is moved to the memory location for the variable named: age. Another way to say it: age is assigned the value 21.

The item to the right of the assignment operator is an expression. The expression will be evaluated and the answer is 14. The value 14 would assigned to the variable named: total_cousins.

The expression to the right of the assignment operator contains some identifier names. The program would fetch the values stored in those variables; add them together and get a value of 44; then assign the 44 to the total_students variable.

As we have seen, assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below:

  • “=” : This is the simplest assignment operator, which was discussed above. This operator is used to assign the value on the right to the variable on the left. For example: a = 10; b = 20; ch = 'y';

If initially the value 5 is stored in the variable a,  then:  (a += 6) is equal to 11.  (the same as: a = a + 6)

If initially value 8 is stored in the variable a, then (a -= 6) is equal to  2. (the same as a = a - 6)

If initially value 5 is stored in the variable a,, then (a *= 6) is equal to 30. (the same as a = a * 6)

If initially value 6 is stored in the variable a, then (a /= 2) is equal to 3. (the same as a = a / 2)

Below example illustrates the various Assignment Operators:

Definitions

 Adapted from:  "Assignment Operator"  by  Kenneth Leroy Busbee , (Download for free at http://cnx.org/contents/[email protected] ) is licensed under  CC BY 4.0

  • Module 2: The Essentials of Python »
  • Variables & Assignment
  • View page source

Variables & Assignment 

There are reading-comprehension exercises included throughout the text. These are meant to help you put your reading to practice. Solutions for the exercises are included at the bottom of this page.

Variables permit us to write code that is flexible and amendable to repurpose. Suppose we want to write code that logs a student’s grade on an exam. The logic behind this process should not depend on whether we are logging Brian’s score of 92% versus Ashley’s score of 94%. As such, we can utilize variables, say name and grade , to serve as placeholders for this information. In this subsection, we will demonstrate how to define variables in Python.

In Python, the = symbol represents the “assignment” operator. The variable goes to the left of = , and the object that is being assigned to the variable goes to the right:

Attempting to reverse the assignment order (e.g. 92 = name ) will result in a syntax error. When a variable is assigned an object (like a number or a string), it is common to say that the variable is a reference to that object. For example, the variable name references the string "Brian" . This means that, once a variable is assigned an object, it can be used elsewhere in your code as a reference to (or placeholder for) that object:

Valid Names for Variables 

A variable name may consist of alphanumeric characters ( a-z , A-Z , 0-9 ) and the underscore symbol ( _ ); a valid name cannot begin with a numerical value.

var : valid

_var2 : valid

ApplePie_Yum_Yum : valid

2cool : invalid (begins with a numerical character)

I.am.the.best : invalid (contains . )

They also cannot conflict with character sequences that are reserved by the Python language. As such, the following cannot be used as variable names:

for , while , break , pass , continue

in , is , not

if , else , elif

def , class , return , yield , raises

import , from , as , with

try , except , finally

There are other unicode characters that are permitted as valid characters in a Python variable name, but it is not worthwhile to delve into those details here.

Mutable and Immutable Objects 

The mutability of an object refers to its ability to have its state changed. A mutable object can have its state changed, whereas an immutable object cannot. For instance, a list is an example of a mutable object. Once formed, we are able to update the contents of a list - replacing, adding to, and removing its elements.

To spell out what is transpiring here, we:

Create (initialize) a list with the state [1, 2, 3] .

Assign this list to the variable x ; x is now a reference to that list.

Using our referencing variable, x , update element-0 of the list to store the integer -4 .

This does not create a new list object, rather it mutates our original list. This is why printing x in the console displays [-4, 2, 3] and not [1, 2, 3] .

A tuple is an example of an immutable object. Once formed, there is no mechanism by which one can change of the state of a tuple; and any code that appears to be updating a tuple is in fact creating an entirely new tuple.

Mutable & Immutable Types of Objects 

The following are some common immutable and mutable objects in Python. These will be important to have in mind as we start to work with dictionaries and sets.

Some immutable objects

numbers (integers, floating-point numbers, complex numbers)

“frozen”-sets

Some mutable objects

dictionaries

NumPy arrays

Referencing a Mutable Object with Multiple Variables 

It is possible to assign variables to other, existing variables. Doing so will cause the variables to reference the same object:

What this entails is that these common variables will reference the same instance of the list. Meaning that if the list changes, all of the variables referencing that list will reflect this change:

We can see that list2 is still assigned to reference the same, updated list as list1 :

In general, assigning a variable b to a variable a will cause the variables to reference the same object in the system’s memory, and assigning c to a or b will simply have a third variable reference this same object. Then any change (a.k.a mutation ) of the object will be reflected in all of the variables that reference it ( a , b , and c ).

Of course, assigning two variables to identical but distinct lists means that a change to one list will not affect the other:

Reading Comprehension: Does slicing a list produce a reference to that list?

Suppose x is assigned a list, and that y is assigned a “slice” of x . Do x and y reference the same list? That is, if you update part of the subsequence common to x and y , does that change show up in both of them? Write some simple code to investigate this.

Reading Comprehension: Understanding References

Based on our discussion of mutable and immutable objects, predict what the value of y will be in the following circumstance:

Reading Comprehension Exercise Solutions: 

Does slicing a list produce a reference to that list?: Solution

Based on the following behavior, we can conclude that slicing a list does not produce a reference to the original list. Rather, slicing a list produces a copy of the appropriate subsequence of the list:

Understanding References: Solutions

Integers are immutable, thus x must reference an entirely new object ( 9 ), and y still references 3 .

is assignment variable

The biomedical informatics hub's Introduction to Python workshop pages

© 2019. All rights reserved.

python-intro

Variables & the assignment operator, `=`.

The last exercise in particular would have been much cleaner if we had a way of referring to that particular string instead of having to write it all out several times!

This is one of the basic use-cases of variables !

A variable is a way of keeping a handle on data. Variables can hold numerical or string data that we’ve encountered so far, as well any other type of data, as we’ll see later.

In order to create a variable in python, we use the assignment operator , = i.e. the equals sign.

For example

Naming variables

You are free to choose any name for a variable that you wish . The only exceptions are that the variable name cannot contain spaces or other special characters, and cannot correspond to a special python keyword like if , else , or for , as these are reserved for special operations.

While not being illegal ( illegal in programming means that it will give an error), you are also strongly advised to not over-write built-in function names.

For example it is technically legal to name a variable print ! However, you would then overwrite the print function and no longer be able to print things to the terminal!

Python variables are case-sensitive , so a variable called a cannot be referred to as A , and a variable called MyNumber is not the same as mynumber !

Note on variables vs the data they hold

New programmers are sometimes confused by variables vs the data they contain, especially when it comes to string variables.

For example, the following are all valid variable assignments

  • one = "1" - a variable called one that holds the single-character string “1”
  • one = 1 - a variable called one that holds the number 1
  • OnE = "one" - a variable called OnE that holds the string “one”

Using variables

Once a variable has been assigned, we can manipulate its data in exactly the same way as if we were dealing with the data (number, string, etc) directly.

would both output Bloggs .

What happened here?

  • In the first line we assigned the string "Joe Bloggs" to the variable somename .
  • Then in the second line, we access the last 6 characters of the string using the slicing that we learned about above, and print it to the terminal.

Exercise : Basic variable usage

Write a script (name the file exercise_variables.py ) and create a variable (give it any name you like!) that contains the string

Then create a second variable that contains the text

Now use the replace member-function to replace “lazy dog” with the contents of the second variable and assign the result into a third variable. Remember that a member-function is called using the

Lastly print out all three variables.

Variables exercise

The new part of this exercise is using the assignment operator; e.g.

Most of the other functionality has been covered before!

Variables exercise answer

The following example achieves each of the steps:

Here I’ve used very short and simple variable names, a , b , c - but usually a balance between simplicity and readabilty is best!

If this were part of a big script and saw variable a , b , and c , we wouldn’t have a clue what they meant.

Instead, we could use, for example input_text , replacement , and result_text . Then if we read the script again in a year’s time, (or if our collaborator reads it) there’s a much better chance that we (/ he/she) will understand it.

The output of the script should be

More assignment operators

Along with the standard assignment operator, = , Python has additional extensions that provide shorthand ways to assign values into a variable.

For example (rhs = right hand side)

  • += : add the rhs to the variable; a += 10 is the same as a = a + 10
  • *= : multiply rhs by the variable; a *= 2 is the same as a = a * 2
  • /= : divide variable by rhs; a /= 4 is the same as a = a/4

Where appropriate, this also applies to string data, e.g.

would output Some text .

Leon Lovett

Leon Lovett

Python Variables – A Guide to Variable Assignment and Naming

a computer monitor sitting on top of a wooden desk

In Python, variables are essential elements that allow developers to store and manipulate data. When writing Python code, understanding variable assignment and naming conventions is crucial for effective programming.

Python variables provide a way to assign a name to a value and use that name to reference the value later in the code. Variables can be used to store various types of data, including numbers, strings, and lists.

In this article, we will explore the basics of Python variables, including variable assignment and naming conventions. We will also dive into the different variable types available in Python and how to use them effectively.

Key Takeaways

  • Python variables are used to store and manipulate data in code.
  • Variable assignment allows developers to assign a name to a value and reference it later.
  • Proper variable naming conventions are essential for effective programming.
  • Python supports different variable types, including integers, floats, strings, and lists.

Variable Assignment in Python

Python variables are created when a value is assigned to them using the equals sign (=) operator. For example, the following code snippet assigns the integer value 5 to the variable x :

From this point forward, whenever x is referenced in the code, it will have the value 5.

Variables can also be assigned using other variables or expressions. For example, the following code snippet assigns the value of x plus 2 to the variable y :

It is important to note that variables in Python are dynamically typed, meaning that their type can change as the program runs. For example, the following code snippet assigns a string value to the variable x , then later reassigns it to an integer value:

x = "hello" x = 7

Common Mistakes in Variable Assignment

One common mistake is trying to reference a variable before it has been assigned a value. This will result in a NameError being raised. For example:

print(variable_name) NameError: name ‘variable_name’ is not defined

Another common mistake is assigning a value to the wrong variable name. For example, the following code snippet assigns the value 5 to the variable y instead of x :

y = 5 print(x) NameError: name ‘x’ is not defined

To avoid these mistakes, it is important to carefully review code and double-check variable names and values.

Using Variables in Python

Variables are used extensively in Python code for a variety of purposes, from storing user input to performing complex calculations. The following code snippet demonstrates the basic usage of variables in a simple addition program:

number1 = input("Enter the first number: ") number2 = input("Enter the second number: ") sum = float(number1) + float(number2) print("The sum of", number1, "and", number2, "is", sum)

This program prompts the user to enter two numbers, converts them to floats using the float() function, adds them together, and prints the result using the print() function.

Variables can also be used in more complex operations, such as string concatenation and list manipulation. The following code snippet demonstrates how variables can be used to combine two strings:

greeting = "Hello" name = "Alice" message = greeting + ", " + name + "!" print(message)

This program defines two variables containing a greeting and a name, concatenates them using the plus (+) operator, and prints the result.

Variable Naming Conventions in Python

In Python, proper variable naming conventions are crucial for writing clear and maintainable code. Consistently following naming conventions makes code more readable and easier to understand, especially when working on large projects with many collaborators. Here are some commonly accepted conventions:

It’s recommended to use lowercase or snake case for variable names as they are easier to read and more commonly used in Python. Camel case is common in other programming languages, but can make Python code harder to read.

Variable names should be descriptive and meaningful. Avoid using abbreviations or single letters, unless they are commonly understood, like “i” for an iterative variable in a loop. Using descriptive names will make your code easier to understand and maintain by you and others.

Lastly, it’s a good practice to avoid naming variables with reserved words in Python such as “and”, “or”, and “not”. Using reserved words can cause errors in your code, making it hard to debug.

Scope of Variables in Python

Variables in Python have a scope, which dictates where they can be accessed and used within a code block. Understanding variable scope is important for writing efficient and effective code.

Local Variables in Python

A local variable is created within a particular code block, such as a function. It can only be accessed within that block and is destroyed when the block is exited. Local variables can be defined using the same Python variable assignment syntax as any other variable.

Example: def my_function():     x = 10     print(“Value inside function:”, x) my_function() print(“Value outside function:”, x) Output: Value inside function: 10 NameError: name ‘x’ is not defined

In the above example, the variable ‘x’ is a local variable that is defined within the function ‘my_function()’. It cannot be accessed outside of that function, which is why the second print statement results in an error.

Global Variables in Python

A global variable is a variable that can be accessed from anywhere within a program. These variables are typically defined outside of any code block, at the top level of the program. They can be accessed and modified from any code block within the program.

Example: x = 10 def my_function():     print(“Value inside function:”, x) my_function() print(“Value outside function:”, x) Output: Value inside function: 10 Value outside function: 10

In the above example, the variable ‘x’ is a global variable that is defined outside of any function. It can be accessed from within the ‘my_function()’ as well as from outside it.

When defining a function, it is possible to access and modify a global variable from within the function using the ‘global’ keyword.

Example: x = 10 def my_function():     global x     x = 20 my_function() print(x) Output: 20

In the above example, the ‘global’ keyword is used to indicate that the variable ‘x’ inside the function is the same as the global variable ‘x’. The function modifies the global variable, causing the final print statement to output ’20’ instead of ’10’.

One of the most fundamental concepts in programming is the use of variables. In Python, variables allow us to store and manipulate data efficiently. Here are some practical examples of how to use variables in Python:

Mathematical Calculations

Variables are often used to perform mathematical calculations in Python. For instance, we can assign numbers to variables and then perform operations on those variables. Here’s an example:

x = 5 y = 10 z = x + y print(z) # Output: 15

In this code, we have assigned the value 5 to the variable x and the value 10 to the variable y. We then create a new variable z by adding x and y together. Finally, we print the value of z, which is 15.

String Manipulation

Variables can also be used to manipulate strings in Python. Here is an example:

first_name = “John” last_name = “Doe” full_name = first_name + ” ” + last_name print(full_name) # Output: John Doe

In this code, we have assigned the strings “John” and “Doe” to the variables first_name and last_name respectively. We then create a new variable full_name by combining the values of first_name and last_name with a space in between. Finally, we print the value of full_name, which is “John Doe”.

Working with Data Structures

Variables are also essential when working with data structures such as lists and dictionaries in Python. Here’s an example:

numbers = [1, 2, 3, 4, 5] sum = 0 for num in numbers:     sum += num print(sum) # Output: 15

In this code, we have assigned a list of numbers to the variable numbers. We then create a new variable sum and initialize it to 0. We use a for loop to iterate over each number in the list, adding it to the sum variable. Finally, we print the value of sum, which is 15.

As you can see, variables are an essential tool in Python programming. By using them effectively, you can manipulate data and perform complex operations with ease.

Variable Types in Python

Python is a dynamically typed language, which means that variables can be assigned values of different types without explicit type declaration. Python supports a wide range of variable types, each with its own unique characteristics and uses.

Numeric Types:

Python supports several numeric types, including integers, floats, and complex numbers. Integers are whole numbers without decimal points, while floats are numbers with decimal points. Complex numbers consist of a real and imaginary part, expressed as a+bi.

Sequence Types:

Python supports several sequence types, including strings, lists, tuples, and range objects. Strings are sequences of characters, while lists and tuples are sequences of values of any type. Range objects are used to represent sequences of numbers.

Mapping Types:

Python supports mapping types, which are used to store key-value pairs. The most commonly used mapping type is the dictionary, which supports efficient lookup of values based on their associated keys.

Boolean Type:

Python supports a Boolean type, which is used to represent truth values. The Boolean type has two possible values: True and False.

Python has a special value called None, which represents the absence of a value. This type is often used to indicate the result of functions that do not return a value.

Understanding the different variable types available in Python is essential for effective coding. Each type has its own unique properties and uses, and choosing the right type for a given task can help improve code clarity, efficiency, and maintainability.

Python variables are a fundamental concept that every aspiring Python programmer must understand. In this article, we have covered the basics of variable assignment and naming conventions in Python. We have also explored the scope of variables and their different types.

It is important to remember that variables play a crucial role in programming, and their effective use can make your code more efficient and easier to read. Proper naming conventions and good coding practices can also help prevent errors and improve maintainability.

As you continue to explore the vast possibilities of Python programming, we encourage you to practice using variables in your code. With a solid understanding of Python variables, you will be well on your way to becoming a proficient Python programmer.

Similar Posts

Coding Reusable Logic with Python Functions

Coding Reusable Logic with Python Functions

In the world of coding, efficiency and reusability are paramount. With Python functions, you can achieve both. Functions are code blocks that perform specific tasks and can be called multiple times throughout your program. This means you can write a block of code once and reuse it whenever you need it, saving you valuable time…

Demystifying the Python __init__ Method

Demystifying the Python __init__ Method

Python is one of the most widely used programming languages in the world, known for its simplicity and ease of use. One of the key features of Python is the __init__ method, which plays a critical role in object-oriented programming. In this article, we will explore the __init__ method in depth, starting with its syntax…

Using *args and **kwargs in Python

Using *args and **kwargs in Python

Python is a versatile language that allows for a high degree of flexibility and customization in coding. One powerful feature of Python functions is the ability to use variable arguments, which provides more flexibility in function definition and allows for a variable number of arguments to be passed to a function. This is where *args…

Introduction to Anonymous Functions in Python

Introduction to Anonymous Functions in Python

Python is a popular language used widely for coding because of its simplicity and versatility. One of the most powerful aspects of Python is its ability to use lambda functions, also known as anonymous functions. In this article, we will explore the concept of anonymous functions in Python, and how they can help simplify your…

Understanding Python Iterators and Generators

Understanding Python Iterators and Generators

Python is a high-level programming language that offers a wide range of built-in functions and data structures. One of the most powerful and versatile of these data structures are iterators and generators. In this article, we’ll take a closer look at Python iterators and generators, their types, and how to work with them to improve…

A Guide to Python’s String Methods

A Guide to Python’s String Methods

Python is a powerful programming language for text processing, thanks to its rich set of string methods. Python string methods are built-in functions that allow you to manipulate and transform text data in various ways. In this article, we will explore Python’s string methods in depth, discussing their functionalities and demonstrating their usage with examples….

cppreference.com

Std:: is_assignable, std:: is_trivially_assignable, std:: is_nothrow_assignable.

If T or U is not a complete type, (possibly cv-qualified) void , or an array of unknown bound, the behavior is undefined.

If an instantiation of a template above depends, directly or indirectly, on an incomplete type, and that instantiation could yield a different result if that type were hypothetically completed, the behavior is undefined.

If the program adds specializations for any of the templates described on this page, the behavior is undefined.

[ edit ] Helper variable templates

Inherited from std:: integral_constant, member constants, member functions, member types, [ edit ] notes.

This trait does not check anything outside the immediate context of the assignment expression: if the use of T or U would trigger template specializations, generation of implicitly-defined special member functions etc, and those have errors, the actual assignment may not compile even if std :: is_assignable < T,U > :: value compiles and evaluates to true .

[ edit ] Example

[ edit ] see also.

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 26 May 2023, at 01:57.
  • This page has been accessed 89,567 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment

Variable Declaration and Assignment

Mohammad Shah Miran

In programming, a variable serves as a placeholder for an unknown value, enabling the user to store the different data and access them whenever needed. During compilation or interpretation , the symbolic names of variables are replaced with their corresponding data locations . This article will mainly focus on the variable declaration and assignment in a Bash Script . So, let’s start.

Key Takeaways

  • Getting familiar with Bash Variables.
  • Learning to declare and assign variables.

Free Downloads

Factors of variable declaration and assignment.

There are multiple factors to be followed to declare a variable and assign data to it. Here I have listed the factors below to understand the process. Check it out.

1. Choosing Appropriate Variable Name

When choosing appropriate variable names for declaration and assignment, it’s essential to follow some guidelines to ensure clarity and readability and to avoid conflicts with other system variables. Here some common guidelines to be followed are listed below:

  • Using descriptive names: Using descriptive names in variable naming conventions involves choosing meaningful and expressive names for variables in your code. This practice improves code readability and makes it easier to grasp the purpose of the code at a glance.
  • Using lowercase letters: It is a good practice to begin variable names with a lowercase letter . This convention is not enforced by the bash language itself, but it is a widely followed practice to improve code readability and maintain consistency . For example name , age , count , etc.
  • Separating words with underscores: Using underscores to separate words in variable names enhances code readability. For example first_name , num_students , etc.
  • Avoid starting with numbers: Variable names should not begin with a number. For instance, 1var is not a valid variable
  • Avoiding special characters : Avoid using special characters , whitespace , or punctuation marks, as they can cause syntax errors or introduce unexpected behavior. For instance, using any special character such as @, $, or # anywhere while declaring a variable is not legal.

2. Declaring the Variable in the Bash Script

In Bash , declaring variables and assigning values to them can be done for different data types by using different options along with the declare command . However, you can also declare and assign the variable value without explicitly specifying the type .

3. Assigning the Value to the Variable

When declaring variables for numeric values , simply assign the desired number directly, as in age=30 for an integer or price=12.99 for a floating – point value . For strings , enclose the text in single or double quotes , such as name =’ John ‘ or city =” New York “. Booleans can be represented using 0 and 1 , where 0 indicates false and 1 represents true , like is_valid = 1 .

Arrays are declared by assigning a sequence of values enclosed in parentheses to a variable, e.g., fruits=(“apple” “banana” “orange”) . To create associative arrays ( key-value pairs ), use the declare -A command followed by assigning the elements, like declare -A ages=([“John”]=30 [“Jane”]=25) .

4 Practical Cases of Declaring and Assigning Bash Variable

In this section, I have demonstrated some sample Bash scripts that will help you understand the basic concept of variable declaration and assignment in Bash script . So let’s get into it.

Case 01: Basic Variable Assignment in Bash Script

In my first case , I have shown a basic variable assignment with its output. Here, I have taken a string and an integer variable to show the basic variable assignment mechanism. Follow the given steps to accomplish the task.

Steps to Follow >

❶ At first, launch an Ubuntu terminal .

❷ Write the following command to open a file in Nano :

  • nano : Opens a file in the Nano text editor.
  • basic_var.sh : Name of the file.

❸ Copy the script mentioned below:

The script starts with the shebang line ( #!/bin/bash ), specifying that the script should be executed using the Bash shell . Next, two variables are declared and assigned values using the format variable_name = value . The first variable is name , and it is assigned the string value “ John .” The second variable is age , assigned the numeric value 30 . The script then uses the echo command to print the values of the variables.

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable:

  • chmod : is used to change the permissions of files and directories.
  • u+x : Here, u refers to the “ user ” or the owner of the file and +x specifies the permission being added, in this case, the “ execute ” permission. When u+x is added to the file permissions, it grants the user ( owner ) permission to execute ( run ) the file.
  • basic_var.sh : File name to which the permissions are being applied.

❻ Run the script by the following command:

Basic Variable Assignment in Bash Script

Case 02: Input From User and Variable Assignment

In Bash , you can take input from the user and store it in variables using the read command . To do so use the following script:

You can follow the steps of Case 01 , to create, save and make the script executable.

Script (user_var.sh) >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. The read command is then used twice, each with the -p option, to prompt the user for input. Both the name and age variables take the name and age of the user and store them in the name and age variable with the help of the read command . Then the script uses the echo command to print the values of the variable’s name and age , respectively. The $ name and $age syntax are used to access the values stored in the variables and display them in the output.

Now, run the following command into your terminal to execute the bash file.

Input from User and Variable Assignment

Case 03: Variable Assignment Using Positional Parameters

In Bash , you can assign values to variables using positional parameters . Positional parameters are special variables that hold arguments passed to the script when it is executed. They are referenced by their position, starting from $0 for the script name, $1 for the first argument , $2 for the second argument , and so on. To do the same use the below script.

Script (var_command_line.sh) >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. The script uses the special variables $1 and $2, which represent the first and second command – line arguments , respectively, and assigns their values to the name and age variables . The $ name and $age syntax are used to access the values stored in the variables and display them using the echo command .

Now, run the following command into your terminal to execute the script.

Variable Assignment Using Positional Parameters

Upon execution of the Bash file , the script takes two command-line arguments, John and 30 , and returns the output Name : John and Age : 30 in the command line.

Case 04:  Environment Variables and Variable Scope

In Bash script , Environment Variables are another type of variable. Those variables are available in the current session and its child processes once you export your own variable in the environment. However, you can access those and scope it to a function. Here’s a sample Bash script code of environment variables and variable scope describing the concept.

Script (var_scope.sh) >

The script starts with the shebang line ( #!/bin/bash ) to specify that the Bash shell should be used for executing the script. Then, an environment variable named MY_VARIABLE is assigned the value “ Hello, World! ” using the export command . The script also defines a Bash function called my_function . Inside this function, a local variable named local_var is declared using the local keyword . After defining the function, the script proceeds to print the value of the environment variable MY_VARIABLE , which is accessible throughout the script. Upon calling the my_function , it prints the value of the local variable local_var , demonstrating its local scope .

Finally, run the following command into your terminal to execute the bash file.

Environment Variables and Variable Scope

Upon printing the My_VARIABLE and calling the my_function, the code returns “ Environment Variable: Hello, World ” and “ I am a local variable ” respectively.

In conclusion, variable declaration and assignment is a very straightforward process and does not take any extra effort to declare the variable first, just like the Python programming language . In this article, I have tried to give you a guideline on how to declare and assign variables in a Bash Scripts . I have also provided some practical cases related to this topic. However, if you have any questions or queries regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • Bash Variable Naming Conventions in Shell Script [6 Rules]
  • How to Assign Variables in Bash Script? [8 Practical Cases]
  • How to Check Variable Value Using Bash Scripts? [5 Cases]
  • How to Use Default Value in Bash Scripts? [2 Methods]
  • How to Use Set – $Variable in Bash Scripts? [2 Examples]
  • How to Read Environment Variables in Bash Script? [2 Methods]
  • How to Export Environment Variables with Bash? [4 Examples]

<< Go Back to Bash Variables | Bash Scripting Tutorial

icon linux

Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

  • Using Common Features for HCM

Considerations for Bind Variables in Table-Validated Value Sets

After you assign a value set to a flexfield, you can use bind variables in the WHERE clause.

These bind variables refer to flexfield elements:

:{SEGMENT.<segment_code>}

:{CONTEXT.<context_code>;SEGMENT.<segment_code>}

:{VALUESET.<value_set_code>}

:{FLEXFIELD.<internal_code>}

:{PARAMETER.<parameter_code>}

Segment Code

This bind variable refers to the ID or value of a segment where <segment_code> identifies the segment. Where referring to the ID, the value set is ID-validated. Where referring to the value, the value set isn't ID-validated. The data type of the bind value is the same as the data type of the segment's column.

For both descriptive and extensible flexfields, the segment must be in the same context as the source segment. The source segment contains the WHERE clause. For descriptive flexfields, if the segment is global, then the source segment must be global.

The segment must have a sequence number that's less than the sequence number of the target segment with this bind variable. A matching segment must exist in the current flexfield context.

This bind variable is useful when the set of valid values depends on the value in another segment. For example, the values to select from a CITIES table might depend upon the selected country. If SEGMENT1 contains the country value, then the WHERE clause for the CITIES table might be <country_code> = :{SEGMENT.SEGMENT1} .

Context Code

This bind variable, which is valid only for extensible flexfields, refers to the ID (if the value set is ID-validated) or value (if not ID-validated) of a segment that's in a different context than the target segment (the segment with the WHERE clause).

The <context_code> identifies the context and must be in the same category or in an ancestor category. It can't be a multiple-row context.

The <segment_code> identifies the segment. The data type of the bind value is the same as the data type of the segment's column.

The framework of extensible flexfields doesn't perform any additional validation related to mismatched values for segments defined with cross context bind parameters. Administrators must populate the correct pair of segment values.

This bind variable is useful when the set of valid values depends on the value of a segment in another context. For example, the values to select from a CERTIFICATION table for a segment in the Compliance and Certification context might depend on the value of the country segment in the Manufacturing context.

Value Set Code

This bind variable refers to the ID (if the value set is ID-validated) or value (if not ID-validated) of the segment that's assigned to the value set that's identified by the value_set_code . The data type of the bind value is the same as the data type of the segment's column.

The segment must have a sequence number that's less than the sequence number of the segment with this bind variable. If more than one segment is assigned to the value set, the closest prior matching segment will be used to resolve the bind expression. A matching segment must exist in the current flexfield context.

This bind variable is useful when the set of valid values depends on the value in another segment and that segment code can vary, such as when the value set is used for more than one context or flexfield. For example, the values to select from a CITIES table might depend upon the selected country. If the value set for the segment that contains the country value is COUNTRIES, then the WHERE clause for the CITIES table might be <country_code> = :{VALUESET.COUNTRIES} .

Flexfield Internal Code

This bind variable refers to an internal code of the flexfield in which the value set is used, or to a validation date. The internal_code must be one of the following:

APPLICATION_ID - the application ID of the flexfield in which this value set is used. The data type of APPLICATION_ID and its resulting bind value is NUMBER.

DESCRIPTIVE_FLEXFIELD_CODE - the identifying code of the flexfield in which this value set is used. The data type of DESCRIPTIVE_FLEXFIELD_CODE and its resulting bind value is VARCHAR2. Note that you use this string for both descriptive and extensible flexfields.

CONTEXT_CODE - the context code of the flexfield context in which this value set is used. The data type of CONTEXT_CODE and its resulting bind value is VARCHAR2.

SEGMENT_CODE - the identifying code of the flexfield segment in which this value set is used. The data type of SEGMENT_CODE and its resulting bind value is VARCHAR2.

VALIDATION_DATE - the current database date. The data type of VALIDATION_DATE and its resulting bind value is DATE.

Flexfield Parameters

This bind variable refers to the value of a flexfield parameter where parameter_code identifies the parameter. The data type of the resulting bind value is the same as the parameter's data type.

Related Topics

  • Create and Edit Table-Validated Value Sets Based on Lookups

IMAGES

  1. Learn Python Programming Tutorial 4

    is assignment variable

  2. Difference Between Variable Declaration vs Assignment vs Initialization?

    is assignment variable

  3. 1.4. Expressions and Assignment Statements

    is assignment variable

  4. Variables In Python

    is assignment variable

  5. PPT

    is assignment variable

  6. Assignment and Variables : Python Tutorial #2

    is assignment variable

VIDEO

  1. Removing automatic assignment proration in Variable Pay

  2. Assignment operators in java

  3. Assignment Statement and Constant Variable

  4. PHP Variable Scope & Operator

  5. 6 storing values in variable, assignment statement

  6. Variable Declaration, Initialization, Assignment Lecture

COMMENTS

  1. 1.4

    int x; // define an integer variable named x int y, z; // define two integer variables, named y and z. Variable assignment. After a variable has been defined, you can give it a value (in a separate statement) using the = operator. This process is called assignment, and the = operator is called the assignment operator.

  2. Python's Assignment Operator: Write Robust Assignments

    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.

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

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

  5. Variables in Python

    In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ): Python. >>> n = 300. This is read or interpreted as " n is assigned the value 300 .".

  6. Variable Assignment

    Variable Assignment. Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ).

  7. Python Variable Assignment. Explaining One Of The Most Fundamental

    Assignment sets a value to a variable. To assign variable a value, use the equals sign (=) myFirstVariable = 1 mySecondVariable = 2 myFirstVariable = "Hello You" Assigning a value is known as binding in Python. In the example above, we have assigned the value of 2 to mySecondVariable. Note how I assigned an integer value of 1 and then a string ...

  8. Variables and Assignment

    You assign variables with an equals sign ( = ). In Python, a single equals sign = is the "assignment operator." (A double equals sign == is the "real" equals sign.) Variables are names for values. In Python the = symbol assigns the value on the right to the name on the left. The variable is created when a value is assigned to it.

  9. Python Variables and Assignment

    A Python variable is a named bit of computer memory, keeping track of a value as the code runs. A variable is created with an "assignment" equal sign =, with the variable's name on the left and the value it should store on the right: x = 42 In the computer's memory, each variable is like a box, identified by the name of the variable.

  10. 1.6. Variables and Assignment

    A variable is a name for a value. An assignment statement associates a variable name on the left of the equal sign with the value of an expression calculated from the right of the equal sign. Enter. width. Once a variable is assigned a value, the variable can be used in place of that value. The response to the expression width is the same as if ...

  11. How to assign a variable in Python

    This is called an assignment statement.We've pointed the variable count to the value 4.. We don't have declarations or initializations. Some programming languages have an idea of declaring variables.. Declaring a variable says a variable exists with this name, but it doesn't have a value yet.After you've declared the variable, you then have to initialize it with a value.

  12. Assignment (=)

    Assignment (=) The assignment ( =) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  13. 4.6: Assignment Operator

    Assignment Operator. The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol.

  14. Variables & Assignment

    Assign this list to the variable x; x is now a reference to that list. Using our referencing variable, x, update element-0 of the list to store the integer -4. This does not create a new list object, rather it mutates our original list. This is why printing x in the console displays [-4, 2, 3] and not [1, 2, 3]. A tuple is an example of an ...

  15. Variables & the assignment operator, `=` · python-intro

    More assignment operators. Along with the standard assignment operator, =, Python has additional extensions that provide shorthand ways to assign values into a variable. For example (rhs = right hand side) +=: add the rhs to the variable; a += 10 is the same as a = a + 10 *=: multiply rhs by the variable; a *= 2 is the same as a = a * 2

  16. Is variable assignment a statement or expression?

    defines the variable named x and initialises it with the expression 5. 5 is a literal value. If x has been previously declared, x = 5; is a simple expression statement - its sole purpose is evaluating an assignment expression. The 5, again, is a literal with value 5. x = 5 is therefore an expression, which assigns x to have the value 5.

  17. Python Variables

    Python variables provide a way to assign a name to a value and use that name to reference the value later in the code. Variables can be used to store various types of data, including numbers, strings, and lists. In this article, we will explore the basics of Python variables, including variable assignment and naming conventions.

  18. std::is_assignable, std::is_trivially_assignable, std::is_nothrow

    Notes. This trait does not check anything outside the immediate context of the assignment expression: if the use of T or U would trigger template specializations, generation of implicitly-defined special member functions etc, and those have errors, the actual assignment may not compile even if std:: is_assignable < T,U >:: value compiles and evaluates to true.

  19. JavaScript OR (||) variable assignment explanation

    Agreed, this is my favorite answer as it specifically addresses JavaScript variable assignment concerns. Additionally, if you choose to use a ternary as one of the subsequent variables to test for assignment (after the operator) you must wrap the ternary in parentheses for assignment evaluation to work properly. -

  20. Variable Declaration and Assignment

    In programming, a variable serves as a placeholder for an unknown value, enabling the user to store the different data and access them whenever needed.During compilation or interpretation, the symbolic names of variables are replaced with their corresponding data locations.This article will mainly focus on the variable declaration and assignment in a Bash Script.

  21. Set Variable Assignment Enable State

    Set Variable Assignment Enable State

  22. Considerations for Bind Variables in Table-Validated Value Sets

    This bind variable refers to the ID (if the value set is ID-validated) or value (if not ID-validated) of the segment that's assigned to the value set that's identified by the value_set_code. The data type of the bind value is the same as the data type of the segment's column. The segment must have a sequence number that's less than the sequence ...

  23. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...