• Assignment Statement

An Assignment statement is a statement that is used to set a value to the variable name in a program .

Assignment statement allows a variable to hold different types of values during its program lifespan. Another way of understanding an assignment statement is, it stores a value in the memory location which is denoted by a variable name.

Assignment Statement Method

The symbol used in an assignment statement is called as an operator . The symbol is ‘=’ .

Note: The Assignment Operator should never be used for Equality purpose which is double equal sign ‘==’.

The Basic Syntax of Assignment Statement in a programming language is :

variable = expression ;

variable = variable name

expression = it could be either a direct value or a math expression/formula or a function call

Few programming languages such as Java, C, C++ require data type to be specified for the variable, so that it is easy to allocate memory space and store those values during program execution.

data_type variable_name = value ;

In the above-given examples, Variable ‘a’ is assigned a value in the same statement as per its defined data type. A data type is only declared for Variable ‘b’. In the 3 rd line of code, Variable ‘a’ is reassigned the value 25. The 4 th line of code assigns the value for Variable ‘b’.

Assignment Statement Forms

This is one of the most common forms of Assignment Statements. Here the Variable name is defined, initialized, and assigned a value in the same statement. This form is generally used when we want to use the Variable quite a few times and we do not want to change its value very frequently.

Tuple Assignment

Generally, we use this form when we want to define and assign values for more than 1 variable at the same time. This saves time and is an easy method. Note that here every individual variable has a different value assigned to it.

(Code In Python)

Sequence Assignment

(Code in Python)

Multiple-target Assignment or Chain Assignment

In this format, a single value is assigned to two or more variables.

Augmented Assignment

In this format, we use the combination of mathematical expressions and values for the Variable. Other augmented Assignment forms are: &=, -=, **=, etc.

Browse more Topics Under Data Types, Variables and Constants

  • Concept of Data types
  • Built-in Data Types
  • Constants in Programing Language 
  • Access Modifier
  • Variables of Built-in-Datatypes
  • Declaration/Initialization of Variables
  • Type Modifier

Few Rules for Assignment Statement

Few Rules to be followed while writing the Assignment Statements are:

  • Variable names must begin with a letter, underscore, non-number character. Each language has its own conventions.
  • The Data type defined and the variable value must match.
  • A variable name once defined can only be used once in the program. You cannot define it again to store other types of value.
  • If you assign a new value to an existing variable, it will overwrite the previous value and assign the new value.

FAQs on Assignment Statement

Q1. Which of the following shows the syntax of an  assignment statement ?

  • variablename = expression ;
  • expression = variable ;
  • datatype = variablename ;
  • expression = datatype variable ;

Answer – Option A.

Q2. What is an expression ?

  • Same as statement
  • List of statements that make up a program
  • Combination of literals, operators, variables, math formulas used to calculate a value
  • Numbers expressed in digits

Answer – Option C.

Q3. What are the two steps that take place when an  assignment statement  is executed?

  • Evaluate the expression, store the value in the variable
  • Reserve memory, fill it with value
  • Evaluate variable, store the result
  • Store the value in the variable, evaluate the expression.

Customize your course in 30 seconds

Which class are you in.

tutor

Data Types, Variables and Constants

  • Variables in Programming Language
  • Concept of Data Types
  • Declaration of Variables
  • Type Modifiers
  • Access Modifiers
  • Constants in Programming Language

Leave a Reply Cancel reply

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

Download the App

Google Play

  • 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
  • Solve Coding Problems
  • How to perform modulo with negative values in Python?
  • Python - Iterate through list without using the increment variable
  • How to install Python Pycharm on Windows?
  • Working with Binary Data in Python
  • Primary and secondary prompt in Python
  • Python Docstrings
  • Understanding the Execution of Python Program
  • is keyword in Python
  • Difference between continue and pass statements in Python
  • break, continue and pass in Python
  • Indentation in Python
  • Use of nonlocal vs use of global keyword in Python
  • Python assert keyword
  • Difference between Yield and Return in Python
  • Variables under the hood in Python
  • Is Python call by reference or call by value
  • Context Variables in Python
  • Python Scope of Variables
  • Internal working of Python

Different Forms of Assignment Statements in Python

We use Python assignment statements to assign objects to names. The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object.

There are some important properties of assignment in Python :-

  • Assignment creates object references instead of copying the objects.
  • Python creates a variable name the first time when they are assigned a value.
  • Names must be assigned before being referenced.
  • There are some operations that perform assignments implicitly.

Assignment statement forms :-

1. Basic form:

This form is the most common form.

2. Tuple assignment:

When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on the left by position and assigns them from left to right. Therefore, the values of x and y are 50 and 100 respectively.

3. List assignment:

This works in the same way as the tuple assignment.

4. Sequence assignment:

In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment – any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position.

5. Extended Sequence unpacking:

It allows us to be more flexible in how we select portions of a sequence to assign.

Here, p is matched with the first character in the string on the right and q with the rest. The starred name (*q) is assigned a list, which collects all items in the sequence not assigned to other names.

This is especially handy for a common coding pattern such as splitting a sequence and accessing its front and rest part.

6. Multiple- target assignment:

In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left.

7. Augmented assignment :

The augmented assignment is a shorthand assignment that combines an expression and an assignment.

There are several other augmented assignment forms:

Please Login to comment...

  • python-basics
  • What Is Trunk-Or-Treat?
  • 10 Best AI Tools for Lawyers (Free + Paid)
  • Fireflies AI vs Gong: Which AI Tool is best in 2024?
  • Top 10 Alternatives to Snapseed in 2024 [Free + Paid]
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Logo for Rebus Press

Want to create or adapt books like this? Learn more about how Pressbooks supports open publishing practices.

Kenneth Leroy Busbee

An assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable. [1]

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

Simple Assignment

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

Assignment with an Expression

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

Assignment with Identifier Names in the Expression

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

  • cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
  • Wikipedia: Assignment (computer science) ↵

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

assignment statement in programming

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Preface
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Variables
  • 1.7 Java Development Environments (optional)
  • 1.8 Unit 1 Summary
  • 1.9 Unit 1 Mixed Up Code Practice
  • 1.10 Unit 1 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Lesson Workspace
  • 1.3. Variables and Data Types" data-toggle="tooltip">
  • 1.5. Compound Assignment Operators' data-toggle="tooltip" >

