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

If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

To log in and use all the features of Khan Academy, please enable JavaScript in your browser.

AP®︎/College Computer Science Principles

Course: ap®︎/college computer science principles   >   unit 3, storing data in variables, assigning variables, displaying variables, re-assigning variables, pseudocode for variables.

  • (Choice A)   x ← 200 A x ← 200
  • (Choice B)   var x = 200 B var x = 200
  • (Choice C)   x = 200 C x = 200
  • (Choice D)   var x ← 200 D var x ← 200

Want to join the conversation?

  • Upvote Button navigates to signup page
  • Downvote Button navigates to signup page
  • Flag Button navigates to signup page

Good Answer

Introduction to Programming

Variables in python.

  • The purpose of a variable is to store information within a program while it is running.
  • A variable is a named storage location in computer memory. Use the name to access the value.
  • To store a value in a variable, use the = operator (called the assignment operator).
  • An = sign in Python is nothing like an equal sign in mathematics. Think of it more like an arrow going from right to left. The expression on the right is evaluated and then stored in the variable named on the left.
  • For example, the line of code hourly_wage = 16.75 stores the value 16.75 in the variable called hourly_wage
  • You can change the value of a variable with another assignment statement, such as hourly_wage = 17.25
  • Every value has a type ( int for integers, float for decimals, str for text). In python, when you store a value in a variable (with = ), that variable then automatically has a type. For example, after the above assignment, hourly_wage is of type float .

Rules and conventions for naming variables in python

  • The first character must be a letter or an underscore. For now, stick to letters for the first character.
  • The remaining characters must be letters, numbers or underscores.
  • No spaces are allowed in variable names.
  • Legal examples: _pressure , pull , x_y , r2d2
  • Invalid examples, these are NOT legal variable names: 4th_dimension , %profit , x*y , four(4) , repo man
  • In python, it's a conventiion to use snake case to name variables. This means that we use all lower-case letters and we separate words in the variable name with underscores. Examples include age , x_coordinate , hourly_wage , user_password
  • If the value stored in a variable is a true constant (in other words, its value will never change throughout the program), then we use all capital letters: COURSE_ENROLLMENT_LIMIT , MAX_PASSWORD_ATTEMPTS .
  • For high quality code, it is crucial that you give descriptive names for variables. The variable names must help the reader of your program understand your intention.

Typical way we visualize variables

We usually draw variables by putting the value in a box, and labelling the box with the name of the variable:

Visual representation of a variable

Types of variables

Each variable has a name, a value, and a type. Types are necessary because different kinds of data are stored differently within the computer's memory. For now, we will learn three different types, for storing signed (positive or negative) whole numbers, signed decimals, and text.

Creating a variable with an assignment operator

A variable is created or declared when we assign a value to it using the assignment operator = . In python, the code looks like this: variable_name = <value> .

Notice that the left hand side of an assignment must be a variable name. Non-example:

After creating a variable, you can change the value stored in a variable with another assignment operator at any time. This is called reassignment .

Finding out the type of a variable or value

The type() function in python will return the type of either a variable or a value. Here are examples that show how to use it:

The output of the above code will be:

Casting (changing the type) of a variable or value

