• 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

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

Assignment Statement

The assignment statement is an instruction that stores a value in a variable . You use this instruction any time you want to update the value of a variable.

An assignment statements assigns a value to a variable

The assignment statement performs two actions. First, it calculates the value of the expression (calculation) on the right-hand side of the assignment operator (the = ). Once it has the value, it stores the value (assigns it) to the variable on the left-hand side of the assignment operator.

Assignment Statement — when, why, and how

When you create a variable, you have identified a piece of information that you want to be able to change as your program runs. Whenever you need to give a variable an initial or new value, you use an assignment statement .

The assignment statement uses the assignment operator = . Whatever is on the right-hand side of = represents the value to be assigned. This could be a literal , a method call , or any other expression . On the left-hand side you write the identifier of the variable you want to store this value in.

For example, you might decide to ask the user for their name. First, you need a variable to store the value. You might decide to call this variable name . Then, the assignment statement lets you read a response from the user and store it in that variable. In this case, the right-hand side of the assignment would be a call to ReadLine , which reads input from standard in and returns it to you. The left-hand side would be the identifier of our variable, name .

It is important to remember that every assignment statement has 2 actions :

  • Calculate the value on the right-hand side
  • Store it in the variable on the left-hand side.

The ordering of these actions allow you to update the value of a variable using an expression involving the variable being updated. This can be very useful. For example, you might want to update the value of a variable storing the number of steps you have taken today.

In C# the assignment operator is = . Most assignment statements are written using = , with an identifier on the left-hand side and an expression on the right-hand side. The assignment operator can optionally be modified with + , - , * , or / , which are shorthands for adding to, subtracting from, multiplying, and dividing the variable identified on the left-hand side of the statement.

Some assignment statements are written without = . These are assignment statements using increment ( ++ ) or decrement ( -- ), which allow you to add or remove one from a variable’s current value.

For example, x = x - 1 , x -= 1 , and x-- are all assignment statements which do the same thing — assign the variable x a new value that is one lower than its current value.

Basic assignment statement

In this example we use ReadLine to get input from the user and store it in a name variable.

Shorthand assignment statements

The following code shows an example of how to use some of the shorthand assignment statements.

If you ran the above code and entered 17 as the start count you should get this output:

You do not always need to store values in variables. Sometimes you can just use the value and then forget it. For example, in the above code, we read the initial count from the user. This requires us to read it as text, and then convert that text to a number. Given that we do not ever use the details in line again, we do not need to create this variable in the first place. Instead, we could pass the value to the convert function directly as shown below.

Assignment statement up close

The following sliders show how the assignment statement works in detail. These are both relatively simple programs, but notice how much is going on behind the scenes!

Assigning an int division result to an int variable

Assigning an int division result to a double variable.

logo

Python Numerical Methods

../_images/book_cover.jpg

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

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

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

Variables and Assignment ¶

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

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

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

TRY IT! List all the variables in this notebook

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

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

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

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

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

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

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

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

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

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

Assignment Statements

The last thing we discussed in the previous unit were variables. We use variables to store values of an evaluated expression. To store this value, we use an assignment statement . A simple assignment statement consists of a variable name, an equal sign ( assignment operator ) and the value to be stored.

a in the above expression is assigned the value 7.

Here we see that the variable a has 2 added to it's previous value. The resulting number is 9, the addition of 7 and 2.

To break it down into easy steps:

  • a = 7 -> Variable is initialized when we store a value in it
  • a = a + 2 -> Variable is assigned a new value and forgets the old value

This is called overwriting the variable. a 's value was overwritten in the process. The expression on the right of the = operator is evaluated down to a single value before it is assigned to the variable on the left. During the evaluation stage, a still carries the number 7 , this is added by 2 which results in 9 . 9 is then assigned to the variable a and overwrites the previous value.

Another example:

Hence, when a new value is assigned to a variable, the old one is forgotten.

Variable Names

There are three rules for variable names:

  • It can be only one word, no spaces are allowed.
  • It can use only letters, numbers, and the underscore (_) character.
  • It can’t begin with a number.
Note: Variable names are case-sensitive. This means that hello, Hello, hellO are three different variables. The python convention is to start a variable name with lowercase characters. Tip: A good variable name describes the data it contains. Imagine you have a cat namely Kitty. You could say cat = 'Kitty' .