1.4. Expressions and Assignment Statements ¶

In this lesson, you will learn about assignment statements and expressions that contain math operators and variables.

1.4.1. Assignment Statements ¶

Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator = . An assignment statement always has a single variable on the left hand side of the = sign. The value of the expression on the right hand side of the = sign (which can contain math operators and other variables) is copied into the memory location of the variable on the left hand side.

Assignment statement

Figure 1: Assignment Statement (variable = expression) ¶

Instead of saying equals for the = operator in an assignment statement, say “gets” or “is assigned” to remember that the variable on the left hand side gets or is assigned the value on the right. In the figure above, score is assigned the value of 10 times points (which is another variable) plus 5.

The following video by Dr. Colleen Lewis shows how variables can change values in memory using assignment statements.

As we saw in the video, we can set one variable to a copy of the value of another variable like y = x;. This won’t change the value of the variable that you are copying from.

coding exercise

Click on the Show CodeLens button to step through the code and see how the values of the variables change.

The program is supposed to figure out the total money value given the number of dimes, quarters and nickels. There is an error in the calculation of the total. Fix the error to compute the correct amount.

Calculate and print the total pay given the weekly salary and the number of weeks worked. Use string concatenation with the totalPay variable to produce the output Total Pay = $3000 . Don’t hardcode the number 3000 in your print statement.

exercise

Assume you have a package with a given height 3 inches and width 5 inches. If the package is rotated 90 degrees, you should swap the values for the height and width. The code below makes an attempt to swap the values stored in two variables h and w, which represent height and width. Variable h should end up with w’s initial value of 5 and w should get h’s initial value of 3. Unfortunately this code has an error and does not work. Use the CodeLens to step through the code to understand why it fails to swap the values in h and w.

1-4-7: Explain in your own words why the ErrorSwap program code does not swap the values stored in h and w.

Swapping two variables requires a third variable. Before assigning h = w , you need to store the original value of h in the temporary variable. In the mixed up programs below, drag the blocks to the right to put them in the right order.

The following has the correct code that uses a third variable named “temp” to swap the values in h and w.

The code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right, then check your solution. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.

After three incorrect attempts you will be able to use the Help Me button to make the problem easier.

Fix the code below to perform a correct swap of h and w. You need to add a new variable named temp to use for the swap.

1.4.2. Incrementing the value of a variable ¶

If you use a variable to keep score you would probably increment it (add one to the current value) whenever score should go up. You can do this by setting the variable to the current value of the variable plus one (score = score + 1) as shown below. The formula looks a little crazy in math class, but it makes sense in coding because the variable on the left is set to the value of the arithmetic expression on the right. So, the score variable is set to the previous value of score + 1.

Click on the Show CodeLens button to step through the code and see how the score value changes.

1-4-11: What is the value of b after the following code executes?

  • It sets the value for the variable on the left to the value from evaluating the right side. What is 5 * 2?
  • Correct. 5 * 2 is 10.

1-4-12: What are the values of x, y, and z after the following code executes?

  • x = 0, y = 1, z = 2
  • These are the initial values in the variable, but the values are changed.
  • x = 1, y = 2, z = 3
  • x changes to y's initial value, y's value is doubled, and z is set to 3
  • x = 2, y = 2, z = 3
  • Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side.
  • x = 1, y = 0, z = 3

1.4.3. Operators ¶

Java uses the standard mathematical operators for addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Arithmetic expressions can be of type int or double. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value. (You may have noticed that + was also used to put text together in the input program above – more on this when we talk about strings.)

Java uses the operator == to test if the value on the left is equal to the value on the right and != to test if two items are not equal. Don’t get one equal sign = confused with two equal signs == ! They mean different things in Java. One equal sign is used to assign a value to a variable. Two equal signs are used to test a variable to see if it is a certain value and that returns true or false as you’ll see below. Use == and != only with int values and not doubles because double values are an approximation and 3.3333 will not equal 3.3334 even though they are very close.

Run the code below to see all the operators in action. Do all of those operators do what you expected? What about 2 / 3 ? Isn’t surprising that it prints 0 ? See the note below.

When Java sees you doing integer division (or any operation with integers) it assumes you want an integer result so it throws away anything after the decimal point in the answer, essentially rounding down the answer to a whole number. If you need a double answer, you should make at least one of the values in the expression a double like 2.0.

With division, another thing to watch out for is dividing by 0. An attempt to divide an integer by zero will result in an ArithmeticException error message. Try it in one of the active code windows above.

Operators can be used to create compound expressions with more than one operator. You can either use a literal value which is a fixed value like 2, or variables in them. When compound expressions are evaluated, operator precedence rules are used, so that *, /, and % are done before + and -. However, anything in parentheses is done first. It doesn’t hurt to put in extra parentheses if you are unsure as to what will be done first.

In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider operator precedence .

1-4-15: Consider the following code segment. Be careful about integer division.

What is printed when the code segment is executed?

  • 0.666666666666667
  • Don't forget that division and multiplication will be done first due to operator precedence.
  • Yes, this is equivalent to (5 + ((a/b)*c) - 1).
  • Don't forget that division and multiplication will be done first due to operator precedence, and that an int/int gives an int result where it is rounded down to the nearest int.

1-4-16: Consider the following code segment.

What is the value of the expression?

  • Dividing an integer by an integer results in an integer
  • Correct. Dividing an integer by an integer results in an integer
  • The value 5.5 will be rounded down to 5

1-4-17: Consider the following code segment.

  • Correct. Dividing a double by an integer results in a double
  • Dividing a double by an integer results in a double

1-4-18: Consider the following code segment.

  • Correct. Dividing an integer by an double results in a double
  • Dividing an integer by an double results in a double

1.4.4. The Modulo Operator ¶

The percent sign operator ( % ) is the mod (modulo) or remainder operator. The mod operator ( x % y ) returns the remainder after you divide x (first number) by y (second number) so 5 % 2 will return 1 since 2 goes into 5 two times with a remainder of 1. Remember long division when you had to specify how many times one number went into another evenly and the remainder? That remainder is what is returned by the modulo operator.