You can change the type of a value (called “casting”) using the int() , float() and str() functions. For example:

  • int(23.7) (truncates the float value 23.7 to the int value 23. This is different from rounding - the decimal part is discarded, regardless of whether it is larger or smaller than 0.5.
  • float(23) (outputting the result will give 23.0 rather than 23)
  • str(23) (converts the integer 23 to the text "23" )
  • int("23") (converts the string "23" into a numerical integer value 23 )
  • float("23") (converts the string "23" into a numerical decimal value 23.0 )
  • int("23.5") results in an error
  • float("hello") results in an error

Doing arithmetic in python

Here are the basic arithmetic operators in python. In these examples, assume

An example of a use of the modulus operator is to determine if an integer is even or odd. Note that if x is an integer, then x%2 takes the value 0 or 1 . So x % 2 == 0 is True when x is even and False when x is odd.

Another example of integer division and modulus: When we divide 3 by 4, we get a quotient of 0 and a remainder of 3. So 3//4 results in 0 and 3%4 results in 3.

Warning note: In python, ^ is not an exponent!

Order of operations

The order of operations in python is similar to the order you are familiar with in math: parentheses, then exponentiation, then multiplication/division/modulus in order from left to right, then addition/subtraction in order from left to right.

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.

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

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

Variable Assignment

To "assign" a variable means to symbolically associate a specific piece of information with a name. Any operations that are applied to this "name" (or variable) must hold true for any possible values. The assignment operator is the equals sign which SHOULD NEVER be used for equality, which is the double equals sign.

The '=' symbol is the assignment operator. Warning, while the assignment operator looks like the traditional mathematical equals sign, this is NOT the case. The equals operator is '=='

Design Pattern

To evaluate an assignment statement:

  • Evaluate the "right side" of the expression (to the right of the equal sign).
  • Once everything is figured out, place the computed value into the variables bucket.

We've already seen many examples of assignment. Assignment means: "storing a value (of a particular type) under a variable name" . Think of each assignment as copying the value of the righthand side of the expression into a "bucket" associated with the left hand side name!

Read this as, the variable called "name" is "assigned" the value computed by the expression to the right of the assignment operator ('=');

Now that you have seen some variables being assigned, tell me what the following code means?

The answer to above questions: the assignment means that lkjasdlfjlskdfjlksjdflkj is a variable (a really badly named one), but a variable none-the-less. jlkajdsf and lkjsdflkjsdf must also be variables. The sum of the two numbers held in jlkajdsf and lkjsdflkjsdf is stored in the variable lkjasdlfjlskdfjlksjdflkj.

Examples of builtin Data and Variables (and Constants)

For more info, use the "help" command: (e.g., help realmin);

Examples of using Data and Variable

Pattern to memorize, assignment pattern.

The assignment pattern creates a new variable, if this is the first time we have seen the "name", or, updates the variable to a new value!

Read the following code in English as: First, compute the value of the thing to the right of the assignment operator (the =). then store the computed value under the given name, destroying anything that was there before.

Or more concisely: assign the variable "name" the value computed by "right_hand_expression"

Darren Jones

A Guide to Variable Assignment and Mutation in JavaScript

Share this article

A Guide to Variable Assignment and Mutation in JavaScript

Variable Assignment

Variable reassignment, variable assignment by reference, copying by reference, the spread operator to the rescue, are mutations bad, frequently asked questions (faqs) about javascript variable assignment and mutation.

Mutations are something you hear about fairly often in the world of JavaScript, but what exactly are they, and are they as evil as they’re made out to be?

In this article, we’re going to cover the concepts of variable assignment and mutation and see why — together — they can be a real pain for developers. We’ll look at how to manage them to avoid problems, how to use as few as possible, and how to keep your code predictable.

If you’d like to explore this topic in greater detail, or get up to speed with modern JavaScript, check out the first chapter of my new book Learn to Code with JavaScript for free.

Let’s start by going back to the very basics of value types …

Every value in JavaScript is either a primitive value or an object. There are seven different primitive data types:

  • numbers, such as 3 , 0 , -4 , 0.625
  • strings, such as 'Hello' , "World" , `Hi` , ''
  • Booleans, true and false
  • symbols — a unique token that’s guaranteed never to clash with another symbol
  • BigInt — for dealing with large integer values

Anything that isn’t a primitive value is an object , including arrays, dates, regular expressions and, of course, object literals. Functions are a special type of object. They are definitely objects, since they have properties and methods, but they’re also able to be called.

Variable assignment is one of the first things you learn in coding. For example, this is how we would assign the number 3 to the variable bears :

A common metaphor for variables is one of boxes with labels that have values placed inside them. The example above would be portrayed as a box containing the label “bears” with the value of 3 placed inside.

variables like a box

An alternative way of thinking about what happens is as a reference, that maps the label bears to the value of 3 :

variables like a reference

If I assign the number 3 to another variable, it’s referencing the same value as bears:

variables referencing the same value

The variables bears and musketeers both reference the same primitive value of 3. We can verify this using the strict equality operator, === :

The equality operator returns true if both variables are referencing the same value.

Some gotchas when working with objects

The previous examples showed primitive values being assigned to variables. The same process is used when assigning objects:

This assignment means that the variable ghostbusters references an object:

variables referencing different objects

A big difference when assigning objects to variables, however, is that if you assign another object literal to another variable, it will reference a completely different object — even if both object literals look exactly the same! For example, the assignment below looks like the variable tmnt (Teenage Mutant Ninja Turtles) references the same object as the variable ghostbusters :

Even though the variables ghostbusters and tmnt look like they reference the same object, they actually both reference a completely different object, as we can see if we check with the strict equality operator:

variables referencing different objects

When the const keyword was introduced in ES6, many people mistakenly believed that constants had been introduced to JavaScript, but this wasn’t the case. The name of this keyword is a little misleading.

Any variable declared with const can’t be reassigned to another value. This goes for primitive values and objects. For example, the variable bears was declared using const in the previous section, so it can’t have another value assigned to it. If we try to assign the number 2 to the variable bears , we get an error:

The reference to the number 3 is fixed and the bears variable can’t be reassigned another value.

The same applies to objects. If we try to assign a different object to the variable ghostbusters , we get the same error:

Variable reassignment using let

When the keyword let is used to declare a variable, it can be reassigned to reference a different value later on in our code. For example, we declared the variable musketeers using let , so we can change the value that musketeers references. If D’Artagnan joined the Musketeers, their number would increase to 4:

variables referencing different values

This can be done because let was used to declare the variable. We can alter the value that musketeers references as many times as we like.

The variable tmnt was also declared using let , so it can also be reassigned to reference another object (or a different type entirely if we like):

Note that the variable tmnt now references a completely different object ; we haven’t just changed the number property to 5.

In summary , if you declare a variable using const , its value can’t be reassigned and will always reference the same primitive value or object that it was originally assigned to. If you declare a variable using let , its value can be reassigned as many times as required later in the program.

Using const as often as possible is generally considered good practice, as it means that the value of variables remains constant and the code is more consistent and predictable, making it less prone to errors and bugs.

In native JavaScript, you can only assign values to variables. You can’t assign variables to reference another variable, even though it looks like you can. For example, the number of Stooges is the same as the number of Musketeers, so we can assign the variable stooges to reference the same value as the variable musketeers using the following:

This looks like the variable stooges is referencing the variable musketeers , as shown in the diagram below:

variables cannot reference another variable

However, this is impossible in native JavaScript: a variable can only reference an actual value; it can’t reference another variable . What actually happens when you make an assignment like this is that the variable on the left of the assignment will reference the value the variable on the right references, so the variable stooges will reference the same value as the musketeers variable, which is the number 3. Once this assignment has been made, the stooges variable isn’t connected to the musketeers variable at all.

variables referencing values

This means that if D’Artagnan joins the Musketeers and we set the value of the musketeers to 4, the value of stooges will remain as 3. In fact, because we declared the stooges variable using const , we can’t set it to any new value; it will always be 3.

In summary : if you declare a variable using const and set it to a primitive value, even via a reference to another variable, then its value can’t change. This is good for your code, as it means it will be more consistent and predictable.

A value is said to be mutable if it can be changed. That’s all there is to it: a mutation is the act of changing the properties of a value.

All primitive value in JavaScript are immutable : you can’t change their properties — ever. For example, if we assign the string "cake" to variable food , we can see that we can’t change any of its properties:

If we try to change the first letter to “f”, it looks like it has changed:

But if we take a look at the value of the variable, we see that nothing has actually changed:

The same thing happens if we try to change the length property:

Despite the return value implying that the length property has been changed, a quick check shows that it hasn’t:

Note that this has nothing to do with declaring the variable using const instead of let . If we had used let , we could set food to reference another string, but we can’t change any of its properties. It’s impossible to change any properties of primitive data types because they’re immutable .

Mutability and objects in JavaScript

Conversely, all objects in JavaScript are mutable, which means that their properties can be changed, even if they’re declared using const (remember let and const only control whether or not a variable can be reassigned and have nothing to do with mutability). For example, we can change the the first item of an array using the following code:

Note that this change still occurred, despite the fact that we declared the variable food using const . This shows that using const does not stop objects from being mutated .

We can also change the length property of an array, even if it has been declared using const :

Remember that when we assign variables to object literals, the variables will reference completely different objects, even if they look the same:

But if we assign a variable fantastic4 to another variable, they will both reference the same object:

This assigns the variable fantastic4 to reference the same object that the variable tmnt references, rather than a completely different object.

variables referencing the same object

This is often referred to as copying by reference , because both variables are assigned to reference the same object.

This is important, because any mutations made to this object will be seen in both variables.

So, if Spider-Man joins The Fantastic Four, we might update the number value in the object:

This is a mutation, because we’ve changed the number property rather than setting fantastic4 to reference a new object.

This causes us a problem, because the number property of tmnt will also also change, possibly without us even realizing:

This is because both tmnt and fantastic4 are referencing the same object, so any mutations that are made to either tmnt or fantastic4 will affect both of them.

This highlights an important concept in JavaScript: when objects are copied by reference and subsequently mutated, the mutation will affect any other variables that reference that object. This can lead to unintended side effects and bugs that are difficult to track down.

So how do you make a copy of an object without creating a reference to the original object? The answer is to use the spread operator !

The spread operator was introduced for arrays and strings in ES2015 and for objects in ES2018. It allows you to easily make a shallow copy of an object without creating a reference to the original object.

The example below shows how we could set the variable fantastic4 to reference a copy of the tmnt object. This copy will be exactly the same as the tmnt object, but fantastic4 will reference a completely new object. This is done by placing the name of the variable to be copied inside an object literal with the spread operator in front of it:

What we’ve actually done here is assign the variable fantastic4 to a new object literal and then used the spread operator to copy all the enumerable properties of the object referenced by the tmnt variable. Because these properties are values, they’re copied into the fantastic4 object by value, rather than by reference.

variables referencing different objects

Now any changes that are made to either object won’t affect the other. For example, if we update the number property of the fantastic4 variable to 5, it won’t affect the tmnt variable:

Changes don't affect the other object

The spread operator also has a useful shortcut notation that can be used to make copies of an object and then make some changes to the new object in a single line of code.

For example, say we wanted to create an object to model the Teenage Mutant Ninja Turtles. We could create the first turtle object, and assign the variable leonardo to it:

The other turtles all have the same properties, except for the weapon and color properties, that are different for each turtle. It makes sense to make a copy of the object that leonardo references, using the spread operator, and then change the weapon and color properties, like so:

We can do this in one line by adding the properties we want to change after the reference to the spread object. Here’s the code to create new objects for the variables donatello and raphael :

Note that using the spread operator in this way only makes a shallow copy of an object. To make a deep copy, you’d have to do this recursively, or use a library. Personally, I’d advise that you try to keep your objects as shallow as possible.

In this article, we’ve covered the concepts of variable assignment and mutation and seen why — together — they can be a real pain for developers.

Mutations have a bad reputation, but they’re not necessarily bad in themselves. In fact, if you’re building a dynamic web app, it must change at some point. That’s literally the meaning of the word “dynamic”! This means that there will have to be some mutations somewhere in your code. Having said that, the fewer mutations there are, the more predictable your code will be, making it easier to maintain and less likely to develop any bugs.

A particularly toxic combination is copying by reference and mutations. This can lead to side effects and bugs that you don’t even realize have happened. If you mutate an object that’s referenced by another variable in your code, it can cause lots of problems that can be difficult to track down. The key is to try and minimize your use of mutations to the essential and keep track of which objects have been mutated.

In functional programming, a pure function is one that doesn’t cause any side effects, and mutations are one of the biggest causes of side effects.

A golden rule is to avoid copying any objects by reference. If you want to copy another object, use the spread operator and then make any mutations immediately after making the copy.

Next up, we’ll look into array mutations in JavaScript .

Don’t forget to check out my new book Learn to Code with JavaScript if you want to get up to speed with modern JavaScript. You can read the first chapter for free. And please reach out on Twitter if you have any questions or comments!

What is the difference between variable assignment and mutation in JavaScript?

In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand, mutation refers to the process of changing the value of an existing variable. For example, if we later write x = 10; we are mutating the variable x by changing its value from 5 to 10.

How does JavaScript handle variable assignment and mutation differently for primitive and non-primitive data types?

JavaScript treats primitive data types (like numbers, strings, and booleans) and non-primitive data types (like objects and arrays) differently when it comes to variable assignment and mutation. For primitive data types, when you assign a variable, a copy of the value is created and stored in a new memory location. However, for non-primitive data types, when you assign a variable, both variables point to the same memory location. Therefore, if you mutate one variable, the change is reflected in all variables that point to that memory location.

What is the concept of pass-by-value and pass-by-reference in JavaScript?

Pass-by-value and pass-by-reference are two ways that JavaScript can pass variables to a function. When JavaScript passes a variable by value, it creates a copy of the variable’s value and passes that copy to the function. Any changes made to the variable inside the function do not affect the original variable. However, when JavaScript passes a variable by reference, it passes a reference to the variable’s memory location. Therefore, any changes made to the variable inside the function also affect the original variable.

How can I prevent mutation in JavaScript?

There are several ways to prevent mutation in JavaScript. One way is to use the Object.freeze() method, which prevents new properties from being added to an object, existing properties from being removed, and prevents changing the enumerability, configurability, or writability of existing properties. Another way is to use the const keyword when declaring a variable. This prevents reassignment of the variable, but it does not prevent mutation of the variable’s value if the value is an object or an array.

What is the difference between shallow copy and deep copy in JavaScript?

In JavaScript, a shallow copy of an object is a copy of the object where the values of the original object and the copy point to the same memory location for non-primitive data types. Therefore, if you mutate the copy, the original object is also mutated. On the other hand, a deep copy of an object is a copy of the object where the values of the original object and the copy do not point to the same memory location. Therefore, if you mutate the copy, the original object is not mutated.

How can I create a deep copy of an object in JavaScript?

One way to create a deep copy of an object in JavaScript is to use the JSON.parse() and JSON.stringify() methods. The JSON.stringify() method converts the object into a JSON string, and the JSON.parse() method converts the JSON string back into an object. This creates a new object that is a deep copy of the original object.

What is the MutationObserver API in JavaScript?

The MutationObserver API provides developers with a way to react to changes in a DOM. It is designed to provide a general, efficient, and robust API for reacting to changes in a document.

How does JavaScript handle variable assignment and mutation in the context of closures?

In JavaScript, a closure is a function that has access to its own scope, the scope of the outer function, and the global scope. When a variable is assigned or mutated inside a closure, it can affect the value of the variable in the outer scope, depending on whether the variable was declared in the closure’s scope or the outer scope.

What is the difference between var, let, and const in JavaScript?

In JavaScript, var, let, and const are used to declare variables. var is function scoped, and if it is declared outside a function, it is globally scoped. let and const are block scoped, meaning they exist only within the block they are declared in. The difference between let and const is that let allows reassignment, while const does not.

How does JavaScript handle variable assignment and mutation in the context of asynchronous programming?

In JavaScript, asynchronous programming allows multiple things to happen at the same time. When a variable is assigned or mutated in an asynchronous function, it can lead to unexpected results if other parts of the code are relying on the value of the variable. This is because the variable assignment or mutation may not have completed before the other parts of the code run. To handle this, JavaScript provides several features, such as promises and async/await, to help manage asynchronous code.

Darren loves building web apps and coding in JavaScript, Haskell and Ruby. He is the author of Learn to Code using JavaScript , JavaScript: Novice to Ninja and Jump Start Sinatra .He is also the creator of Nanny State , a tiny alternative to React. He can be found on Twitter @daz4126.

SitePoint Premium

5 Best Ways to Declare a Variable in Python

💡 Problem Formulation: When starting with Python programming, a common task is to store values in variables. Consider the need to track the score in a game or the need to store user input. This article walks through the various methods of declaring variables in Python to store such pieces of information effectively.

Method 1: Basic Variable Assignment

This is the most straightforward method for creating and assigning a variable in Python. You simply declare a variable by typing its name, followed by an equals sign, and the value you wish to assign to it. This method is readable, writable, and often used for its simplicity.

Here’s an example:

The line score = 10 initializes a variable called score with the integer value 10 . This variable can now be used in other parts of a Python program to represent the score in a game.

Method 2: Assignment with Type Annotation (Python 3.6+)

Type annotations allow the programmer to explicitly state the expected data type of a variable. Python 3.6 introduced this capability, which aids in code readability and can help with type checking when using tools like MyPy.

In the example username: str = "PlayerOne" , we declare a variable username with the type annotation str , which indicates it should store a string, and we assign it the value “PlayerOne”. Type annotations are optional in Python but can be very informative.

Method 3: Multiple Assignment

Python allows you to assign multiple variables at once in a single line. This can be cleaner and more efficient when initializing several variables that may relate to each other.

In the snippet x, y, z = 1, 2, 3 , we simultaneously create three variables x , y , and z , assigning them the values 1 , 2 , and 3 respectively. This is a compact way of declaring related variables.

Method 4: Unpacking a Sequence

When you have a list or tuple, you can “unpack” its values into separate variables. This is particularly useful when the sequence size is known, and you want to assign its elements to named variables.

Here, coordinates is a tuple with two elements. The line x, y = coordinates unpacks those elements into variables x and y . This results in x having the value of 10 and y the value of 20 .

Bonus One-Liner Method 5: Variable Assignment with Chained Operators

Python permits chaining assignment operators to assign the same value to multiple variables in a single line. This method is a one-liner that makes the code concise when initial values are the same.

The line a = b = c = 0 initializes the variables a , b , and c to 0 . Now all three variables can be used independently, yet they start with the same initial value.

Summary/Discussion

  • Method 1: Basic Variable Assignment. Simple and universally applicable. No inherent weaknesses except lack of type declaration.
  • Method 2: Assignment with Type Annotation. Great for code clarity and for use with static type checkers. Not supported in versions of Python before 3.6.
  • Method 3: Multiple Assignment. Efficient for declaring multiple variables at once, but may lead to reduced readability if overused.
  • Method 4: Unpacking a Sequence. Clean and elegant, provided that the structure of the sequence is known beforehand. Not practical for variable-length sequences.
  • Bonus Method 5: Variable Assignment with Chained Operators. Handy for initializing multiple variables with the same value. Can be confusing if used beyond simple initializations.

Emily Rosemary Collins is a tech enthusiast with a strong background in computer science, always staying up-to-date with the latest trends and innovations. Apart from her love for technology, Emily enjoys exploring the great outdoors, participating in local community events, and dedicating her free time to painting and photography. Her interests and passion for personal growth make her an engaging conversationalist and a reliable source of knowledge in the ever-evolving world of technology.

variable assignment example

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 .

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • CBSE Class 11 Informatics Practices Syllabus 2023-24
  • CBSE Class 11 Information Practices Syllabus 2023-24 Distribution of Marks
  • CBSE Class 11 Informatics Practices Unit-wise Syllabus
  • Unit 1:Introduction to Computer System
  • Introduction to Computer System
  • Evolution of Computer
  • Computer Memory
  • Unit 2:Introduction to Python
  • Python Keywords
  • Identifiers
  • Expressions
  • Input and Output
  • if else Statements
  • Nested Loops
  • Working with Lists and Dictionaries
  • Introduction to List
  • List Operations
  • Traversing a List
  • List Methods and Built in Functions
  • Introduction to Dictionaries
  • Traversing a Dictionary
  • Dictionary Methods and Built-in Functions
  • Unit 3 Data Handling using NumPy
  • Introduction
  • NumPy Array
  • Indexing and Slicing
  • Operations on Arrays
  • Concatenating Arrays
  • Reshaping Arrays
  • Splitting Arrays
  • Saving NumPy Arrays in Files on Disk
  • Unit 4: Database Concepts and the Structured Query Language
  • Understanding Data
  • Introduction to Data
  • Data Collection
  • Data Storage
  • Data Processing
  • Statistical Techniques for Data Processing
  • Measures of Central Tendency
  • Database Concepts
  • Introduction to Structured Query Language
  • Structured Query Language
  • Data Types and Constraints in MySQL
  • CREATE Database
  • CREATE Table
  • DESCRIBE Table
  • ALTER Table
  • SQL for Data Manipulation
  • SQL for Data Query
  • Data Updation and Deletion
  • Unit 5 Introduction to Emerging Trends
  • Artificial Intelligence
  • Internet of Things
  • Cloud Computing
  • Grid Computing
  • Blockchains
  • Class 11 IP Syllabus Practical and Theory Components

Python Variables

Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program. In this article, we will see how to define a variable in Python .

Example of Variable in Python

An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s terms, we can say that Variable in Python is containers that store values.

Here we have stored “ Geeksforgeeks ”  in a variable var , and when we call its name the stored information will get printed.

Notes: The value stored in a variable can be changed during program execution. A Variables in Python is only a name given to a memory location, all the operations done on the variable effects that memory location.

Rules for Python variables

  • A Python variable name must start with a letter or the underscore character.
  • A Python variable name cannot start with a number.
  • A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).
  • The reserved words(keywords) in Python cannot be used to name the variable in Python.