What would this output: 'name' + 'namename' ? a. 'name' b. 'namenamename' c. 'namename' d. namenamename

What would this output: 'name' * 3 a. 'name' b. 'namenamename' c. 'namename' d. namenamename

results matching " "

No results matching " ".

an assignment statement stores what in a variable

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

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

CS105: Introduction to Python

Variables and assignment statements.

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

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

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

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

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

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

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

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

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

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

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

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

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

Choosing variable names

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

Note about syntax

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

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

Syntax and Sema ntic Errors

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

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

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

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

Distinguishing Expressions and Assignments

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

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

Creative Commons License

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

Learn C++

1.4 — Variable assignment and initialization

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

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

Variable assignment

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

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

Here’s an example where we use assignment twice:

This prints:

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

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

Initialization

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

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

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

Different forms of initialization

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

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

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

Default initialization

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

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

Copy initialization

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

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

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

For advanced readers

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

Direct initialization

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

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

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

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

List initialization

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

List initialization comes in three forms:

As an aside…

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

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

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

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

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

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

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

Best practice

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

Author’s note

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

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

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

Value initialization and zero initialization

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

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

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

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

Initialize your variables

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

Related content

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

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

Initialize your variables upon creation.

Initializing multiple variables

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

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

You can initialize multiple variables defined on the same line:

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

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

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

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

Unused initialized variables warnings

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

Consider the following innocent looking program:

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

and the program fails to compile.

There are a few easy ways to fix this.

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

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

The [[maybe_unused]] attribute C++17

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

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

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

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

The following program should generate no warnings/errors:

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

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

Question #1

What is the difference between initialization and assignment?

Show Solution

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

Question #2

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

Direct list initialization (aka. direct brace initialization).

Question #3

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

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

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

You should prefer value initialization to default initialization.

guest

Python Variables and Assignment

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

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"

Now that we’ve learned how to use the print(expression) statement, let’s focus on the next major concept in Python, as well as any other programming language: variables .

The word variable is traditionally defined as a value that can change. We’ve seen variables like $ x $ used in Algebraic equations like $ x + 4 = 7 $ to represent unknown values that we can try to work out. In programming a variable is defined as a way to store a value in a computer’s memory so we can retrieve it later. One common way to think of variables is like a box in the real world. We can put something in the box, representing our value. Likewise, we can write a name on the side of the box, corresponding to our variable’s name. When we want to use the variable, we can get the value that it currently stores, and even change it to a different value. It’s a pretty handy mental metaphor to keep in mind!

In a later lab, we’ll learn how to use operators to manipulate the values stored in variables, but for right now we’re just going to focus on storing and retrieving data using variables.

Creating Variables

To use a variable, we must first create one. In Python, we create a variable in a special type of statement called an assignment statement . The basic structure for an assignment statement is a = expression . When our Python interpreter runs this statement, it will first evaluate expression into a single value. Then, it will store that value in the variable named a .

For example, let’s consider the Python statement:

In that statement, we are storing the string value "Hello World" in the variable named x . Pretty handy!

Now, let’s cover some important rules related to assignment statements:

  • Assignment statements are always written with the variable on the left, and an expression on the right. We cannot reverse the statement and say expression = x in programming like we can in math. In mathematical terms, this means an assignment statement is not commutative.
  • The left side of an assignment statement must be a location where a value can be stored. For now, we’re just going to work with single variables, so we don’t have to worry about this yet. In a later lab, we’ll introduce lists as another way to store data, and we’ll revisit this rule.
  • The right side of an assignment statement must be an expression that evaluates to a value that can be stored in the location given on the left side. Right now we’re only working with string values, so we don’t have to worry about this rule yet. We’ll come back to it in a future lab.

Using Variables

Once we’ve created a variable, we can use it in any expression to recall the current value stored in the variable. So, we can extend our previous example to store a value in a variable, and then use the print(expression) statement to display it’s value. Here’s what that would look like in Python:

Notice that we don’t put quotation marks " around the variable x in the print(expression) statement. This is because we want to display the value stored in the variable x , not the string value "x" . So, when we run this code, we should get this output:

To confirm, feel free to try it yourself! Copy the code above into a Python file, then use the python3 command in the terminal to run the file and see what it does. Running these examples is a great way to learn how a computer actually executes code, and it helps to confirm that your “mental model” of a computer matches how a real computer operates.

