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

Creating variables

What can you put inside a variable?

Anything.

You can use a variable to store any value of any of the already presented kinds, and many more of the ones we haven't shown you yet.

The value of a variable is what you have to put into it. It can vary as often as you need or want. It can be an integer one moment, and a float a moment later, eventually becoming a string.

Let's talk now about two important things p how variables are created, and how to put values inside them (or rather - how to give or pass values to them).

REMEMBER

A variable comes into existence as a result of assigning a value to it. Unlike in other languages, you don't need to declare it in any special way.

If you assign any value to a nonexistent variable, the variable will be automatically created. You don't need to do anything else.

The creation (or otherwise -its syntax) is extremely simple: just use the name of the desired variable, then the equal sign (=) and the value you want to put into the variable.

You can put anything inside a variable. 

Take a look at the snippet:

var = 1

print(var)

It consists of two simple instructions:

  • The first of them creates a variable named var, and assigns a literal with an integer value equal to 1. 
  • The second prints the value of the newly created variable to the console.

Note: print() has yet another side to it - it can handle variables too. Do you know what the output of the snippet will be? 

1

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

 

Creating variables

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

Description

Creating variables
No tags specified