Variables Assignment in Python

Here, we will define a variable in python. Here, clearly we have assigned a number, a floating point number, and a string to a variable such as age, salary, and name.

Declaration and Initialization of Variables

Let’s see how to declare a variable and how to define a variable and print the variable.

Redeclaring variables in Python

We can re-declare the Python variable once we have declared the variable and define variable in python already.

Python Assign Values to Multiple Variables 

Also, Python allows assigning a single value to several variables simultaneously with “=” operators.  For example: 

Assigning different values to multiple variables

Python allows adding different values in a single line with “,” operators.

Can We Use the S ame Name for Different Types?

If we use the same name, the variable starts referring to a new value and type.

How does + operator work with variables?  

The Python plus operator + provides a convenient way to add a value if it is a number and concatenate if it is a string. If a variable is already created it assigns the new value back to the same variable.

Can we use + for different Datatypes also?  

No use for different types would produce an error.

Global and Local Python Variables

Local variables in Python are the ones that are defined and declared inside a function. We can not call this variable outside the function.

Global variables in Python are the ones that are defined and declared outside a function, and we need to use them inside a function.

Global keyword in Python

Python global is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.

Rules of global keyword

  • If a variable is assigned a value anywhere within the function’s body, it’s assumed to be local unless explicitly declared as global.
  • Variables that are only referenced inside a function are implicitly global.
  • We use a global in Python to use a global variable inside a function.
  • There is no need to use a global keyword in Python outside a function.