Updating Variable Values

Python also allows us to change the value stored in a variable using another assignment statement . For example, we can write some Python code that uses the same variable to print multiple outputs:

When we run this code, we’ll see the following output:

So, just like we learned above, when we evaluate a variable in code, it will result in the value currently stored in that variable at the time it is evaluated. So, even though we are printing the same variable twice, each time it is storing a different value. Recall that this is why we call items like a a variable - their value can change!

Variable Names

Finally, Python has a few simple rules that determine what names can be used for variables in our code. Let’s quickly review those rules, as well as some conventions that most Python developers follow when naming variables.

First, the rules that must be followed:

  • Variable names must begin with either a letter or an underscore _ .
  • Variable names may only contain letters, numbers, and underscores _ .
  • Variable names are case sensitive.

Next, here are the conventions that most Python developers follow for variable names, which we will also follow in this course:

  • Variable names beginning with an underscore _ have a special meaning. So, we won’t create any variables beginning with an underscore right now, but later we’ll learn about what they mean and start using them.
  • Variables should have a descriptive name, like total or average, that makes it clear what the variable is used for.
  • Variables should be named using Snake Case . This means that spaces are represented by underscores _ , as in number_of_inputs
  • tmp or temp are temporary variables.
  • i , j , and k are iterator variables (we’ll learn about those later).
  • x , y , and z are coordinates in a coordinate plane.
  • r , g , b , a are colors in an RGB color system.
  • For example, Python has a print statement, so we should not name a variable print in our language.
  • In general, longer variable names are more useful than short ones, even if they are more difficult to type.

These conventions are not strict requirements enforced by the Python language itself, but they are general rules to help us write code that is meaningful and easy to read.

Finally, don’t forget that some of the code examples in this course will NOT follow these conventions, mainly because long, descriptive variable names might give away the purpose of the code itself. We’ll still follow the rules that are required, but in many cases we’ll use simple variable names so that the focus is learning to read the structure of the code, not inferring what it does based solely on the names of the variables.

Last modified by: Russell Feldhausen May 30, 2023

Variables and Assignment Statements

  • First Online: 23 August 2018

Cite this chapter

Book cover

  • Irv Kalb 2  

5972 Accesses

This chapter covers the following topics:

A sample Python program

Building blocks of programming

Four types of data

What a variable is

Rules for naming variables

Giving a variable a value with an assignment statement

A good way to name variables

Special Python keywords

Case sensitivity

More complicated assignment statements

Print statements

Basic math operators

Order of operations and parentheses

A few small sample programs

Additional naming conventions

How to add comments in a program

Use of “whitespace”

Errors in programs

This is a preview of subscription content, log in via an institution to check access.

Access this chapter

  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
  • Available as EPUB and PDF
  • Compact, lightweight edition
  • Dispatched in 3 to 5 business days
  • Free shipping worldwide - see info

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

Author information

Authors and affiliations.

Mountain View, California, USA

You can also search for this author in PubMed   Google Scholar

Rights and permissions

Reprints and permissions

Copyright information

© 2018 Irv Kalb

About this chapter

Kalb, I. (2018). Variables and Assignment Statements. In: Learn to Program with Python 3. Apress, Berkeley, CA. https://doi.org/10.1007/978-1-4842-3879-0_2

Download citation

DOI : https://doi.org/10.1007/978-1-4842-3879-0_2

Published : 23 August 2018

Publisher Name : Apress, Berkeley, CA

Print ISBN : 978-1-4842-3878-3

Online ISBN : 978-1-4842-3879-0

eBook Packages : Professional and Applied Computing Apress Access Books Professional and Applied Computing (R0)

Share this chapter

Anyone you share the following link with will be able to read this content:

Sorry, a shareable link is not currently available for this article.

Provided by the Springer Nature SharedIt content-sharing initiative

  • Publish with us

Policies and ethics

  • Find a journal
  • Track your research

2. Expressions and Assignment Statements

Recall that an assignment statement is used to store a value in a variable, and looks like this:

When I first introduced assignment statements, I told you that C# requires that the data type of the expression be compatible with the data type of the variable (on the left side). Thus, if x is an int variable, x = 5 is legal, but x = "Jon" is not.

