Data

Variable

Python

 

Defining Variable

Python 2.7
age = 21

name = "Sam"

Variables are defined by assigning values to them.

Here we are defining two variables name and age.

Variable names are:

  • Case sensitive
  • Can contain letters, digits or _
  • Cannot start with a digit
  • Cannot be any of the reserved keywords
 

Variable Types

Python 2.7
booleanVar = True
integerVar = 12
floatingPointVar = 1.618
complexVar = 2j+1
stringVar = "Hello"
listVar = [1, 2, 3]
tupleVar = (1, 2, 3)
rangeVar = range(6)
dictVar = {"name": "Sam", "age": 21}
setVar = {"apple", "banana", "orange"}
frozensetVar = frozenset({1, 2, 3})
byteVar = b"Hello"
bytearrayVar = bytearray(5)
memoryviewVar = memoryview(bytes(5))
noneVar = None

Python built-in Data Types can be categorized like below:

  • Text: str
  • Numeric: int, float, complex
  • Sequence: list, tuple, range
  • Mapping: dict
  • Set: set, frozenset
  • Boolean: bool
  • Binary: bytes, bytearray, memoryview
  • None: None
 

Type Safety

Python 2.7
status = 0

status = "success"

Python unlike C and Java, is not a Type-Safe Language.

It automatically converts the variable to the correct data type, depending on its value.

 

Defining Variables in one line

Python 2.7
x, y, z = None, 7, 12

You can define multiple variables in one statement.

Here, we are creating variables x, y, and z, and initialize x to None, y to 7 and z to 12.

 

Setting Variable value

Python 2.7
age = 21  # defines age with value 21

age = 22  # assign new value 22 to age

Here, we're defining a variable age with value 21, then on the next statement, it assigns a value 22 to it.

 

Getting Variable value

Python 2.7
age = 21

samAge = age + 3   # samAge -> 24

To get the value of a variable, you can simply use its name.