../_images/mod-py.png

Figure 2: Long division showing the whole number result and the remainder ¶

In the example below, try to guess what it will print out and then run it to see if you are right.

The result of x % y when x is smaller than y is always x . The value y can’t go into x at all (goes in 0 times), since x is smaller than y , so the result is just x . So if you see 2 % 3 the result is 2 .

1-4-21: What is the result of 158 % 10?

  • This would be the result of 158 divided by 10. modulo gives you the remainder.
  • modulo gives you the remainder after the division.
  • When you divide 158 by 10 you get a remainder of 8.

1-4-22: What is the result of 3 % 8?

  • 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number!
  • This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8.
  • What is the remainder after you divide 3 by 8?

1.4.5. FlowCharting ¶

Assume you have 16 pieces of pizza and 5 people. If everyone gets the same number of slices, how many slices does each person get? Are there any leftover pieces?

In industry, a flowchart is used to describe a process through symbols and text. A flowchart usually does not show variable declarations, but it can show assignment statements (drawn as rectangle) and output statements (drawn as rhomboid).

The flowchart in figure 3 shows a process to compute the fair distribution of pizza slices among a number of people. The process relies on integer division to determine slices per person, and the mod operator to determine remaining slices.

Flow Chart

Figure 3: Example Flow Chart ¶

A flowchart shows pseudo-code, which is like Java but not exactly the same. Syntactic details like semi-colons are omitted, and input and output is described in abstract terms.

Complete the program based on the process shown in the Figure 3 flowchart. Note the first line of code declares all 4 variables as type int. Add assignment statements and print statements to compute and print the slices per person and leftover slices. Use System.out.println for output.

1.4.6. Storing User Input in Variables ¶

Variables are a powerful abstraction in programming because the same algorithm can be used with different input values saved in variables.

Program input and output

Figure 4: Program input and output ¶

A Java program can ask the user to type in one or more values. The Java class Scanner is used to read from the keyboard input stream, which is referenced by System.in . Normally the keyboard input is typed into a console window, but since this is running in a browser you will type in a small textbox window displayed below the code. The code below shows an example of prompting the user to enter a name and then printing a greeting. The code String name = scan.nextLine() gets the string value you enter as program input and then stores the value in a variable.

Run the program a few times, typing in a different name. The code works for any name: behold, the power of variables!

Run this program to read in a name from the input stream. You can type a different name in the input window shown below the code.

Try stepping through the code with the CodeLens tool to see how the name variable is assigned to the value read by the scanner. You will have to click “Hide CodeLens” and then “Show in CodeLens” to enter a different name for input.

The Scanner class has several useful methods for reading user input. A token is a sequence of characters separated by white space.

Run this program to read in an integer from the input stream. You can type a different integer value in the input window shown below the code.

A rhomboid (slanted rectangle) is used in a flowchart to depict data flowing into and out of a program. The previous flowchart in Figure 3 used a rhomboid to indicate program output. A rhomboid is also used to denote reading a value from the input stream.

Flow Chart

Figure 5: Flow Chart Reading User Input ¶

Figure 5 contains an updated version of the pizza calculator process. The first two steps have been altered to initialize the pizzaSlices and numPeople variables by reading two values from the input stream. In Java this will be done using a Scanner object and reading from System.in.

Complete the program based on the process shown in the Figure 5 flowchart. The program should scan two integer values to initialize pizzaSlices and numPeople. Run the program a few times to experiment with different values for input. What happens if you enter 0 for the number of people? The program will bomb due to division by zero! We will see how to prevent this in a later lesson.

The program below reads two integer values from the input stream and attempts to print the sum. Unfortunately there is a problem with the last line of code that prints the sum.

Run the program and look at the result. When the input is 5 and 7 , the output is Sum is 57 . Both of the + operators in the print statement are performing string concatenation. While the first + operator should perform string concatenation, the second + operator should perform addition. You can force the second + operator to perform addition by putting the arithmetic expression in parentheses ( num1 + num2 ) .

More information on using the Scanner class can be found here https://www.w3schools.com/java/java_user_input.asp

1.4.7. Programming Challenge : Dog Years ¶

In this programming challenge, you will calculate your age, and your pet’s age from your birthdates, and your pet’s age in dog years. In the code below, type in the current year, the year you were born, the year your dog or cat was born (if you don’t have one, make one up!) in the variables below. Then write formulas in assignment statements to calculate how old you are, how old your dog or cat is, and how old they are in dog years which is 7 times a human year. Finally, print it all out.

Calculate your age and your pet’s age from the birthdates, and then your pet’s age in dog years. If you want an extra challenge, try reading the values using a Scanner.

1.4.8. Summary ¶

Arithmetic expressions include expressions of type int and double.

The arithmetic operators consist of +, -, * , /, and % (modulo for the remainder in division).

An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away, essentially rounding down the answer to a whole number.

An arithmetic operation that uses at least one double value will evaluate to a double value.

Operators can be used to construct compound expressions.

During evaluation, operands are associated with operators according to operator precedence to determine how they are grouped. (*, /, % have precedence over + and -, unless parentheses are used to group those.)

An attempt to divide an integer by zero will result in an ArithmeticException to occur.

The assignment operator (=) allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.

During execution, expressions are evaluated to produce a single value.

The value of an expression has a type based on the evaluation of the expression.

logo

Learning Python by doing

  • suggest edit

Variables, Expressions, and Assignments

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

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

Values and Types #

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

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

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

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

Expressions and Statements #

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

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

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

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

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

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

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

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

Assignment Statements #

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

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

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

Do It Yourself!

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

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

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

Names and Keywords #

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

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

It should start with a letter or underscore.

It cannot start with a number.

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

They cannot share the name of a Python keyword.

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

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

The following are examples of invalid variable names.

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

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

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

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

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass break

except in raise

Reassignments #

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

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

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

Updating Variables #

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

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

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

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

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

Order of Operations #

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

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

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

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

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

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

In case of doubt, use parentheses!

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

Floor Division and Modulus Operators #

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

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

Conventional division returns a floating-point number.

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

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

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

The modulus operator is more useful than it seems.

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

String Operations #

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

But there are two exceptions, + and * .

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

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

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

