Python Variables

A variable is a storage area. You can think about variables like temporary boxes in a computer’s memory to store data. Python uses variable to store different type of Data.

For example, if we want to store our name in a python code and then see it, we can use a python variable to store our name.

Python variable syntax

To declare a variable you have to follow this syntax:

variableName = value

Python variable example

  • In the above example, we have created a variable named x and assigned it a value of 23. As 23 is a number value (called integer data type) so we don’t need to place it in double quotes.
  • We have created a second variable named myName and assigned it a value of  John. As John is a text (string data type) so we have placed it inside double quotes.
  • To show the value of x or myName variable, we just place it inside the print function.
  • Notice, how we can directly show messages using print function and also combine variable with them.

Rules for naming variable

  • variables’ names are case sensitive. It means that a variable named MyVariable is different from a variable named myvariable
  • you can use alphanumeric characters and underscores (A-z, 0-9, and _ )
  • no spaces in variable names
  • the first character of a variable name can be a letter or an underscore (no numbers)
  • variables in Python don’t need any keyword. In some other languages when we create variables, we nee to use keyword to specify that we are creating a variable.
  • Variables values in Python don’t need to show data type. In some other programming languages we specify what type of value we intend to assign to a variable. Python can read the value and assign it a data type automatically, for example, it knows that this is string “Hello” and this is an integer 23 and this is a float 23.45

Rules for variable values

  • you can assign a value to a variable using the assignment operator (=)
  • if the value is a piece of text (a string) you have to wrap the value in between quotation marks
  • if the name of the variable contains more than one word, please use lower camel case notation (e.g. thisIsMyName or varNameHere). This is not mandatory but an easy way to use one style for all variable names.

Variables declaration and datatype

Unlike other programming languages, Python is a loosely typed language. For this reason you do not have to declare a data type while declaring a new variable. While variables do not have specific types, Python still maintains the concept of a type.

The principal types in Python are:

  • Integer (e.g. 4)
  • Float (e.g. 2.3)
  • String (e.g. “dog”)
  • Boolean (true or false)