We need to dig into this rule a little bit, because until you understand it well, you will have difficulty when you are working with expressions that include variables of different data types, which happens all the time in C#. There are two parts to consider: "the data type of the expression" and "compatible with the data type of the variable".

2.1. Determining the Data Type of an Expression

An expression, as you know, computes a value, and that value has a data type. By "data type of an expression," I am referring to the data type of the value produced by the expression. For example, the expression 5 + 5 yields the int value 10, and the expression 2.0 * 3.0 yields the double value 6.0.

It's pretty easy to determine the data type of a simple expressions, such as a literal or a single variable. But what happens when you start mixing types? More complicated expressions can present a challenge, but if you learn to tackle them in a systematic way, you can easily analyze them to determine their type. First, here are the two rules governing numeric expressions:

A mathematical expression that consists only of integer types will produce an int result. When a long value is involved, the result is long.

A mathematical expression that contains at least one double or float value will always produce a floating point result. The resulting data type depends on the "largest" data type in the expression. For example, if a double value is involved, then the result is a double. If only float values (and possibly integer values) are used, then the result is a float.

An expression that contains at least one string value will always produce a string result.

Let's take a look at some examples. We'll use the following variables:

Here is the first one:

int1 + int2 - 5

This one is easy. Only int values are involved; the result is an int.

int1 + long1

Still only integer types, but since a long is involved, the result is a long.

long1 + float1 - int2

Since a float is involved, the result must be floating point. No double value, so the result is a float.

int1 + int2 - (long1 * float1) / double2 * float2

Again, since floats and doubles are involved, the result must be a floating point type. Since a double is involved, the result is double.

"Fred weighs " + double1 + " pounds."

Since a string is involved, the result is a string.

2.2. Data Type Compatibility

In an assignment statement, the data type of the expression must be compatible with the data type of the variable being changed. I use the word "compatible" because the two types don't have to be identical. Let me give you an example to explain what I mean.

In this fragment, the compiler would permit the first assignment statement, but not the second. Here's why. An int expression is "assignment compatible" with a double variable, but a double expression is not "assignment compatible" with an int variable. The reason that one is allowed and the other is not has to do with information loss. Any int value can be safely stored in a double variable with no loss of information. However, a double value cannot be safely stored in an int variable, because an int variable cannot hold digits after the decimal point. In other words, C# allows automatic data type conversions any time that information loss is avoided.

Perhaps you have encountered an error message like this:

This is the error that my compiler issued for the second assignment statement above. To avoid errors like this, you must observe the rules on assignment compatibility:

A smaller integer-type expression can be stored in a larger integer-type variable. For example, an int expression can be stored in a long variable.

Any integer-type expression (byte, short, int, long) can be stored in a float or double variable.

A float expression can be stored in a double variable.

Other combinations are not legal.

2.3. Forcing Square Pegs into Round Holes

There are times when you have an expression that produces a result whose type is not compatible with the variable you want to hold the result. In other words, there are legitimate reasons to want to convert data from one type to another. In these cases, you need a way to tell C# to force the conversion, losing information if necessary. You do this with something called a cast. In our example, here's how it would work:

i = (int) d;

When you write a data type in parenthesis in front of an expression, C# computes the result of the expression as it normally would, and then after the result is computed, converts it to the indicated type. For example, if d were 3.2532, the (int) cast would convert the expression to 3, so it can be stored in the int variable. Note that the cast does not affect any variables in the expression; it only affects the result of the expression. So d's value is not changed.

The cast is actually an operator. It has a very high precedence -- higher than all the arithmetic operators. When your expression is more complicated than a single variable, you should enclose the expression in parenthesis. Take the following as an example:

This assignment statement is invalid, because the type of the expression is double. You might try to correct the problem by adding a cast:

i = (int) i + d;

But the compiler will still complain that the expression produces a double. What's going on here? To understand the problem, take a look at the assignment statement rewritten with the expression fully parenthesized:

i = ((int) i) + d;

This statement is equivalent to the previous one, and highlights the problem. The cast (int) has higher precedence than the + operator, so it affects only the value of i, not the value of (i + d). In effect, the cast does nothing. There are two ways to fix the problem.

Parenthesize the expression like this:

i = (int) (i + d);

Now the cast applies to the double value produced by (i + d).

Change the order of the operands:

i = (int) d + i;