Python program to modify a global value inside a function.

Variable Types in Python

Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instances (object) of these classes.

Built-in Python Data types are:

  • Sequence Type ( Python list , Python tuple , Python range )

In this example, we have shown different examples of Built-in data types in Python.

Object Reference in Python

Let us assign a variable x to value 5.

Object References

Another variable is y to the variable x.

Object References in Python

When Python looks at the first statement, what it does is that, first, it creates an object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference to this new object 5. The second line causes Python to create the variable y, and it is not assigned with x, rather it is made to reference that object that x does. The net effect is that the variables x and y wind up referencing the same object. This situation, with multiple names referencing the same object, is called a Shared Reference in Python. Now, if we write:

This statement makes a new object to represent ‘Geeks’ and makes x reference this new object.

Python Variable

Now if we assign the new value in Y, then the previous object refers to the garbage values.

Object References in Python

Creating objects (or variables of a class type)

Please refer to Class, Object, and Members for more details. 

Frequently Asked Questions

1. how to define a variable in python.

In Python, we can define a variable by assigning a value to a name. Variable names must start with a letter (a-z, A-Z) or an underscore (_) and can be followed by letters, underscores, or digits (0-9). Python is dynamically typed, meaning we don’t need to declare the variable type explicitly; it will be inferred based on the assigned value.

2. Are there naming conventions for Python variables?

Yes, Python follows the snake_case convention for variable names (e.g., my_variable ). They should start with a letter or underscore, followed by letters, underscores, or numbers. Constants are usually named in ALL_CAPS.

3. Can I change the type of a Python variable?

Yes, Python is dynamically typed, meaning you can change the type of a variable by assigning a new value of a different type. For instance:

Please Login to comment...

Similar reads.

  • python-basics
  • School Programming
  • What are Tiktok AI Avatars?
  • Poe Introduces A Price-per-message Revenue Model For AI Bot Creators
  • Truecaller For Web Now Available For Android Users In India
  • Google Introduces New AI-powered Vids App
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

variable assignment example

Hiring? Flexiple helps you build your dream team of  developers   and  designers .

How To Assign Values To Variables In Python?

Harsh Pandey

Harsh Pandey

Last updated on 16 Apr 2024

Assigning values in Python to variables is a fundamental and straightforward process. This action forms the basis for storing and manipulating Python data. The various methods for assigning values to variables in Python are given below.

Assign Values To Variables Direct Initialisation Method

Assigning values to variables in Python using the Direct Initialization Method involves a simple, single-line statement. This method is essential for efficiently setting up variables with initial values.

To use this method, you directly assign the desired value to a variable. The format follows variable_name = value . For instance, age = 21 assigns the integer 21 to the variable age.

This method is not just limited to integers. For example, assigning a string to a variable would be name = "Alice" . An example of this implementation in Python is.

Python Variables – Assign Multiple Values

In Python, assigning multiple values to variables can be done in a single, efficient line of code. This feature streamlines the initializing of several variables at once, making the code more concise and readable.

Python allows you to assign values to multiple variables simultaneously by separating each variable and value with commas. For example, x, y, z = 1, 2, 3 simultaneously assigns 1 to x, 2 to y, and 3 to z.

Additionally, Python supports unpacking a collection of values into variables. For example, if you have a list values = [1, 2, 3] , you can assign these values to a, b, c by writing a, b, c = values .

Python’s capability to assign multiple values to multiple variables in a single line enhances code efficiency and clarity. This feature is applicable across various data types and includes unpacking collections into multiple variables, as shown in the examples.

Assign Values To Variables Using Conditional Operator

Assigning values to variables in Python using a conditional operator allows for more dynamic and flexible value assignments based on certain conditions. This method employs the ternary operator, a concise way to assign values based on a condition's truth value.

The syntax for using the conditional operator in Python follows the pattern: variable = value_if_true if condition else value_if_false . For example, status = 'Adult' if age >= 18 else 'Minor' assigns 'Adult' to status if age is 18 or more, and 'Minor' otherwise.

This method can also be used with more complex conditions and various data types. For example, you can assign different strings to a variable based on a numerical comparison

Using the conditional operator for variable assignment in Python enables more nuanced and condition-dependent variable initialization. It is particularly useful for creating readable one-liners that eliminate the need for longer if-else statements, as illustrated in the examples.

Python One Liner Conditional Statement Assigning

Python allows for one-liner conditional statements to assign values to variables, providing a compact and efficient way of handling conditional assignments. This approach utilizes the ternary operator for conditional expressions in a single line of code.

The ternary operator syntax in Python is variable = value_if_true if condition else value_if_false . For instance, message = 'High' if temperature > 20 else 'Low' assigns 'High' to message if temperature is greater than 20, and 'Low' otherwise.

This method can also be applied to more complex conditions.

Using one-liner conditional statements in Python for variable assignment streamlines the process, especially when dealing with simple conditions. It replaces the need for multi-line if-else statements, making the code more concise and readable.

Work with top startups & companies. Get paid on time.

Try a top quality developer for 7 days. pay only if satisfied..

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

  • Ruby on Rails
  • Elasticsearch
  • Google Cloud
  • React Native
  • Contact Details
  • 2093, Philadelphia Pike, DE 19703, Claymont
  • [email protected]
  • Explore jobs
  • We are Hiring!
  • Write for us
  • 2093, Philadelphia Pike DE 19703, Claymont

Copyright @ 2024 Flexiple Inc

CS105: Introduction to Python

Variables and assignment statements.

Computers must be able to remember and store data. This can be accomplished by creating a variable to house a given value. The assignment operator = is used to associate a variable name with a given value. For example, type the command:

in the command line window. This command assigns the value 3.45 to the variable named a . Next, type the command:

in the command window and hit the enter key. You should see the value contained in the variable a echoed to the screen. This variable will remember the value 3.45 until it is assigned a different value. To see this, type these two commands:

You should see the new value contained in the variable a echoed to the screen. The new value has "overwritten" the old value. We must be careful since once an old value has been overwritten, it is no longer remembered. The new value is now what is being remembered.

Although we will not discuss arithmetic operations in detail until the next unit, you can at least be equipped with the syntax for basic operations: + (addition), - (subtraction), * (multiplication), / (division)

For example, entering these command sequentially into the command line window:

would result in 12.32 being echoed to the screen (just as you would expect from a calculator). The syntax for multiplication works similarly. For example:

would result in 35 being echoed to the screen because the variable b has been assigned the value a * 5 where, at the time of execution, the variable a contains a value of 7.

After you read, you should be able to execute simple assignment commands using integer and float values in the command window of the Repl.it IDE. Try typing some more of the examples from this web page to convince yourself that a variable has been assigned a specific value.

In programming, we associate names with values so that we can remember and use them later. Recall Example 1. The repeated computation in that algorithm relied on remembering the intermediate sum and the integer to be added to that sum to get the new sum. In expressing the algorithm, we used th e names current and sum .

In programming, a name that refers to a value in this fashion is called a variable . When we think of values as data stored somewhere i n the computer, we can have a mental image such as the one below for the value 10 stored in the computer and the variable x , which is the name we give to 10. What is most important is to see that there is a binding between x and 10.

The term variable comes from the fact that values that are bound to variables can change throughout computation. Bindings as shown above are created, and changed by assignment statements . An assignment statement associates the name to the left of the symbol = with the value denoted by the expression on the right of =. The binding in the picture is created using an assignment statemen t of the form x = 10 . We usually read such an assignment statement as "10 is assigned to x" or "x is set to 10".

If we want to change the value that x refers to, we can use another assignment statement to do that. Suppose we execute x = 25 in the state where x is bound to 10.Then our image becomes as follows:

Choosing variable names

