• 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

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 definition computer

  • 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 Getting Started
  • 1.1.1 Preface
  • 1.1.2 About the AP CSA Exam
  • 1.1.3 Transitioning from AP CSP to AP CSA
  • 1.1.4 Java Development Environments
  • 1.1.5 Growth Mindset and Pair Programming
  • 1.1.6 Pretest for the AP CSA Exam
  • 1.1.7 Survey
  • 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 Values
  • 1.7 Unit 1 Summary
  • 1.8 Mixed Up Code Practice
  • 1.9 Toggle Mixed Up or Write Code Practice
  • 1.10 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Method Signatures (preview 2026 curriculum)
  • 1.13 Calling Class Methods (preview 2026 curriculum)
  • 1.3. Variables and Data Types" data-toggle="tooltip">
  • 1.5. Compound Assignment Operators' data-toggle="tooltip" >

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

Time estimate: 90 min.

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. The value of the expression (which can contain math operators and other variables) on the right of the = sign is stored in the variable on the left.

../_images/assignment.png

Figure 1: Assignment Statement (variable = expression;) ¶

Instead of saying equals for the = in an assignment statement, say “gets” or “is assigned” to remember that the variable gets or is assigned the value on the right. In the figure above score is assigned the value of the expression 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’s value 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.

Let’s step through the following code in the Java visualizer to see the values in memory. Click on the Next button at the bottom of the code to see how the values of the variables change. You can run the visualizer on any Active Code in this e-book by just clicking on the Code Lens button at the top of each Active Code.

Activity: CodeLens 1.4.1.2 (asgnviz1)

exercise

1-4-3: What are the values of x, y, and z after the following code executes? You can step through this code by clicking on this Java visualizer link.

  • 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 = 0, y = 0, z = 3

The following has the correct code to ‘swap’ the values in x and y (so that x ends up with y’s initial value and y ends up with x’s initial value), but 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. Check your solution by clicking on the Check button. 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.

1.4.2. Adding 1 to 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 would look strange in math class, but it makes sense in coding because it is assigning a new value to the variable on the left that comes from evaluating the arithmetic expression on the right. So, the score variable is set to the previous value of score plus 1.

Try the code below to see how score is incremented by 1. Try substituting 2 instead of 1 to see what happens.

1.4.3. Input with Variables ¶

Variables are a powerful abstraction in programming because the same algorithm can be used with different input values saved in variables. The code below using the Scanner class will say hello to anyone who types in their name and will have different results for different name values. First, type in your name below the code and then click on run. Try again with a friend’s name. The code works for any name: behold, the power of variables!

The code below will say hello to anyone who types in their name. Type in your name below the code and then click on run. Try again with a friend’s name.

Although you will not be tested in the AP CSA exam on using the Java input or the Scanner or Console classes, learning how to do input in Java is very useful and fun. For more information on using the Scanner class, go to https://www.w3schools.com/java/java_user_input.asp , and for the newer Console class, https://howtodoinjava.com/java-examples/console-input-output/ . We are limited with the one way communication with the Java server in this Runestone ebook, but in most IDEs like replit, the input/output would be more interactive. Here are some examples in replit for Java Scanner Input Repl using the Scanner class and Java Console Input Repl using the Console class that you can try out.

1.4.4. Operators ¶

Java uses the standard mathematical operators for addition ( + ), subtraction ( - ), and division ( / ). The multiplication operator is written as * , as it is in most programming languages, since the character sets used until relatively recently didn’t have a character for a real multiplication sign, × , and keyboards still don’t have a key for it. Likewise no ÷ .

You may be used to using ^ for exponentiation, either from a graphing calculator or tools like Desmos. Confusingly ^ is an operator in Java, but it has a completely different meaning than exponentiation and isn’t even exactly an arithmetic operator. You will learn how to use the Math.pow method to do exponents in Unit 2.

Arithmetic expressions can be of type int or double . An arithmetic expression consisting only of int values will evaluate to an int value. An arithmetic expression that uses at least one double value will evaluate to a double value. (You may have noticed that + was also used to combine String and other values into new String s. More on this when we talk about String s more fully in Unit 2.)

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 very 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. Also note that using == and != with double values can produce surprising results. Because double values are only an approximation of the real numbers even things that should be mathematically equivalent might not be represented by the exactly same double value and thus will not be == . To see this for yourself, write a line of code below to print the value of the expression 0.3 == 0.1 + 0.2 ; it will be false !