Asking the User for Input #

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

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

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

Try it out!

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

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

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

Script Mode #

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

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

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

Library homepage

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

selected template will load here

This action is not available.

Chemistry LibreTexts

2.3: Arithmetic Operations and Assignment Statements

  • Last updated
  • Save as PDF
  • Page ID 206261

  • Robert Belford
  • University of Arkansas at Little Rock

hypothes.is tag:  s20iostpy03ualr Download Assignment:  S2020py03

Learning Objectives

Students will be able to:

  • Explain each Python arithmetic operator
  • Explain the meaning and use of an  assignment statement
  • Explain the use of "+"  and "*" with strings and numbers
  • Use the  int()   and  float()  functions to convert string input to numbers for computation
  • Incorporate numeric formatting into print statements
  • Recognize the four main operations of a computer within a simple Python program
  • Create  input  statements in Python
  • Create  Python  code that performs mathematical and string operations
  • Create  Python  code that uses assignment statements
  • Create  Python   code that formats numeric output

Prior Knowledge

  • Understanding of Python print and input statements
  • Understanding of mathematical operations
  • Understanding of flowchart input symbols

Further Reading

  • https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Hello,_World
  • https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Who_Goes_There%3F

Model 1: Arithmetic Operators in  Python

Python includes several arithmetic operators: addition, subtraction, multiplication, two types of division, exponentiation and  mod .

Critical Thinking Questions:

1.  Draw a line between each flowchart symbol and its corresponding line of Python code. Make note of any problems.

2. Execute the print statements in the previous Python program

    a.  Next to each print statement above, write the output.     b.  What is the value of the following line of code?

    c.  Predict the values of 17%3 and 18%3 without using your computer.

3.  Explain the purpose of each arithmetic operation:

a.               +          ____________________________

b.               -           ____________________________

c.               *          ____________________________

d.               **        ____________________________

e.               /           ____________________________

f.                //          ____________________________

g.                %         ____________________________

An  assignment statement  is a line of code that uses a "=" sign. The statement stores the result of an operation performed on the right-hand side of the sign into the variable memory location on the left-hand side.

4.         Enter and execute the following lines of Python code in the editor window of your IDE (e.g. Thonny):

 a.  What are the variables in the above python program?    b.  What does the  assignment statement :  MethaneMolMs = 16  do?    c.  What happens if you replace the comma (,) in the print statements with a plus sign (+) and execute the code again?  Why does this happen?

5.    What is stored in memory after each assignment statement is executed?

variable assignments

Note: Concatenating Strings in python

The "+"  concatenates  the two strings stored in the variables into one string.    "+" can only be used when both operators are strings.

6.         Run the following program in the editor window of your IDE (e.g. Thonny) to see what happens if you try to use the "+" with strings instead of numbers?

   a.  The third line of code contains an assignment statement. What is stored in  fullName   when the line is executed?    b.  What is the difference between the two output lines?    c.  How could you alter your assignment statements so that  print(fullName)  gives the same output as  print(firstName,lastName)    d. Only one of the following programs will work. Which one will work, and why doesn’t the other work? Try doing this without running the programs!

   e.  Run the programs above and see if you were correct.    f.  The program that worked above results in no space between the number and the street name. How can you alter the code so that it prints properly while using a concatenation operator?

7.  Before entering the following code into the Python interpreter (Thonny IDE editor window), predict the output of this program.

Now execute it.  What is the actual output?  Is this what you thought it would do?  Explain.

8.   Let’s take a look at a python program that prompts the user for two numbers and subtracts them. 

            Execute the following code by entering it in the editor window of Thonny.

      a.   What output do you expect?       b.   What is the actual output       c.   Revise the program in the following manner:

  • Between lines two and three add the following lines of code:       num1 = int(firstNumber)      num2 = int(secondNumber)
  • Next, replace the statement:     difference = firstNumber – secondNumber with the statement:     difference = num1 – num2
  • Execute the program again. What output did you get?

     d.  Explain the purpose of the function  int().      e.  Explain how the changes in the program produced the desired output.

Model 3: Formatting Output in  Python

There are multiple ways to format output in python. The old way is to use the string modulo %, and the new way is with a format method function.

9.  Look closely at the output for python program 7.

    a. How do you indicate the number of decimals to display using

the string modulo (%) ______________________________________________________

the format function ________________________________________________________

     b. What happens to the number if you tell it to display less decimals than are in the number, regardless of formatting method used?

     c. What type of code allows you to right justify your numbers?

10.       Execute the following code by entering it in the editor window of Thonny.

a.  Does the output look like standard output for something that has dollars and cents associated with it?

b.  Replace the last line of code with the following:

print("Total cost of laptops: $%.2f" % price)   