Here, the double value of d is converted to an int before the addition occurs, thus ensuring an int result.

I prefer the first technique, because it is more obvious. In fact, to increase your chances of using the cast correctly, I suggest that you always parenthesize the expression being cast, whether it's needed or not.

2.4. More on Casting

The cast can occur in places other than the beginning of an expression. For example, consider this expression:

(total / num - 2) * 2

If total and num are both int variables, the result is an int. The integer division will likely yield undesirable results. You might think adding a cast at the beginning would solve the problem:

(double) (total / num - 2) * 2

But it doesn't. To understand why it doesn't help, fully parenthesize the expression according to operator precedence:

((double) ((total / num) - 2)) * 2

Now, follow the steps the computer would follow when evaluating the expression:

Compute total / num, yielding an int result (oops).

Subtract 2, yielding an int

Convert the result to a double

Multiply by 2, yielding a double

The problem occurred in the very first step. We want that division to yield a double, not an int. To fix the problem, we must move the cast inside the parentheses:

((double) total / num - 2) * 2

Now, fully parenthesized, the expression looks like this:

((((double) total) / num) - 2) * 2

And the computer evaluates it like this:

Take the value of total and convert to a double.

Divide the result by num, yielding a double.

Subtract 2, yielding a double

2.5. String Conversions

There's an important limitation on casts: you cannot use a cast to convert between a string type and a numeric type. For example, the following won't work:

To convert between string and numeric values, you must use methods in the Convert class. Here's a fragment that shows how to do it:

When you have a numeric value that you need to convert to a string, use the Convert.ToString( ) method. It accepts a numeric expression and returns the string equivalent.

Converting from Strings to numeric types requires the use of the ToDouble and ToInt32 methods in the Convert class. Note that conversion will fail with a runtime error if the string contains any spaces or other non-numeric characters. I will discuss how to handle this problem gracefully in a later chapter.

2.6. Increment, Decrement, and Modulus Operations

You'll find that adding 1 to a variable is an extremely common operation in programming. Subtracting 1 from a variable is also pretty common. You might perform the operation of adding 1 to a variable with assignment statements such as:

The effect of the assignment statement x = x + 1 is to take the old value of the variable x, compute the result of adding 1 to that value, and store the answer as the new value of x. The same operation can be accomplished by writing x++ (or, if you prefer, ++x). This actually changes the value of x, so that it has the same effect as writing "x = x + 1". The statement above could be written

Similarly, you could write x-- (or --x) to subtract 1 from x. That is, x-- performs the same computation as x = x - 1. Adding 1 to a variable is called incrementing that variable, and subtracting 1 is called decrementing. The operators ++ and -- are called the increment operator and the decrement operator, respectively. These operators can be used on variables belonging to any of the numerical types and also on variables of type char.

Sometimes you want to increment or decrement a variable by more than 1. The += and -= operations come in handy for this purpose. Here's an example of what you can do:

counter += 2;

This is basically an abbreviation for

counter = counter + 2;

You can use any expression on the right-hand side of the += operator. For example,

counter += (num * 5) + 2;

would be equivalent to writing

counter = counter + ((num * 5) + 2);

All of the binary arithmetic operators, including +, -, *, /, and the modulo operator (introduced next) can be used in this way. For example, to multiply a number by 3, you could write:

goals *= 3;

In addition to the standard +, -, *, and / operators, C# also has an operator for computing the remainder when one integer is divided by another. This operator is the modulo operator, indicated by %. If A and B are integers, then A % B represents the remainder when A is divided by B. For example, 7 % 2 is 1, while 34577 % 100 is 77, and 50 % 8 is 2. A common use of % is to test whether a given integer is even or odd. N is even if N % 2 is zero, and it is odd if N % 2 is 1. More generally, you can check whether an integer N is evenly divisible by an integer M by checking whether N % M is zero.

2.7. Precedence Rules