coding exercise

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 it surprising that it prints 0? See the note below about truncating division with integers. Change the code to make it print the decimal part of the division too. You can do this by making at least one of the numbers a double like 2.0.

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. This is called truncating division . 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, just like when we do math (remember PEMDAS?), 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 or just to make it more clear.

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 . How do the parentheses change the precedence?

1.4.5. The Remainder Operator ¶

The operator % in Java is the remainder operator. Like the other arithmetic operators is takes two operands. Mathematically it returns the remainder after dividing the first number by the second, using truncating integer division. For instance, 5 % 2 evaluates to 1 since 2 goes into 5 two times with a remainder of 1.

While you may not have heard of remainder as an operator, think back to elementary school math. Remember when you first learned long division, before they taught you about decimals, how when you did a long division that didn’t divide evenly, you gave the answer as the number of even divisions and the remainder. That remainder is what is returned by this operator. In the figures below, the remainders are the same values that would be returned by 2 % 3 and 5 % 2 .

../_images/mod-py.png

Figure 1: Long division showing the integer result and the remainder ¶

Sometimes people—including Professor Lewis in the next video—will call % the modulo , or mod , operator. That is not actually correct though the difference between remainder and modulo, which uses Euclidean division instead of truncating integer division, only matters when negative operands are involved and the signs of the operands differ. With positive operands, remainder and mod give the same results. Java does have a method Math.floorMod in the Math class if you need to use modulo instead of remainder, but % is all you need in the AP exam.

Here’s the video .

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-11: What is the result of 158 % 10?

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

1-4-12: 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.6. Programming Challenge : Dog Years ¶

dog

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. If you are pair programming, switch drivers (who has control of the keyboard in pair programming) after every line of code.

Calculate your age and your pet’s age from the birthdates, and then your pet’s age in dog years.

Your teacher may suggest that you use a Java IDE like replit.com for this challenge so that you can use input to get these values using the Scanner class . Here is a repl template that you can use to get started if you want to try the challenge with input.

1.4.7. Summary ¶

Arithmetic expressions include expressions of type int and double .

The arithmetic operators consist of + , - , * , / , and % also known as addition, subtraction, multiplication, division, and remainder.

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.

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 .

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 types of the values and operators used in the expression.

1.4.8. AP Practice ¶

The following is a 2019 AP CSA sample question.

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

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 truncated result where everything to the right of the decimal point is dropped.

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.

Intro to computer science - Python

Course: intro to computer science - python   >   unit 1, variables and assignment.

  • Variable design patterns
  • Evaluating variable expressions
  • Trace variables
  • Program design: catering contract
  • Challenge: URL paths

assignment statement definition computer

Want to join the conversation?

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

Video transcript

  • Structured Problem Solving
  • Assignment Statement
  • Edit on GitHub

Assignment Statement ¶

Programs can have many variables. Usually information is gathered from the user, stored in a variable, processed with other variables, saved back to one/some variable(s) and then returned to the user. Variables are changed or initially assigned a value by the use of an assignment statement . Assignment statements are usually read in reverse order from what we are use to in math class. A variable on the left side of the assignment statement will receive the value that is on the right hand side of the assignment statement. Note that different programming languages use different symbols to represent the assignment statement (for example in Alpha it is” ←”, in Pascal it is” :=”). No matter what the symbol is, you always read it as, “is assigned”. This is particularly important in many languages where the assignment symbol is an equal sign ( = ) and people are use to reading this as “is equal to”. In many of these language when you actually want to check for “equality” you then use (==).