print("Total cost of laptops:" ,format(price, '.2f.))

                Discuss the change in the output.

      

c.  Replace the last line of code with the following:

print("Total cost of laptops: $",   format(price,'.2f') print("Total cost of laptops: $" ,format(price, '.2f.))

              Discuss the change in the output.

d.  Experiment with the number ".2" in the ‘0.2f’ of the print above statement by substituting the following numbers and explain the results.

                     .4         ___________________________________________________

                     .0         ___________________________________________________

                     .1         ___________________________________________________

                     .8         ___________________________________________________

e.  Now try the following numbers in the same print statement. These numbers contain a whole number and a decimal. Explain the output for each number.

                     02.5     ___________________________________________________

                     08.2     ___________________________________________________

                     03.1     ___________________________________________________

f.  Explain what each part of the format function:  format(variable,  "%n.nf")  does in a print statement where n.n represents a number.

variable ____________________________           First n _________________________

Second n_______________________                      f    _________________________

g.          Revise the print statement by changing the "f" to "d" and  laptopCost = 600 . Execute the statements and explain the output format.

            print("Total cost of laptops: %2d" % price)             print("Total cost of laptops: %10d" % price)

h.         Explain how the function  format(var,'10d')  formats numeric data.  var  represents a whole number.

11.    Use the following program and output to answer the questions below.

a.   From the code and comments in the previous program, explain how the four main operations are implemented in this program. b.  There is one new function in this sample program.  What is it? From the corresponding output, determine what it does.

Application Questions: Use the Python Interpreter to check your work

  • 8 to the 4 th  power
  • The sum of 5 and 6 multiplied by the quotient of 34 and 7 using floating point arithmetic  
  • Write an assignment statement that stores the remainder obtained from dividing 87 and 8 in the variable  leftover  
  • Assume:  

courseLabel = "CHEM" courseNumber = "3350"

Write a line of Python code that concatenates the label with the number and stores the result in the variable  courseName . Be sure that there is a space between the course label and the course number when they are concatenated.

  • Write one line of Python code that will print the word "Happy!" one hundred times.  
  • Write one line of code that calculates the cost of 15 items and stores the result in the variable  totalCost
  • Write one line of code that prints the total cost with a label, a dollar sign, and exactly two decimal places.  Sample output:  Total cost: $22.5  
  • Assume: 

height1 = 67850 height2 = 456

Use Python formatting to write two print statements that will produce the following output exactly at it appears below:

output

Homework Assignment: s2020py03

Download the assignment from the website, fill out the word document, and upload to your Google Drive folder the completed assignment along with the two python files.

1. (5 pts)  Write a Python program that prompts the user for two numbers, and then gives the sum and product of those two numbers. Your sample output should look like this:

Enter your first number:10 Enter your second number:2 The sum of these numbers is: 12 The product of these two numbers is: 20

  • Your program must contain documentation lines that include your name, the date, a line that states "Py03 Homework question 1" and a description line that indicates what the program is supposed to do. 
  • Paste the code this word document and upload to your Google drive when the assignment is completed, with file name [your last name]_py03_HWQ1
  • Save the program as a python file (ends with .py), with file name [your last name]_py03Q1_program and upload that to the Google Drive.

2. (10 pts) Write a program that calculates the molarity of a solution. Molarity is defined as numbers of moles per liter solvent. Your program will calculate molarity and must ask for the substance name, its molecular weight, how many grams of substance you are putting in solution, and the total volume of the solution. Report your calculated value of molarity to 3 decimal places. Your output should also be separated from the input with a line containing 80 asterixis.

Assuming you are using sodium chloride, your input and output should look like:

clipboard_edfaec3a5372d389c1f48c61ebe904909.png

  • Your program must contain documentation lines that include your name, the date, a line that states "Py03 Homework question 2" and a description line that indicates what the program is supposed to do. 
  • Paste the code to question two below
  • Save the program as a python file (ends with .py), with file name [your last name]_py03Q2_program and upload that to the Google Drive.

3. (4 pts) Make two hypothes.is annotations dealing with external open access resources on formatting with the format function method of formatting.  These need the tag of s20iostpy03ualr .

Copyright Statement

cc4.0

  • Contributors

Basic Statements in Python

Table of contents, what is a statement in python, statement set, multi-line statements, simple statements, expression statements, the assert statement, the try statement.

Statements in Python

In Python, statements are instructions or commands that you write to perform specific actions or tasks. They are the building blocks of a Python program.

A statement is a line of code that performs a specific action. It is the smallest unit of code that can be executed by the Python interpreter.

Assignment Statement

In this example, the value 10 is assigned to the variable x using the assignment statement.

Conditional Statement

In this example, the if-else statement is used to check the value of x and print a corresponding message.

By using statements, programmers can instruct the computer to perform a variety of tasks, from simple arithmetic operations to complex decision-making processes. Proper use of statements is crucial to writing efficient and effective Python code.

Here's a table summarizing various types of statements in Python:

Please note that this table provides a brief overview of each statement type, and there may be additional details and variations for each statement.

Multi-line statements are a convenient way to write long code in Python without making it cluttered. They allow you to write several lines of code as a single statement, making it easier for developers to read and understand the code. Here are two examples of multi-line statements in Python:

  • Using backslash:
  • Using parentheses:

Simple statements are the smallest unit of execution in Python programming language and they do not contain any logical or conditional expressions. They are usually composed of a single line of code and can perform basic operations such as assigning values to variables , printing out values, or calling functions .

Examples of simple statements in Python:

Simple statements are essential to programming in Python and are often used in combination with more complex statements to create robust programs and applications.

Expression statements in Python are lines of code that evaluate and produce a value. They are used to assign values to variables, call functions, and perform other operations that produce a result.

In this example, we assign the value 5 to the variable x , then add 3 to x and assign the result ( 8 ) to the variable y . Finally, we print the value of y .

In this example, we define a function square that takes one argument ( x ) and returns its square. We then call the function with the argument 5 and assign the result ( 25 ) to the variable result . Finally, we print the value of result .

Overall, expression statements are an essential part of Python programming and allow for the execution of mathematical and computational operations.

The assert statement in Python is used to test conditions and trigger an error if the condition is not met. It is often used for debugging and testing purposes.

Where condition is the expression that is tested, and message is the optional error message that is displayed when the condition is not met.

In this example, the assert statement tests whether x is equal to 5 . If the condition is met, the statement has no effect. If the condition is not met, an error will be raised with the message x should be 5 .

In this example, the assert statement tests whether y is not equal to 0 before performing the division. If the condition is met, the division proceeds as normal. If the condition is not met, an error will be raised with the message Cannot divide by zero .

Overall, assert statements are a useful tool in Python for debugging and testing, as they can help catch errors early on. They are also easily disabled in production code to avoid any unnecessary overhead.

The try statement in Python is used to catch exceptions that may occur during the execution of a block of code. It ensures that even when an error occurs, the code does not stop running.

Examples of Error Processing

Dive deep into the topic.

  • Match Statements
  • Operators in Python Statements
  • The IF Statement

Contribute with us!

Do not hesitate to contribute to Python tutorials on GitHub: create a fork, update content and issue a pull request.

Profile picture for user AliaksandrSumich

clear sunny desert yellow sand with celestial snow bridge

1.7 Java | Assignment Statements & Expressions

An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java.

After a variable is declared, you can assign a value to it by using an assignment statement . In Java, the equal sign = is used as the assignment operator . The syntax for assignment statements is as follows:

An expression represents a computation involving values, variables, and operators that, when taking them together, evaluates to a value. For example, consider the following code:

You can use a variable in an expression. A variable can also be used on both sides of the =  operator. For example:

In the above assignment statement, the result of x + 1  is assigned to the variable x . Let’s say that x is 1 before the statement is executed, and so becomes 2 after the statement execution.

To assign a value to a variable, you must place the variable name to the left of the assignment operator. Thus the following statement is wrong:

Note that the math equation  x = 2 * x + 1  ≠ the Java expression x = 2 * x + 1

Java Assignment Statement vs Assignment Expression

Which is equivalent to:

And this statement

is equivalent to:

Note: The data type of a variable on the left must be compatible with the data type of a value on the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and does not accept the double value 1.0 without Type Casting .

◄◄◄BACK | NEXT►►►

What's Your Opinion? Cancel reply

Enhance your Brain

Subscribe to Receive Free Bio Hacking, Nootropic, and Health Information

HTML for Simple Website Customization My Personal Web Customization Personal Insights

DISCLAIMER | Sitemap | ◘

SponserImageUCD

HTML for Simple Website Customization My Personal Web Customization Personal Insights SEO Checklist Publishing Checklist My Tools

Top Posts & Pages

7. VbScript | Do Loop

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"

CS101: Introduction to Computer Science I

assignment statement in programming

Variables and Assignment Statements

Read this chapter, which covers variables and arithmetic operations and order precedence in Java.

9. Assignment Statements

No. The incorrect splittings are highlighted in red:

Assignment Statement

So far, the example programs have been using the value initially put into a variable. Programs can change the value in a variable. An  assignment statement  changes the value that is held in a variable. The program uses an assignment statement.

The assignment statement puts the value 123 into the variable. In other words, while the program is executing there will be a 64 bit section of memory that holds the value 123.

Remember that the word "execute" is often used to mean "run". You speak of "executing a program" or "executing" a line of the program.

Question 10:

What Is an Assignment Statement in Java?

...

Java programs store data values in variables. When a programmer creates a variable in a Java application, he declares the type and name of the variable, then assigns a value to it. The value of a variable can be altered at subsequent points in execution using further assignment operations. The assignment statement in Java involves using the assignment operator to set the value of a variable. The exact syntax depends on the type of variable receiving a value.

Advertisement

Video of the Day

In Java, variables are strongly typed. This means that when you declare a variable in a Java program, you must declare its type, followed by its name. The following sample Java code demonstrates declaring two variables, one of primitive-type integer and one of an object type for a class within the application: int num; ApplicationHelper myHelp;

Once a program contains a variable declaration, the kind of value assigned to the variable must be suited to the type declared. These variable declarations could be followed by assignment statements on subsequent lines. However, the assignment operation could also take place on the same line as the declaration.

Assignment in Java is the process of giving a value to a primitive-type variable or giving an object reference to an object-type variable. The equals sign acts as assignment operator in Java, followed by the value to assign. The following sample Java code demonstrates assigning a value to a primitive-type integer variable, which has already been declared: num = 5;

The assignment operation could alternatively appear within the same line of code as the declaration of the variable, as follows: int num = 5;

The value of the variable can be altered again in subsequent processing as in this example: num++;

This code increments the variable value, adding a value of one to it.

Instantiation

When the assignment statement appears with object references, the assignment operation may also involve object instantiation. When Java code creates a new object instance of a Java class in an application, the "new" keyword causes the constructor method of the class to execute, instantiating the object. The following sample code demonstrates instantiating an object variable: myHelp = new ApplicationHelper();

This could also appear within the same line as the variable declaration as follows: ApplicationHelper myHelp = new ApplicationHelper();

When this line of code executes, the class constructor method executes, returning an instance of the class, a reference to which is stored by the variable.

Referencing

Once a variable has been declared and assigned a value, a Java program can refer to the variable in subsequent processing. For primitive-type variables, the variable name refers to a stored value. For object types, the variable refers to the location of the object instance in memory. This means that two object variables can point to the same instance, as in the following sample code: ApplicationHelper myHelp = new ApplicationHelper(); ApplicationHelper sameHelp = myHelp;

This syntax appears commonly when programs pass object references as parameters to class methods.

  • Oracle: The Java Tutorials - Variables
  • Oracle: The Java Tutorials - Assignment, Arithmetic, and Unary Operators
  • Oracle: The Java Tutorials - Primitive Data Types
  • Oracle: The Java Tutorials - Creating Objects
  • Oracle: The Java Tutorials - What Is an Object?
  • Oracle: The Java Tutorials - Summary of Variables
  • Java Language Specification; Types, Values, and Variables; 2000
  • Oracle: The Java Tutorials - Understanding Instance and Class Members

Report an Issue

Screenshot loading...

Assignment Statement in C

How to assign values to the variables? C provides an  assignment operator  for this purpose, assigning the value to a variable using assignment operator is known as an assignment statement in C.

The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side.

The syntax of the  assignment expression

Variable = constant / variable/ expression;

The data type of the variable on left hand side should match the data type of constant/variable/expression on right hand side with a few exceptions where automatic type conversions are possible.

Examples of assignment statements,

b = c ; /* b is assigned the value of c */ a = 9 ; /* a is assigned the value 9*/ b = c+5; /* b is assigned the value of expr c+5 */

The expression on the right hand side of the assignment statement can be:

An arithmetic expression; A relational expression; A logical expression; A mixed expression.

The above mentioned expressions are different in terms of the type of operators connecting the variables and constants on the right hand side of the variable. Arithmetic operators, relational

Arithmetic operators, relational operators and logical operators are discussed in the following sections.

For example, int a; float b,c ,avg, t; avg = (b+c) / 2; /*arithmetic expression */ a = b && c; /*logical expression*/ a = (b+c) && (b<c); /* mixed expression*/

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related Posts

  • #define to implement constants
  • Preprocessor in C Language
  • Pointers and Strings

Leave a Reply Cancel reply

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

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

Notify me of follow-up comments by email.

Notify me of new posts by email.

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

Go home

Assignment Statements

Simple assignment.

  • variable = expression;
  • The expression is evaluated and the result is assigned to the variable

The simple assignment operator "=", assigns the value on its right to the variable on its left.

Compound Assignment

  • variable = variable op expression;
  • Statements with the same variable on each side of the equals sign
  • May use the shortcut assignment operators (compound assignment)

When writing any kind of program, there will be many instances where you will need to use a variable as part of an expression and you will want to assign the result of that expression into the same variable. An example of this kind of operation is when you want to increment a variable by some value (variable or constant). For example, if we wanted to add 5 to a variable called x, we could write it as x = x + 5 since we want to add 5 to the value of x and store the result back in x.

Because it is extremely common to have the same variable on both sides of the expression, C provides a shortcut notation. This is implemented with one of a series of compound assignment operators. Using the same example, if we wanted to add 5 to the variable x, we could write it as x += 5. Similar operations may be carried out using one of the many compound operators shown in Table 2.

Statement vs Expression – What's the Difference in Programming?

Learning the syntax of a programming language is key if you want to use that language effectively. This is true for both new and experienced developers.

And one of the most important things to pay attention to while learning a programming language is whether the code you're dealing with is a statement or an expression.

It can sometimes be confusing to differentiate between statements and expressions in programming. So this article is meant to simplify the differences so that you can improve your programming skills and become a better developer.

What is an Expression in Programming?

Senior caucasian man holding blank empty banner covering mouth with hand, shocked and afraid for mistake. surprised expression

An expression is any word or group of words or symbols that is a value. In programming, an expression is a value, or anything that executes and ends up being a value.

It is necessary to understand that a value is unique. For example, const , let , 2 , 4 , s , a , true , false , and world are values because each of them is unique in meaning or character.

Let's look at some code as an example:

Judging from the code above, const , price , = , and 500 are expressions because each of them has a definite and unique meaning or value. But if we take all of them together const price = 500 - then we have a statement.

Let's look at another example:

Looking at the code above, you can see an anonymous function is assigned to a variable. Oh, wait! You might know that any function is a statement. Can it also be an expression?

Yes! A "function" and a "class" are both statements and expressions because they can perform actions (do or not do tasks) and still execute to a value.

This brings us to statements – so what are they?

What is a Statement in Programming?

A statement is a group of expressions and/or statements that you design to carry out a task or an action.

Statements are two-sided – that is, they either do tasks or don't do them. Any statement that can return a value is automatically qualified to be used as an expression. That is why a function or class is a statement and also an expression in JavaScript.

If you look at the example of the function under the section on expressions, you can see it is assigned and execute to a value passed to a variable. That is why it is an expression in that case.

Examples of Statements in Programming

Inline statements.

The whole of the code above is a statement because it carries out the task of assigning $2000 to amount . It is safe to say a line of code is a statement because most compilers or interpreters don't execute any standalone expression.

Happy man portraits

Block statements

Look at the below if statement:

The if statement is a statement because it helps us check whether I love you or not. As I have said before, it is two-sided: this code finds out whether "I love you" or not, and that is why it is a statement. Also, it doesn't return any value but it can create side effects.

Here's a loop statement:

In short, any loop is a statement because if it can only do the tasks it is meant to do or not – does loop and doesn't loop. But a loop can't execute to a value in the end. They can only have side effects in JavaScript. Once they can execute to a value in a programming language, then they can also be used as an expression.

For example, you can use forloop and if statement as expressions in Python.

There is also an "IF" expression in Python. That means that something that is a statement in one language can be an expression (or both statement and expression) in another.

Look at the below function statement:

We declare the function add(firstNumber, secondNumber) and it returns a value. The function is called with two arguments as in add(2, 3) by declaration and so it is a statement. If you pay close attention, you will realize that calling the function as a statement is useless since it has no side effect.

Hey, stop! How can we turn it into an expression? Oh yeah, we can do it like this:

Though the function is now an expression the way it is called above, the whole of the code is still a statement.

Check out this class statement:

You can see that we declare the class "Person" and instantiate and assign it to "User" immediately. So, it is used as an expression.

Now, let's use it as a statement:

A class is similar to a function in the sense that it can be declared, assigned, or used as an operand just like a class. So, a class is a statement and/or an expression.

The Main Differences Between an Expression and a Statement in Programming

Expressions can be assigned or used as operands, while statements can only be declared.

Statements create side effects to be useful, while expressions are values or execute to values.

Expressions are unique in meaning, while statements are two-sided in execution. For example, 1 has a certain value while go( ) may be executed or not.

Statements are the whole structure, while expressions are the building blocks. For example, a line or a block of code is a statement.

Why You Should Know the Difference

First of all, understanding the difference between statements and expressions should make learning new programming languages less surprising. If you're used to JavaScript, you may be surprised by Python's ability to assign an if statement as a variable which is not possible in JavaScript.

Second, it makes it easy to use programming paradigms across different programming languages.

For example, a JavaScript "if statement" cannot be used as an expression because it can't execute to a value – it can only create side effects. Yet, you can use the ternary operator if you want to avoid the side effects of using an if statement in JavaScript.

For this reason, you can understand why some programmers avoid if statements by using the ternary operator in JavaScript. It is because they want to avoid side effects .

It also makes your realize why you have to be always careful about the scope of your variables whenever you use a statement. This is true because statements mostly have side effects to be useful, and it is reasonable to understand the scope of your variables and operations. For example,

Hey wait! What would be logged in the console if you ran the code above?

Tell yourself the answer first and then paste the code in the console to confirm. If you you're wrong, you need to learn more about scope and side effects. But if you're right, try to make those functions a bit better to avoid the confusion they may generate.

Knowing the difference also helps you to easily identify non-composable and composable syntaxes (functions, classes, modules, and so on) of a programming language. This makes porting your experience from one programming language to another more interesting and direct.

Wrapping Up

Now that you understand the difference between expressions and statements in programming, and you know why understanding the differences is important, you can identify pieces of code as expressions or statements while coding.

Next time, we'll go even further and help make learning a second programming language easier.

Go and get things done now! See you soon.

I am planning to share a lot about programming tips and tutorials in 2023. If you're struggling to build projects or you want to stay connected with my write-ups and videos, please join my list at YouTooCanCode or subscribe to my YouTube channel at You Too Can Code on YouTube .

Ayobami loves writing history with JavaScript(React) and PHP(Laravel). He has been making programming fun to learn for learners. Check him out on YouTube: https://bit.ly/3usOu3s

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

IMAGES

  1. PPT

    assignment statement in programming

  2. PPT

    assignment statement in programming

  3. 51. Assignment and Multiple Assignment Statement in C Programming (Hindi)

    assignment statement in programming

  4. PPT

    assignment statement in programming

  5. PPT

    assignment statement in programming

  6. What is statement in Programming?

    assignment statement in programming

VIDEO

  1. Programming Methodologies

  2. Week 13

  3. CSE102 Programming Zero C Assignment Statement

  4. if statement in C programming part #12

  5. Assignment Statement ll python ll Animation ll class-6 ll

  6. _DSDV_Discuss Structure, Variable Assignment Statement in verilog

COMMENTS

  1. Assignment (computer science)

    Assignment (computer science) In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location (s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages, the assignment statement (or expression) is a fundamental construct.

  2. What are Assignment Statement: Definition, Assignment Statement ...

    An Assignment statement is a statement that is used to set a value to the variable name in a program. Assignment statement allows a variable to hold different types of values during its program lifespan. Another way of understanding an assignment statement is, it stores a value in the memory location which is denoted.

  3. PDF The assignment statement

    The assignment statement. The assignment statement is used to store a value in a variable. As in most programming languages these days, the assignment statement has the form: <variable>= <expression>; For example, once we have an int variable j, we can assign it the value of expression 4 + 6: int j; j= 4+6; As a convention, we always place a ...

  4. Different Forms of Assignment Statements in Python

    Assignment statement forms :- 1. Basic form: This form is the most common form. 2. Tuple assignment: When we code a tuple on the left side of the =, Python pairs objects on the right side with targets on the left by position and assigns them from left to right.

  5. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  6. What is an Assignment?

    Assignment: An assignment is a statement in computer programming that is used to set a value to a variable name. The operator used to do assignment is denoted with an equal sign (=). This operand works by assigning the value on the right-hand side of the operand to the operand on the left-hand side. It is possible for the same variable to hold ...

  7. 1.4. Expressions and Assignment Statements

    In this lesson, you will learn about assignment statements and expressions that contain math operators and variables. 1.4.1. Assignment Statements ¶. Assignment statements initialize or change the value stored in a variable using the assignment operator =. An assignment statement always has a single variable on the left hand side.

  8. Assignment Statements :: CIS 301 Textbook

    Assignments with mutation are variable assignments that use the old value of a variable to calculate a value for the variable. For example, an increment statement like x = x + 1 MUTATES the value of x by updating its value to be one bigger than it was before. In order to make sense of such a statement, we need to know the previous value of x.

  9. PDF 1. The Assignment Statement and Types

    Rule 1. Name must be comprised of digits, upper case letters, lower case letters, and the underscore character "_". Rule 2. Must begin with a letter or underscore. A good name for a variable is short but suggestive of its role: Circle_Area.

  10. Assignment

    An assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable. [1] ... (again usually a variable). Within most programming languages the symbol used for assignment is the equal symbol. But bite your tongue, when you see the = symbol you ...

  11. 1.4. Expressions and Assignment Statements

    In this lesson, you will learn about assignment statements and expressions that contain math operators and variables. 1.4.1. Assignment Statements ¶. Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator =.

  12. PDF Resource: Variables, Declarations & Assignment Statements

    Three interrelated programming concepts are variables, declarations and assignment statements. Variables The concept of a variable is a powerful programming idea. It's called a variable because - now pay attention - it varies. When you see it used in a program, the variable is often written like this r = 255; (r is the variable and the ...

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

  14. Variables, Expressions, and Assignments

    Lastly, an assignment is a language construct know as an statement that assign a value (either as a constant or expression) to a variable. The rest of this notebook will dive into the main concepts that we need to fully understand these three language constructs. Values and Types# A value is the basic unit used in a program. It may be, for ...

  15. 2.3: Arithmetic Operations and Assignment Statements

    An assignment statement is a line of code that uses a "=" sign. The statement stores the result of an operation performed on the right-hand side of the sign into the variable memory location on the left-hand side. 4. Enter and execute the following lines of Python code in the editor window of your IDE (e.g. Thonny):

  16. Introduction into Python Statements: Assignment, Conditional Examples

    Expression statements in Python are lines of code that evaluate and produce a value. They are used to assign values to variables, call functions, and perform other operations that produce a result. x = 5. y = x + 3. print(y) In this example, we assign the value 5 to the variable x, then add 3 to x and assign the result ( 8) to the variable y.

  17. 1.7 Java

    An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java. After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is as follows: variable ...

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

  19. Variables and Assignment Statements: Assignment Statements

    The program uses an assignment statement. The assignment statement puts the value 123 into the variable. In other words, while the program is executing there will be a 64 bit section of memory that holds the value 123. Remember that the word "execute" is often used to mean "run". You speak of "executing a program" or "executing" a line of the ...

  20. What Is an Assignment Statement in Java?

    Assignment. Assignment in Java is the process of giving a value to a primitive-type variable or giving an object reference to an object-type variable. The equals sign acts as assignment operator in Java, followed by the value to assign. The following sample Java code demonstrates assigning a value to a primitive-type integer variable, which has ...

  21. Assignment Statement in C Programming Language

    b = c+5; /* b is assigned the value of expr c+5 */. The expression on the right hand side of the assignment statement can be: An arithmetic expression; A relational expression; A logical expression; A mixed expression. The above mentioned expressions are different in terms of the type of operators connecting the variables and constants on the ...

  22. Assignment Statements

    Compound Assignment. Statements with the same variable on each side of the equals sign. May use the shortcut assignment operators (compound assignment) When writing any kind of program, there will be many instances where you will need to use a variable as part of an expression and you will want to assign the result of that expression into the ...

  23. Understanding Variables and Assignment Statements in Python

    Understanding Variables and Assignment Statements in Python In Python, an assignment statement is used to create, initialize, and update variables. Variables are names given to specific values or objects that can be reused throughout the program. To bind a value to a variable, the assignment operator (=) is used. This allows the variable to be updated and used throughout the program as needed ...

  24. Statement vs Expression

    Expressions are unique in meaning, while statements are two-sided in execution. For example, 1 has a certain value while go ( ) may be executed or not. Statements are the whole structure, while expressions are the building blocks. For example, a line or a block of code is a statement.