If you use several operators in one expression, and if you don't use parentheses to explicitly indicate the order of evaluation, then you have to worry about the precedence rules that determine the order of evaluation. (Advice: don't confuse yourself or the reader of your program; use parentheses liberally.) Here is a listing of the operators discussed in this section (along with some we haven't discussed yet), listed in order from highest precedence (evaluated first) to lowest precedence (evaluated last):

Table 4.4. Operator Precedence in C#

Operators on the same line (like * and /) have the same precedence. When they occur together, unary operators and assignment operators are evaluated right-to-left, and the remaining operators are evaluated left-to-right. For example, A*B/C means (A*B)/C, while A=B=C means A=(B=C). (Tip: You can write things like X = Y = 0 to assign several values the same value with one statement.)

IMAGES

  1. 1.4. Expressions and Assignment Statements

    an assignment statement stores what in a variable

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

    an assignment statement stores what in a variable

  3. PPT

    an assignment statement stores what in a variable

  4. Assignment Statement in Python

    an assignment statement stores what in a variable

  5. PPT

    an assignment statement stores what in a variable

  6. Variable Assignment in Python

    an assignment statement stores what in a variable

VIDEO

  1. Topic 7 assignment Analysis of Statement of Cash Flow

  2. If Statement Assignment

  3. emotion detail assignment a statement major line

  4. _DSDV_Discuss Structure, Variable Assignment Statement in verilog

  5. Chapter 1 Sample Program

  6. Switch Statement Assignment

COMMENTS

  1. PDF 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 blank after the = sign but ...

  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. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

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

  5. Assignment Statement

    The assignment statement is an instruction that stores a value in a variable. You use this instruction any time you want to update the value of a variable. The assignment statement performs two actions. First, it calculates the value of the expression (calculation) on the right-hand side of the assignment operator (the = ).

  6. Variables and Assignment

    Variables and Assignment¶. When programming, it is useful to be able to store information in variables. A variable is a string of characters and numbers associated with a piece of information. The assignment operator, denoted by the "=" symbol, is the operator that is used to assign values to variables in Python.The line x=1 takes the known value, 1, and assigns that value to the variable ...

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

  8. Variables and Assignment Statements: Assignment Statements

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

  9. Assignment Statements · Pythonium

    To store this value, we use an assignment statement. A simple assignment statement consists of a variable name, an equal sign (assignment operator) and the value to be stored. >>> a = 7 # -> Assignment statement a in the above expression is assigned the value 7. >>> a = a + 2 >>> a 9 Here we see that the variable a has 2 added to it's previous ...

  10. 1.4. Expressions and Assignment Statements

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

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

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

  13. Variables, Expressions, and Assignments

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

  14. 1.4

    1.4 — Variable assignment and initialization. Alex March 22, 2024. In the previous lesson ( 1.3 -- Introduction to objects and variables ), we covered how to define a variable that we can use to store values. In this lesson, we'll explore how to actually put values into variables and use those values. As a reminder, here's a short snippet ...

  15. Python Variables and Assignment

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

  16. PDF Resource: Variables, Declarations & Assignment Statements

    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 whole thing is the assignment statement). You get the idea from

  17. Programming

    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. More info . We've already seen many examples of assignment. Assignment means: "storing a value (of a particular type) under a variable name".

  18. Variables :: Introduction to Python

    In Python, we create a variable in a special type of statement called an assignment statement. The basic structure for an assignment statement is a = expression. When our Python interpreter runs this statement, it will first evaluate expression into a single value. Then, it will store that value in the variable named a.

  19. Variables and Assignment Statements

    In an assignment statement, everything on the right of the equals sign is calculated, and the result is assigned to the variable on the left. Whenever you see an assignment statement, you can read or think of the equals sign as meaning any of the following: "is assigned". "is given the value of". "is set to". "becomes".

  20. 2. Expressions and Assignment Statements

    2. Expressions and Assignment Statements. Recall that an assignment statement is used to store a value in a variable, and looks like this: variable-name = expression; When I first introduced assignment statements, I told you that C# requires that the data type of the expression be compatible with the data type of the variable (on the left side ...

  21. 2. Variables, expressions and statements

    2.1. Values and data types¶. A value is one of the fundamental things — like a letter or a number — that a program manipulates. The values we have seen so far are 4 (the result when we added 2 + 2), and "Hello, World!".. These values are classified into different classes, or data types: 4 is an integer, and "Hello, World!" is a string, so-called because it contains a string of letters.

  22. pythonForEveryone Ch2 Flashcards

    When a value such as 6 or 0.355 occurs in a Python program, it is called a number literal. Variable and Types. A variable in Python can store a value of any type. The data type is associated with the value, not the variable. Once a variable is initialized with a value of a particular type, it should always store values of that same type.