Suppose that we u sed the variables x and y in place of the variables side and area in the examples above. Now, if we were to compute some other value for the square that depends on the length of the side , such as the perimeter or length of the diagonal, we would have to remember which of x and y , referred to the length of the side because x and y are not as descriptive as side and area . In choosing variable names, we have to keep in mind that programs are read and maintained by human beings, not only executed by machines.

Note about syntax

In Python, variable identifiers can contain uppercase and lowercase letters, digits (provided they don't start with a digit) and the special character _ (underscore). Although it is legal to use uppercase letters in variable identifiers, we typically do not use them by convention. Variable identifiers are also case-sensitive. For example, side and Side are two different variable identifiers.

There is a collection of words, called reserved words (also known as keywords), in Python that have built-in meanings and therefore cannot be used as variable names. For the list of Python's keywords See 2.3.1 of the Python Language Reference.

Syntax and Sema ntic Errors

Now that we know how to write arithmetic expressions and assignment statements in Python, we can pause and think about what Python does if we write something that the Python interpreter cannot interpret. Python informs us about such problems by giving an error message. Broadly speaking there are two categories for Python errors:

  • Syntax errors: These occur when we write Python expressions or statements that are not well-formed according to Python's syntax. For example, if we attempt to write an assignment statement such as 13 = age , Python gives a syntax error. This is because Python syntax says that for an assignment statement to be well-formed it must contain a variable on the left hand side (LHS) of the assignment operator "=" and a well-formed expression on the right hand side (RHS), and 13 is not a variable.
  • Semantic errors: These occur when the Python interpreter cannot evaluate expressions or execute statements because they cannot be associated with a "meaning" that the interpreter can use. For example, the expression age + 1 is well-formed but it has a meaning only when age is already bound to a value. If we attempt to evaluate this expression before age is bound to some value by a prior assignment then Python gives a semantic error.

Even though we have used numerical expressions in all of our examples so far, assignments are not confined to numerical types. They could involve expressions built from any defined type. Recall the table that summarizes the basic types in Python.

The following video shows execution of assignment statements involving strings. It also introduces some commonly used operators on strings. For more information see the online documentation. In the video below, you see the Python shell displaying "=> None" after the assignment statements. This is unique to the Python shell presented in the video. In most Python programming environments, nothing is displayed after an assignment statement. The difference in behavior stems from version differences between the programming environment used in the video and in the activities, and can be safely ignored.

Distinguishing Expressions and Assignments

So far in the module, we have been careful to keep the distinction between the terms expression and statement because there is a conceptual difference between them, which is sometimes overlooked. Expressions denote values; they are evaluated to yield a value. On the other hand, statements are commands (instructions) that change the state of the computer. You can think of state here as some representation of computer memory and the binding of variables and values in the memory. In a state where the variable side is bound to the integer 3, and the variable area is yet unbound, the value of the expression side + 2 is 5. The assignment statement side = side + 2 , changes the state so that value 5 is bound to side in the new state. Note that when you type an expression in the Python shell, Python evaluates the expression and you get a value in return. On the other hand, if you type an assignment statement nothing is returned. Assignment statements do not return a value. Try, for example, typing x = 100 + 50 . Python adds 100 to 50, gets the value 150, and binds x to 150. However, we only see the prompt >>> after Python does the assignment. We don't see the change in the state until we inspect the value of x , by invoking x .

What we have learned so far can be summarized as using the Python interpreter to manipulate values of some primitive data types such as integers, real numbers, and character strings by evaluating expressions that involve built-in operators on these types. Assignments statements let us name the values that appear in expressions. While what we have learned so far allows us to do some computations conveniently, they are limited in their generality and reusability. Next, we introduce functions as a means to make computations more general and reusable.

Creative Commons License

11 Variables and assignment

11.1  let, 11.2.1  const and immutability, 11.2.2  const and loops.

  • 11.3  Deciding between const and let
  • 11.4.1  Shadowing variables
  • 11.5  (Advanced)
  • 11.6.1  Static phenomenon: scopes of variables
  • 11.6.2  Dynamic phenomenon: function calls

11.7.1  globalThis [ES2020]

11.8.1  const and let : temporal dead zone.

  • 11.8.2  Function declarations and early activation
  • 11.8.3  Class declarations are not activated early

11.8.4  var : hoisting (partial early activation)

  • 11.9.1  Bound variables vs. free variables
  • 11.9.2  What is a closure?
  • 11.9.3  Example: A factory for incrementors
  • 11.9.4  Use cases for closures

These are JavaScript’s main ways of declaring variables:

  • let declares mutable variables.
  • const declares constants (immutable variables).

Before ES6, there was also var . But it has several quirks, so it’s best to avoid it in modern JavaScript. You can read more about it in Speaking JavaScript .

Variables declared via let are mutable:

You can also declare and assign at the same time:

11.2  const

Variables declared via const are immutable. You must always initialize immediately:

In JavaScript, const only means that the binding (the association between variable name and variable value) is immutable. The value itself may be mutable, like obj in the following example.

You can use const with for-of loops, where a fresh binding is created for each iteration:

In plain for loops, you must use let , however:

11.3 Deciding between const and let

I recommend the following rules to decide between const and let :

  • const indicates an immutable binding and that a variable never changes its value. Prefer it.
  • let indicates that the value of a variable changes. Use it only when you can’t use const .

exercises/variables-assignment/const_exrc.mjs

11.4 The scope of a variable

The scope of a variable is the region of a program where it can be accessed. Consider the following code.

  • Scope A is the (direct) scope of x .
  • Scopes B and C are inner scopes of scope A.
  • Scope A is an outer scope of scope B and scope C.

Each variable is accessible in its direct scope and all scopes nested within that scope.

The variables declared via const and let are called block-scoped because their scopes are always the innermost surrounding blocks.

11.4.1 Shadowing variables

You can’t declare the same variable twice at the same level:

eval() delays parsing (and therefore the SyntaxError ), until the callback of assert.throws() is executed. If we didn’t use it, we’d already get an error when this code is parsed and assert.throws() wouldn’t even be executed.

You can, however, nest a block and use the same variable name x that you used outside the block:

Inside the block, the inner x is the only accessible variable with that name. The inner x is said to shadow the outer x . Once you leave the block, you can access the old value again.

See quiz app .

11.5 (Advanced)

All remaining sections are advanced.

11.6 Terminology: static vs. dynamic

These two adjectives describe phenomena in programming languages:

  • Static means that something is related to source code and can be determined without executing code.
  • Dynamic means at runtime.

Let’s look at examples for these two terms.

11.6.1 Static phenomenon: scopes of variables

Variable scopes are a static phenomenon. Consider the following code:

x is statically (or lexically ) scoped . That is, its scope is fixed and doesn’t change at runtime.

Variable scopes form a static tree (via static nesting).

11.6.2 Dynamic phenomenon: function calls

Function calls are a dynamic phenomenon. Consider the following code:

Whether or not the function call in line A happens, can only be decided at runtime.

Function calls form a dynamic tree (via dynamic calls).

11.7 Global variables and the global object

JavaScript’s variable scopes are nested. They form a tree:

  • The outermost scope is the root of the tree.
  • The scopes directly contained in that scope are the children of the root.

The root is also called the global scope . In web browsers, the only location where one is directly in that scope is at the top level of a script. The variables of the global scope are called global variables and accessible everywhere. There are two kinds of global variables:

  • They can only be created while at the top level of a script, via const , let , and class declarations.
  • They are created in the top level of a script, via var and function declarations.
  • The global object can be accessed via the global variable globalThis . It can be used to create, read, and delete global object variables.
  • Other than that, global object variables work like normal variables.

The following HTML fragment demonstrates globalThis and the two kinds of global variables.

Each ECMAScript module has its own scope. Therefore, variables that exist at the top level of a module are not global. Fig.  5 illustrates how the various scopes are related.

The global variable globalThis is the new standard way of accessing the global object. It got its name from the fact that it has the same value as this in global scope.

For example, in browsers, there is an indirection . That indirection is normally not noticable, but it is there and can be observed.

11.7.1.1 Alternatives to globalThis

Older ways of accessing the global object depend on the platform:

  • Global variable window : is the classic way of referring to the global object. But it doesn’t work in Node.js and in Web Workers.
  • Global variable self : is available in Web Workers and browsers in general. But it isn’t supported by Node.js.
  • Global variable global : is only available in Node.js.

11.7.1.2 Use cases for globalThis

The global object is now considered a mistake that JavaScript can’t get rid of, due to backward compatibility. It affects performance negatively and is generally confusing.

ECMAScript 6 introduced several features that make it easier to avoid the global object – for example:

  • const , let , and class declarations don’t create global object properties when used in global scope.
  • Each ECMAScript module has its own local scope.

It is usually better to access global object variables via variables and not via properties of globalThis . The former has always worked the same on all JavaScript platforms.

Tutorials on the web occasionally access global variables globVar via window.globVar . But the prefix “ window. ” is not necessary and I recommend to omit it:

Therefore, there are relatively few use cases for globalThis – for example:

  • Polyfills that add new features to old JavaScript engines.
  • Feature detection, to find out what features a JavaScript engine supports.

11.8 Declarations: scope and activation

These are two key aspects of declarations:

  • Scope: Where can a declared entity be seen? This is a static trait.
  • Activation: When can I access an entity? This is a dynamic trait. Some entities can be accessed as soon as we enter their scopes. For others, we have to wait until execution reaches their declarations.

Tbl.  1 summarizes how various declarations handle these aspects.

import is described in §27.5 “ECMAScript modules” . The following sections describe the other constructs in more detail.

For JavaScript, TC39 needed to decide what happens if you access a constant in its direct scope, before its declaration:

Some possible approaches are:

  • The name is resolved in the scope surrounding the current scope.
  • You get undefined .
  • There is an error.

Approach 1 was rejected because there is no precedent in the language for this approach. It would therefore not be intuitive to JavaScript programmers.

Approach 2 was rejected because then x wouldn’t be a constant – it would have different values before and after its declaration.

let uses the same approach 3 as const , so that both work similarly and it’s easy to switch between them.

The time between entering the scope of a variable and executing its declaration is called the temporal dead zone (TDZ) of that variable:

  • During this time, the variable is considered to be uninitialized (as if that were a special value it has).
  • If you access an uninitialized variable, you get a ReferenceError .
  • Once you reach a variable declaration, the variable is set to either the value of the initializer (specified via the assignment symbol) or undefined – if there is no initializer.

The following code illustrates the temporal dead zone:

The next example shows that the temporal dead zone is truly temporal (related to time):

Even though func() is located before the declaration of myVar and uses that variable, we can call func() . But we have to wait until the temporal dead zone of myVar is over.

11.8.2 Function declarations and early activation

In this section, we are using functions – before we had a chance to learn them properly. Hopefully, everything still makes sense. Whenever it doesn’t, please see §25 “Callable values” .

A function declaration is always executed when entering its scope, regardless of where it is located within that scope. That enables you to call a function foo() before it is declared:

The early activation of foo() means that the previous code is equivalent to:

If you declare a function via const or let , then it is not activated early. In the following example, you can only use bar() after its declaration.

11.8.2.1 Calling ahead without early activation

Even if a function g() is not activated early, it can be called by a preceding function f() (in the same scope) if we adhere to the following rule: f() must be invoked after the declaration of g() .

The functions of a module are usually invoked after its complete body is executed. Therefore, in modules, you rarely need to worry about the order of functions.

Lastly, note how early activation automatically keeps the aforementioned rule: when entering a scope, all function declarations are executed first, before any calls are made.

11.8.2.2 A pitfall of early activation

If you rely on early activation to call a function before its declaration, then you need to be careful that it doesn’t access data that isn’t activated early.

The problem goes away if you make the call to funcDecl() after the declaration of MY_STR .

11.8.2.3 The pros and cons of early activation

We have seen that early activation has a pitfall and that you can get most of its benefits without using it. Therefore, it is better to avoid early activation. But I don’t feel strongly about this and, as mentioned before, often use function declarations because I like their syntax.

11.8.3 Class declarations are not activated early

Even though they are similar to function declarations in some ways, class declarations are not activated early:

Why is that? Consider the following class declaration:

The operand of extends is an expression. Therefore, you can do things like this:

Evaluating such an expression must be done at the location where it is mentioned. Anything else would be confusing. That explains why class declarations are not activated early.

var is an older way of declaring variables that predates const and let (which are preferred now). Consider the following var declaration.

This declaration has two parts:

  • Declaration var x : The scope of a var -declared variable is the innermost surrounding function and not the innermost surrounding block, as for most other declarations. Such a variable is already active at the beginning of its scope and initialized with undefined .
  • Assignment x = 123 : The assignment is always executed in place.

The following code demonstrates the effects of var :

11.9 Closures

Before we can explore closures, we need to learn about bound variables and free variables.

11.9.1 Bound variables vs. free variables

Per scope, there is a set of variables that are mentioned. Among these variables we distinguish:

  • Bound variables are declared within the scope. They are parameters and local variables.
  • Free variables are declared externally. They are also called non-local variables .

Consider the following code:

In the body of func() , x and y are bound variables. z is a free variable.

11.9.2 What is a closure?

What is a closure then?

A closure is a function plus a connection to the variables that exist at its “birth place”.

What is the point of keeping this connection? It provides the values for the free variables of the function – for example:

funcFactory returns a closure that is assigned to func . Because func has the connection to the variables at its birth place, it can still access the free variable value when it is called in line A (even though it “escaped” its scope).

Static scoping is supported via closures in JavaScript. Therefore, every function is a closure.

11.9.3 Example: A factory for incrementors

The following function returns incrementors (a name that I just made up). An incrementor is a function that internally stores a number. When it is called, it updates that number by adding the argument to it and returns the new value.

We can see that the function created in line A keeps its internal number in the free variable startValue . This time, we don’t just read from the birth scope, we use it to store data that we change and that persists across function calls.

We can create more storage slots in the birth scope, via local variables:

11.9.4 Use cases for closures

What are closures good for?

For starters, they are simply an implementation of static scoping. As such, they provide context data for callbacks.

They can also be used by functions to store state that persists across function calls. createInc() is an example of that.

And they can provide private data for objects (produced via literals or classes). The details of how that works are explained in Exploring ES6 .

  • bash / FAQ / Shell Scripting

Bash variable assignment examples

by Ramakanta · Published January 19, 2013 · Updated February 11, 2015

Tutorials

This section we will describe the following: 1. Variable assignment 2. Variable substitution 3. Built-in shell variables 4. Other shell variables 5. Variable Assignment

Variable names consist of any number of letters, digits, or underscores. Upper- and lowercase letters are distinct, and names may not start with a digit.

Variables are assigned values using the = operator. There may not be any whitespace between the variable name and the value. You can make multiple assignments on the same line by separating each one with whitespace:

By convention, names for variables used or set by the shell have all uppercase letters; however, you can use uppercase names in your scripts if you use a name that isn’t special to the shell. By default, the shell treats variable values as strings, even if the value of the string is all digits. However, when a value is assigned to an integer variable (created via declare -i), Bash evaluates the righthand side of the assignment as an expression.

For example:

The += operator allows you to add or append the righthand side of the assignment to an existing value. Integer variables treat the righthand side as an expression, which is evaluated and added to the value. Arrays add the new elements to the array.

Variable Substitution

No spaces should be used in the following expressions. The colon (:) is optional; if it’s included, var must be nonnull as well as set.

var=value … Set each variable var to a value.

${var} Use value of var; braces are optional if var is separated from the following text. They are required for array variables.

${var:-value} Use var if set; otherwise, use value.

${var:=value} Use var if set; otherwise, use value and assign value to var.

${var:?value} Use var if set; otherwise, print value and exit (if not interactive). If value isn’t supplied, print the phrase parameter null or not set.

${var:+value} Use value if var is set; otherwise, use nothing.

${#var} Use the length of var.

${#*} Use the number of positional parameters.

${#@} Same as previous.

${var#pattern} Use value of var after removing text matching pattern from the left. Remove the shortest matching piece.

${var##pattern} Same as #pattern, but remove the longest matching piece.

${var%pattern} Use value of var after removing text matching pattern from the right. Remove the shortest matching piece.

${var%%pattern} Same as %pattern, but remove the longest matching piece.

${var^pattern} Convert the case of var to uppercase. The pattern is evaluated as for filename matching. If the first letter of var matches the pattern, it is converted to uppercase. var can be * or @, in which case the positional parameters are modified. var can also be an array subscripted by * or @, in which case the substitution is applied to all the elements of the array.

${var^^pattern} Same as ^pattern, but apply the match to every letter in the string.

${var,pattern} Same as ^pattern, but convert matching characters to lower case. Applies only to the first character in the string.

${var,,pattern} Same as ,pattern, but apply the match to every letter in the string.

${!prefix*},${!prefix@} List of variables whose names begin with prefix.

${var:pos},${var:pos:len} Starting at position pos (0-based) in variable var, extract len characters, or extract rest of string if no len. pos and len may be arithmetic expressions.When var is * or @, the expansion is performed upon the positional parameters. If pos is zero, then $0 is included in the resulting list. Similarly, var can be an array indexed by * or @.

${var/pat/repl} Use value of var, with first match of pat replaced with repl.

${var/pat} Use value of var, with first match of pat deleted.

${var//pat/repl} Use value of var, with every match of pat replaced with repl.

${var/#pat/repl} Use value of var, with match of pat replaced with repl. Match must occur at beginning of the value.

${var/%pat/repl} Use value of var, with match of pat replaced with repl. Match must occur at end of the value.

${!var} Use value of var as name of variable whose value should be used (indirect reference).

Bash provides a special syntax that lets one variable indirectly reference another:

$ greet=”hello, world” Create initial variable

$ friendly_message=greet Aliasing variable

$ echo ${!friendly_message} Use the alias

hello, world Example:

Built-in Shell Variables

Built-in variables are automatically set by the shell and are typically used inside shell scripts. Built-in variables can make use of the variable substitution patterns shown previously. Note that the $ is not actually part of the variable name, although the variable is always referenced this way. The following are

available in any Bourne-compatible shell:

$# Number of command-line arguments.

$- Options currently in effect (supplied on command line or to set). The shell sets some options automatically.

$? Exit value of last executed command.

$$ Process number of the shell.

$! Process number of last background command.

$0 First word; that is, the command name. This will have the full pathname if it was found via a PATH search.

$n Individual arguments on command line (positional parameters).

The Bourne shell allows only nine parameters to be referenced directly (n = 1–9); Bash allows n to be greater than 9 if specified as ${n}.

$*, $@ All arguments on command line ($1 $2 …).

“$*” All arguments on command line as one string (“$1 $2…”). The values are separated by the first character in $IFS.

“$@” All arguments on command line, individually quoted (“$1” “$2” …). Bash automatically sets the following additional variables: $_ Temporary variable; initialized to pathname of script or program being executed. Later, stores the last argument of previous command. Also stores name of matching MAIL file during mail checks.

BASH The full pathname used to invoke this instance of Bash.

BASHOPTS A read-only, colon-separated list of shell options that are currently enabled. Each item in the list is a valid option for shopt -s. If this variable exists in the environment when Bash starts up, it sets the indicated options before executing any startup files.

BASHPID The process ID of the current Bash process. In some cases, this can differ from $$.

BASH_ALIASES Associative array variable. Each element holds an alias defined with the alias command. Adding an element to this array creates a new alias; removing an element removes the corresponding alias.

BASH_ARGC Array variable. Each element holds the number of arguments for the corresponding function or dot-script invocation. Set only in extended debug mode, with shopt –s extdebug. Cannot be unset.

BASH_ARGV An array variable similar to BASH_ARGC. Each element is one of the arguments passed to a function or dot-script. It functions as a stack, with values being pushed on at each call. Thus, the last element is the last argument to the most recent function or script invocation. Set only in extended debug

mode, with shopt -s extdebug. Cannot be unset.

BASH_CMDS Associative array variable. Each element refers to a command in the internal hash table maintained by the hash command. The index is the command name and the value is the full path to the command. Adding an element to this array adds a command to the hash table; removing an element removes the corresponding entry.

BASH_COMMAND The command currently executing or about to be executed. Inside a trap handler, it is the command running when the trap was invoked.

BASH_EXECUTION_STRING The string argument passed to the –c option.

BASH_LINENO Array variable, corresponding to BASH_SOURCE and FUNCNAME. For any given function number i (starting at zero), ${FUNCNAME[i]} was invoked in file ${BASH_SOURCE[i]} on line ${BASH_LINENO[i]}. The information is stored with the most recent function invocation first. Cannot be unset.

BASH_REMATCH Array variable, assigned by the =~ operator of the [[ ]] construct. Index zero is the text that matched the entire pattern. The other

indices are the text matched by parenthesized subexpressions. This variable is read-only.

BASH_SOURCE Array variable, containing source filenames. Each element corresponds to those in FUNCNAME and BASH_LINENO. Cannot be unset.

BASH_SUBSHELL This variable is incremented by one each time a subshell or subshell environment is created.

BASH_VERSINFO[0] The major version number, or release, of Bash.

BASH_VERSINFO[1] The minor version number, or version, of Bash.

BASH_VERSINFO[2] The patch level.

BASH_VERSINFO[3] The build version.

BASH_VERSINFO[4] The release status.

BASH_VERSINFO[5] The machine type; same value as in $MACHTYPE.

BASH_VERSION A string describing the version of Bash.

COMP_CWORD For programmable completion. Index into COMP_WORDS, indicating the current cursor position.

COMP_KEY For programmable completion. The key, or final key in a sequence, that caused the invocation of the current completion function.

COMP_LINE For programmable completion. The current command line.

COMP_POINT For programmable completion. The position of the cursor as a character index in $COMP_LINE.

COMP_TYPE For programmable completion. A character describing the type of programmable completion. The character is one of Tab for normal completion, ? for a completions list after two Tabs, ! for the list of alternatives on partial word completion, @ for completions if the word is modified, or % for menu completion.

COMP_WORDBREAKS For programmable completion. The characters that the readline library treats as word separators when doing word completion.

COMP_WORDS For programmable completion. Array variable containing the individual words on the command line.

COPROC Array variable that holds the file descriptors used for communicating with an unnamed coprocess.

DIRSTACK Array variable, containing the contents of the directory stack as displayed by dirs. Changing existing elements modifies the stack, but only pushd and popd can add or remove elements from the stack.

EUID Read-only variable with the numeric effective UID of the current user.

FUNCNAME Array variable, containing function names. Each element corresponds to those in BASH_SOURCE and BASH_LINENO.

GROUPS Array variable, containing the list of numeric group IDs in which the current user is a member.

HISTCMD The history number of the current command.

HOSTNAME The name of the current host.

HOSTTYPE A string that describes the host system.

LINENO Current line number within the script or function.

MACHTYPE A string that describes the host system in the GNU cpu-company-system format.

MAPFILE Default array for the mapfile and readarray commands.

OLDPWD Previous working directory (set by cd).

OPTARG Value of argument to last option processed by getopts.

OPTIND Numerical index of OPTARG.

OSTYPE A string that describes the operating system.

PIPESTATUS Array variable, containing the exit statuses of the commands in the most recent foreground pipeline.

PPID Process number of this shell’s parent.

PWD Current working directory (set by cd).

RANDOM[=n] Generate a new random number with each reference; start with integer n, if given.

READLINE_LINE For use with bind -x. The contents of the editing buffer are available in this variable.

READLINE_POINT For use with bind -x. The index in $READLINE_LINE of the insertion point.

REPLY Default reply; used by select and read.

SECONDS[=n] Number of seconds since the shell was started, or, if n is given, number of seconds since the assignment + n.

SHELLOPTS A read-only, colon-separated list of shell options (for set -o). If set in the environment at startup, Bash enables each option present in the list before reading any startup files.

SHLVL Incremented by one every time a new Bash starts up.

UID Read-only variable with the numeric real UID of the current user.

Other Shell Variables

The following variables are not automatically set by the shell, although many of them can influence the shell’s behavior. You typically use them in your .bash_profile or .profile file, where you can define them to suit your needs. Variables can be assigned values by issuing commands of the form:

This list includes the type of value expected when defining these variables:

BASH_ENV If set at startup, names a file to be processed for initialization commands. The value undergoes parameter expansion, command substitution, and arithmetic expansion before being interpreted as a filename.

BASH_XTRACEFD=n File descriptor to which Bash writes trace output (from set -x).

CDPATH=dirs Directories searched by cd; allows shortcuts in changing directories; unset by default.

COLUMNS=n Screen’s column width; used in line edit modes and select lists.

COMPREPLY=(words …) Array variable from which Bash reads the possible completions generated by a completion function.

EMACS If the value starts with t, Bash assumes it’s running in an Emacs buffer and disables line editing.

ENV=file Name of script that is executed at startup in POSIX mode or when Bash is invoked as /bin/sh; useful for storing alias and function definitions. For example, ENV=$HOME/.shellrc.

FCEDIT=file Editor used by fc command. The default is /bin/ed when Bash is in POSIX mode. Otherwise, the default is $EDITOR if set, vi if unset.

FIGNORE=patlist Colon-separated list of patterns describing the set of filenames to ignore when doing filename completion.

GLOBIGNORE=patlist Colon-separated list of patterns describing the set of filenames to ignore during pattern matching.

HISTCONTROL=list Colon-separated list of values controlling how commands are saved in the history file. Recognized values are ignoredups, ignorespace, ignoreboth, and erasedups.

HISTFILE=file File in which to store command history.

HISTFILESIZE=n Number of lines to be kept in the history file. This may be different from the number of commands.

HISTIGNORE=list A colon-separated list of patterns that must match the entire command line. Matching lines are not saved in the history file. An unescaped & in a pattern matches the previous history line.

HISTSIZE=n Number of history commands to be kept in the history file.

HISTTIMEFORMAT=string A format string for strftime(3) to use for printing timestamps along with commands from the history command. If set (even if null), Bash saves timestamps in the history file along with the commands.

HOME=dir Home directory; set by login (from /etc/passwd file).

HOSTFILE=file Name of a file in the same format as /etc/hosts that Bash should use to find hostnames for hostname completion.

IFS=’chars’ Input field separators; default is space, Tab, and newline.

IGNOREEOF=n Numeric value indicating how many successive EOF characters must be typed before Bash exits. If null or nonnumeric value, default is 10.

INPUTRC=file Initialization file for the readline library. This overrides the default value of ~/.inputrc.

LANG=locale Default value for locale; used if no LC_* variables are set.

LC_ALL=locale Current locale; overrides LANG and the other LC_* variables.

LC_COLLATE=locale Locale to use for character collation (sorting order).

LC_CTYPE=locale Locale to use for character class functions.

LC_MESSAGES=locale Locale to use for translating $”…” strings.

LC_NUMERIC=locale Locale to use for the decimal-point character.

LC_TIME=locale Locale to use for date and time formats.

LINES=n Screen’s height; used for select lists.

MAIL=file Default file to check for incoming mail; set by login.

MAILCHECK=n Number of seconds between mail checks; default is 600 (10 minutes).

MAILPATH=files One or more files, delimited by a colon, to check for incoming mail. Along with each file, you may supply an optional message that the shell prints when the file increases in size. Messages are separated from the filename by a ? character, and the default message is You have mail in $_. $_ is replaced with the name of the file. For example, you might have MAIL PATH=”$MAIL?Candygram!:/etc/motd?New Login Message” OPTERR=n When set to 1 (the default value), Bash prints error messages from the built-in getopts command.

PATH=dirlist One or more pathnames, delimited by colons, in which to search for commands to execute. The default for many systems is /bin:/usr/bin. On Solaris, the default is /usr/bin:. However, the standard startup scripts change it to /usr/bin:/usr/ucb:/etc:.

POSIXLY_CORRECT=string When set at startup or while running, Bash enters POSIX mode, disabling behavior and modifying features that conflict with the POSIX standard.

PROMPT_COMMAND=command If set, Bash executes this command each time before printing the primary prompt.

PROMPT_DIRTRIM=n Indicates how many trailing directory components to retain for the \w or \W special prompt strings. Elided components are replaced with an ellipsis.

PS1=string Primary prompt string; default is $.

PS2=string Secondary prompt (used in multiline commands); default is >.

PS3=string Prompt string in select loops; default is #?.

PS4=string Prompt string for execution trace (bash –x or set -x); default is +.

SHELL=file Name of user’s default shell (e.g., /bin/sh). Bash sets this if it’s not in the environment at startup.

TERM=string Terminal type.

TIMEFORMAT=string A format string for the output from the time keyword.

TMOUT=n If no command is typed after n seconds, exit the shell. Also affects the read command and the select loop.

TMPDIR=directory Place temporary files created and used by the shell in directory.

auto_resume=list Enables the use of simple strings for resuming stopped jobs. With a value of exact, the string must match a command name exactly. With a value of substring, it can match a substring of the command name.

histchars=chars Two or three characters that control Bash’s csh-style history expansion. The first character signals a history event, the second is the “quick substitution” character, and the third indicates the start of a comment. The default value is !^#.

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Like the article... Share it.

  • Click to print (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Telegram (Opens in new window)

CURRENTLY TRENDING...

Tags: bash variable

  • Next story  Grep Command Tutorial For Unix
  • Previous story  Bash redirect to file and screen

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Sign Up For Our Free Email Newsletter    

IMAGES

  1. Variable Assignment in Python

    variable assignment example

  2. Learn Python Programming Tutorial 4

    variable assignment example

  3. PPT

    variable assignment example

  4. PPT

    variable assignment example

  5. Variable assignment, Comments and print function -Python Programming Tutorial 5

    variable assignment example

  6. PPT

    variable assignment example

VIDEO

  1. Assignment Statement and Constant Variable

  2. 6 storing values in variable, assignment statement

  3. [Algorithm Session 01]

  4. Class-23, For loop introduction 🔴Live

  5. C++ Variables, Literals, an Assignment Statements [2]

  6. Python Variables Assignment

COMMENTS

  1. 1.4

    1.4 — Variable assignment and initialization. Alex March 22, 2024. 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 ...

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

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

    Declare And Assign Value To Variable. 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.

  4. Variables in Python

    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 .". Once this is done, n can be used in a statement or expression, and its value will be substituted: Python.

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

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

  7. Programming with variables

    Assigning variables. Here's how we create a variable named score in JavaScript: var score = 0; That line of code is called a statement. All programs are made up of statements, and each statement is an instruction to the computer about something we need it to do. Let's add the lives variable: var score = 0; var lives = 3;

  8. Variables, Assignment, Types and Arithmetic

    Variables in python. The purpose of a variable is to store information within a program while it is running.; A variable is a named storage location in computer memory. Use the name to access the value. To store a value in a variable, use the = operator (called the assignment operator).; An = sign in Python is nothing like an equal sign in mathematics. Think of it more like an arrow going from ...

  9. Python Variables and Assignment

    Python Variables and Assignment Python Variables. A Python variable is a named bit of computer memory, keeping track of a value as the code runs. ... The string 'hello' in the example above is shown in gray. It is not needed by the code after the third line runs — no variable points to it any longer, so it cannot be used. Memory like this ...

  10. Python Variables

    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: x = 5. From this point forward, whenever x is referenced in the code, it will have the value 5.

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

  12. How To Use Assignment Expressions in Python

    For example, assignment expressions using the := syntax allow variables to be assigned inside of if statements, which can often produce shorter and more compact sections of Python code by eliminating variable assignments in lines preceding or following the if statement.

  13. Programming

    Assignment means: "storing a value (of a particular type) under a variable name". Think of each assignment as copying the value of the righthand side of the expression into a "bucket" associated with the left hand side name! Read this as, the variable called "name" is "assigned" the value computed by the expression to the right of the ...

  14. A Guide to Variable Assignment and Mutation in JavaScript

    In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand ...

  15. 5 Best Ways to Declare a Variable in Python

    Method 1: Basic Variable Assignment. This is the most straightforward method for creating and assigning a variable in Python. You simply declare a variable by typing its name, followed by an equals sign, and the value you wish to assign to it. This method is readable, writable, and often used for its simplicity. Here's an example: score = 10 ...

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

  17. Python Variables

    An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name. ... Variables Assignment in Python. Here, we will define a variable in python. Here, clearly we have assigned a number, a floating point number, and a string to a ...

  18. How To Assign Values To Variables In Python?

    Additionally, Python supports unpacking a collection of values into variables. For example, if you have a list values = [1, 2, 3], you can assign these values to a, b, c by writing a, b, c = values. ... Using one-liner conditional statements in Python for variable assignment streamlines the process, especially when dealing with simple ...

  19. CS105: Variables and Assignment Statements

    The assignment operator = is used to associate a variable name with a given value. For example, type the command: a=3.45. in the command line window. This command assigns the value 3.45 to the variable named a. Next, type the command: a. in the command window and hit the enter key. You should see the value contained in the variable a echoed to ...

  20. Assignment Expressions: The Walrus Operator

    In this lesson, you'll learn about the biggest change in Python 3.8: the introduction of assignment expressions.Assignment expression are written with a new notation (:=).This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side.. Assignment expressions allow you to assign and return a value in the same expression.

  21. Variable Assignment

    Variable Assignment. the assignment operator ( no space before and after) Do not confuse this with = and -eq, which test , rather than assign! Note that = can be either an assignment or a test operator, depending on context. Example 4-2. Plain Variable Assignment. #!/bin/bash. # Naked variables. echo.

  22. 11 Variables and assignment

    Scope A is the (direct) scope of x.; Scopes B and C are inner scopes of scope A.; Scope A is an outer scope of scope B and scope C.; Each variable is accessible in its direct scope and all scopes nested within that scope. The variables declared via const and let are called block-scoped because their scopes are always the innermost surrounding blocks.. 11.4.1 Shadowing variables

  23. Bash variable assignment examples

    Variable assignment 2. Variable substitution 3. Built-in shell variables 4. Other shell variables 5. Variable Assignment. Variable names consist of any number of letters, digits, or underscores. Upper- and lowercase letters are distinct, and names may not start with a digit. Variables are assigned values using the = operator.