Here are a few examples of assignment statements:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 // Copyright (c) 2020 Mr. Coxall All rights reserved. // // Created by: Mr. Coxall // Created on: Sep 2020 // This program shows assingment statements #include <stdio.h> #include <string.h> int main () { // variable definition int numberOfStudents = 2 ; float width = 32.5F ; float length = 10.0F ; float areaOfRectangle = 0 ; char someWords1 [] = "Hello" ; char someWords2 [] = "World!" ; char helloWorld [ 13 ] = "" ; // using assignment statements numberOfStudents = numberOfStudents + 5 ; areaOfRectangle = length * width ; strcat ( helloWorld , someWords1 ); strcat ( helloWorld , ", " ); strcat ( helloWorld , someWords2 ); // output printf ( "The number of students is: %d \n " , numberOfStudents ); printf ( "The area of a rectangle is: %.2f cm² \n " , areaOfRectangle ); printf ( "%s \n " , helloWorld ); printf ( " \n Done. \n " ); return 0 ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Copyright (c) 2020 Mr. Coxall All rights reserved. // // Created by: Mr. Coxall // Created on: Sep 2020 // This program shows assingment statements #include <iostream> int main () { // variable definition int numberOfStudents = 2 ; float width = 32.5F ; float length = 10.0F ; float areaOfRectangle = 0 ; std :: string someWords1 = "Hello" ; std :: string someWords2 = "World!" ; std :: string helloWorld = "" ; // using assignment statements numberOfStudents = numberOfStudents + 5 ; areaOfRectangle = length * width ; helloWorld = someWords1 + ", " + someWords2 ; // output std :: cout << "The number of students is: " << numberOfStudents << std :: endl ; std :: cout << "The area of a rectangle is: " << areaOfRectangle << " cm²" << std :: endl ; std :: cout << helloWorld << std :: endl ; std :: cout << " \n Done." << std :: endl ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 /* Created by: Mr. Coxall * Created on: Sep 2020 * This program shows assingment statements */ using System ; /* * The Program class * Contains all methods for performing basic variable usage */ class Program { public static void Main ( string [] args ) { // variable definition int numberOfStudents = 2 ; float width = 32.5F ; float length = 10.0F ; float areaOfRectangle = 0F ; string someWords1 = "Hello" ; string someWords2 = "World!" ; string helloWorld = null ; // using assignment statements numberOfStudents = numberOfStudents + 5 ; areaOfRectangle = length * width ; helloWorld = someWords1 + ", " + someWords2 ; // output Console . WriteLine ( "The number of students is: " + numberOfStudents ); Console . WriteLine ( "The area of a rectangle is: " + areaOfRectangle + " cm²" ); Console . WriteLine ( helloWorld ); Console . WriteLine ( "\nDone." ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 /** * Created by: Mr. Coxall * Created on: Sep 2020 * This program shows assingment statements */ package main import "fmt" func main () { // variable definition numberOfStudents := 2 width := 32.5 length := 10.0 someWords1 := "Hello" someWords2 := "World!" // using assignment statements numberOfStudents += 5 areaOfRectangle := length * width helloWorld := someWords1 + ", " + someWords2 // output fmt . Println ( "The number of students is:" , numberOfStudents ) fmt . Println ( "The area of a rectangle is:" , areaOfRectangle , "cm²" ) fmt . Println ( helloWorld ) fmt . Println ( "\nDone." ) }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 /* * This program program shows assingment statements * * @author Mr Coxall * @version 1.0 * @since 2020-09-01 */ final class Main { private Main () { // Prevent instantiation // Optional: throw an exception e.g. AssertionError // if this ever *is* called throw new IllegalStateException ( "Cannot be instantiated" ); } /** Constant number TWO. */ private static final int TWO = 2 ; /** Constant number THIRTY_TWO_POINT_FIVE. */ private static final float THIRTY_TWO_POINT_FIVE = 32.5F ; /** Constant number TEN. */ private static final float TEN = 10.0F ; /** Constant number FIVE. */ private static final int FIVE = 5 ; /** * Main entry point into program. * * @param args nothing passed in */ public static void main ( final String [] args ) { // variable definition int numberOfStudents = TWO ; float width = THIRTY_TWO_POINT_FIVE ; float length = TEN ; float areaOfRectangle = 0F ; String someWords1 = "Hello" ; String someWords2 = "World!" ; String helloWorld = null ; // using assignment statements numberOfStudents = numberOfStudents + FIVE ; areaOfRectangle = length * width ; helloWorld = someWords1 + ", " + someWords2 ; // output System . out . println ( "The number of students is: " + numberOfStudents ); System . out . println ( "The area of a rectangle is: " + areaOfRectangle + " cm²" ); System . out . println ( helloWorld ); System . out . println ( "\nDone." ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* Created by: Mr. Coxall * Created on: Sep 2020 * This program shows assingment statements */ // variable definition numberOfStudents = 2 width = 32.5 length = 10.0 someWords1 = "Hello" someWords2 = "World!" // using assignment statements numberOfStudents = numberOfStudents + 5 areaOfRectangle = length * width helloWorld = someWords1 + ", " + someWords2 // output console . log ( "The number of students is: " + numberOfStudents ) console . log ( "The area of a rectangle is: " + areaOfRectangle + " cm²" ) console . log ( helloWorld ) console . log ( "\nDone." )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 #!/usr/bin/env python3 """ Created by: Mr. Coxall Created on: Sep 2020 This module shows using the assignment statement """ def main () -> None : """The main() function shows variable definition, returns None.""" number_of_students = 2 width = 32.5 length = 10.0 some_words1 = "Hello" some_words2 = "World!" # using assignment statements number_of_students = number_of_students + 5 area_of_rectangle = length * width hello_world = some_words1 + ", " + some_words2 # output print ( "The number of students is: " + str ( number_of_students )) print ( "The area of a rectangle is: " + str ( area_of_rectangle ) + " cm²" ) print ( hello_world ) print ( " \n Done." ) if __name__ == "__main__" : main ()

