Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

Using variables

You're allowed to use as many variable declarations as you need to achieve your goa;, like this:

 

var = 1

account_balance = 1000.0

client_name = 'John Doe'

print(var, account_balance, client_name)

print(var)

You're not allowed to use a variable which doesn't exist (in other words, a variable that was not assigned a value).

This example will cause an error:

var = 1 print(Var)

We've tried to use a variable named Var, which doesn't have any value (note: var and Var are different entities, and have nothing in common as far as Python's concerned).

REMEMBER

You can use the print() function and combine text and variables using the + operator to output strings and variables, e.g.:

var = "3.8.5"

print("Python version: " + var)

Can you guess the output of the snippet above? 

Python version: 3.8.5

 

Assigning a new value to an already existing variable

How do you assign a new value to an already created variable? In the same way. You just need to use the equal sign.

The equal sign is in fact an assignment operator. Although this may sound strange, Although this may sound strange, the operator has a simple syntax and unambiguous interpretation. 

It assigns the value of its right argument to the left, which the right argument may be an arbitrarily complex expression involving literals, operators and already defined variables. 

Look at the code below:

var = 1

print(var)

var = var + 1

print(var)

The code sends two lines to the console:

1

2

The first line of the snippet creates a new variable named var and assigns 1 to it.

The statement reads: assign a value of 1 to a variable named var.

We can say it shorter: assign 1 to var.

Some prefer to read such a statement as: var becomes 1

The third line assigns the same variable with the new value taken from the variable itself, summed with 1. Seeing a record like that, a mathematician would probably protest - no value may be equal to itself plus one. This is a contradiction. But Python treats the sign = not as equal to, but as assign a value.

So how do you read such a record in the program?

Take the current value of the variable var , add 1 to it and store the result in the variable var

In effect, the value of the variable var has been incremented by one, which has nothing to do with comparing the variable with any value. 

Do you know what the output of the following snippet will be/ 

var = 100

var = 200 + 300

print(var)

500 - why? Well, first the var variable is created and assigned a value of 100. Then, the same variable is assigned a new value: the result of adding 200 to 300, which is 500.

 

Using variables

David Khieu
Module by David Khieu, updated more than 1 year ago

Description

Using variables
No tags specified