Example Output ¶

Computer Science GCSE GURU

Term: Assignment

In programming, an assignment statement is used to set or copy a value into a variable .

  • IP and MAC addresses
  • Variables and Constants

Sign up for Guru News

Popular downloads.

assignment statement definition computer

Storage Devices Cheat Sheet

assignment statement definition computer

Internet Cheat Sheet

  • All Quizzes
  • Computer Science Glossary
  • Our YouTube Channel
  • GCSE GURU Revision Tips +

Small Print

  • Cookie Policy
  • Privacy Policy
  • Terms and Conditions

Downloads Shop

  • Information & Terms

Copyright © Computer Science GCSE GURU

Computer Science GCSE GURU

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Assignment Operators in C

assignment statement definition computer

Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example:

2. “+=” : This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. Example:

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

What is meant by assignment is a statement in Python?

In the official Python documentation, the assignment = is referred to as a statement or an expression. I really don't get it what it means by assignment is a statement . How is assignment a statement?

  • assignment-operator

A statement is code that tells the computer to do something. A statement has to be written by itself on a line. Examples are assignments, def to define functions, and while to start a loop.

An expression is code that calculates a value, and can be used as part of another statement or expression. Examples are arithmetic calculations, function calls, literal values, and comprehensions.

Since assignments are not expressions, you can't use them as part of another statement. For instance, you can't write:

You have to do this in two steps:

Python 3.8 added a new operator := . This is the operator for an assignment expression , described in detail in PEP-572 , which can be used as above:

Barmar's user avatar

  • The assignment is not an operator in Python, right? –  user13595466 Commented May 22, 2020 at 12:20
  • That's correct. It's part of the syntax of an assigment statement. –  Barmar Commented May 22, 2020 at 12:24
  • Hey, I liked your way of answering the question. Please answer this one too. stackoverflow.com/q/61952036/13595466 –  user13595466 Commented May 22, 2020 at 12:43
  • @anarchy No, not at all. I am using this to ameliorate my perspicaciousness by people who are ready to purvey chasmic insight. –  user13595466 Commented May 22, 2020 at 12:56
  • Please answer this question: stackoverflow.com/q/62073294/13595466 . The documentation has used the term assignment operators . –  user13595466 Commented May 29, 2020 at 6:38

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

  • The Overflow Blog
  • This developer tool is 40 years old: can it be improved?
  • Unpacking the 2024 Developer Survey results
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Introducing an accessibility dashboard and some upcoming changes to display...
  • Tag hover experiment wrap-up and next steps

Hot Network Questions

  • A book about a baby, these nurses(?) and some kind of portal that opens only every few years
  • What are those small notes below other ones?
  • She's a black belt in judo
  • Question about Three mobile operator cellular network coverage in Oban UK
  • What type of concept is "mad scientist"?
  • A finance broker made me the primary instead of a co-signer
  • English equivalent to the famous Hindi proverb "the marriage sweetmeat: those who eat it regret, and those who don't eat it also regret"?
  • Compatibility of SD-Card-Readers with Ipads or Iphones
  • Carbon steel griddle spanning 2 electric burners?
  • Safe(r) / Easier Pointer Allocation Interface in C (ISO C11)
  • Is threatening to go to the police blackmailing?
  • High-precision solution for the area of a region
  • Discrepancy with a result from Peskin & Schroeder's QFT
  • What would "doctor shoes" have looked like in "Man on the Moon"?
  • "Seagulls are gulling away."
  • When are these base spaces isomorphic?
  • Refereeing papers by people you are very close to
  • Error using \verb in a footnote in Beamer
  • Did Einstein say the one-way speed-of-light is "not a fact of nature"?
  • Design patterns - benefits of using with Apex code
  • What's the translation of swiftboating in French?
  • Significance of negative work done
  • Small adjustment or fix to a toilet float to fix constant draining?
  • When/why did software only engines overtake custom hardware?

assignment statement definition computer

Browse Course Material

Course info, instructors.

  • Prof. Eric Grimson
  • Prof. John Guttag

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Programming Languages

Introduction to Computer Science and Programming

Assignments.

facebook

You are leaving MIT OpenCourseWare

IMAGES

  1. PPT

    assignment statement definition computer

  2. PPT

    assignment statement definition computer

  3. PPT

    assignment statement definition computer

  4. 1.4. Expressions and Assignment Statements

    assignment statement definition computer

  5. PPT

    assignment statement definition computer

  6. PPT

    assignment statement definition computer

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

    Assignment Kenneth Leroy Busbee. Overview. 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] Discussion. The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable).

  5. PDF Resource: Variables, Declarations & Assignment Statements

    definition, as explained later). Assignment (continued) An important fact about variables is that declaring them only says how they are used. They don't start out with any value unless initialized, and they don't get any value until you assign one. So in the examples in the last section the assignment statements, such as

  6. The Assignment Statement

    The meaning of the first assignment is computing the sum of the value in Counter and 1, and saves it back to Counter. Since Counter 's current value is zero, Counter + 1 is 1+0 = 1 and hence 1 is saved into Counter. Therefore, the new value of Counter becomes 1 and its original value 0 disappears. The second assignment statement computes the ...

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

  8. 1.4. Expressions and Assignment Statements

    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. The value of the expression (which can contain math operators and other variables) on the right of the = sign is stored in the variable ...

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

  10. 2. Assignment Statements

    Assignment Statements. One of the most common statements (instructions) in C++ is the assignment statement, which has the form: destination = expression ; = is the assignment operator. This statement means that the expression on the right hand side should be evaluated, and the resulting value stored at the desitnation named on the left.

  11. PDF The Assignment Statement

    the computer does the work of figuring out where in memory the current value of the variable with that name is stored. Form variable = expression; where variable is a valid C++ identifier, the assignment operator (=) is an equal sign, and expression is either: • a constant (e.g. 4, 2.89, 'r')

  12. Variables and assignment (video)

    An assignment statement starts with the name of the variable on the left hand side. Then an equal sign, also called the assignment operator. And on the right hand side, the value to be stored. We read this statement as the variable view_count is assigned the value 324. When the computer executes this instruction, it'll go off to its short-term ...

  13. Different Forms of Assignment Statements in Python

    Multiple- target assignment: x = y = 75. print(x, y) In this form, Python assigns a reference to the same object (the object which is rightmost) to all the target on the left. OUTPUT. 75 75. 7. Augmented assignment : The augmented assignment is a shorthand assignment that combines an expression and an assignment.

  14. Assignment Statements

    In C, the assignment operator is ``='' instead. For example, the C statement: ankle_x = 0.0; assigns the (floating point) value zero to the (floating point) variable ankle_x. Go through the program and locate all of the assignment statements. Remember that assignment is not the same thing as equality or definition. For example, consider the ...

  15. Assignment Statement

    Assignment statements are usually read in reverse order from what we are use to in math class. A variable on the left side of the assignment statement will receive the value that is on the right hand side of the assignment statement. Note that different programming languages use different symbols to represent the assignment statement (for ...

  16. Difference between declaration statement and assignment statement in C

    Declaration: int a; Assignment: a = 3; Declaration and assignment in one statement: int a = 3; Declaration says, "I'm going to use a variable named "a" to store an integer value."Assignment says, "Put the value 3 into the variable a." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts with, rather than changing the value.

  17. Assignment

    Term: Assignment. In programming, an assignment statement is used to set or copy a value into a variable. Go Back. Student. Teacher. Learn.

  18. Statement (computer science)

    Statement (computer science) In computer programming, a statement is a syntactic unit of an imperative programming language that expresses some action to be carried out. [1] A program written in such a language is formed by a sequence of one or more statements. A statement may have internal components (e.g. expressions ).

  19. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators.This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.

  20. What is meant by assignment is a statement in Python?

    1. A statement is code that tells the computer to do something. A statement has to be written by itself on a line. Examples are assignments, def to define functions, and while to start a loop. An expression is code that calculates a value, and can be used as part of another statement or expression. Examples are arithmetic calculations, function ...

  21. Assignments

    Assignments. pdf. 98 kB Getting Started: Python and IDLE. file. 193 B shapes. file. 3 kB subjects. file. 634 kB words. pdf. 52 kB ... Computer Science. Programming Languages; Over 2,500 courses & materials Freely sharing knowledge with learners and educators around the world.