The word variable in itself speaks dynamism. It’s value, quantity, and essence, can change from time to time. In programming as well, your value changes from time to time.
In Python, variables are used to store data, like string, numbers, date-time etc. When you create a variable, a little portion is reserved within your computer memory to store this value of the variable. The value of a variable has to be assigned by you.
Types of variables
Python has five standard data types:
Creating a variable
In Python, a variable does not need to be declared while creating or before adding a value to it. Python variables are usually dynamically typed, that is, the type of the variable is interpreted during run-time and you don’t need to specify the type of a variable.
The following program shows how to use string and integer type variables:
x = 10 # Integer variable
y = “Hello World” # String variable
# Displaying variables value
Checking the type of a variable
With the method type(), we can know the type of variable we have created. It could be int, str, is used to get the type of a created variable.
var1 = ‘Hello World’
Important Rules for Variables
- Variables cannot start with a number, but can be Alpha-Numeric. Additionally, they also support underscores – hence the total range is from A-Z, a-z, 0-9, and _.
- Variables are strictly case-sensitive, thus You and you are different variables
Data Type Conversion
Sometimes, due to functional reasons, we need to convert variables. For this purpose, python is quite straight forward. To convert between types, you simply use the type name as a function. A common industry jargon is ‘Type Casting‘.
There are several built-in functions to perform conversion from one data type to another. These functions return a new object, with the changed data type 🙂.
|Sr.No.||Function & Description|
|1||int(x ): Converts x to an integer.|
|2||long(x): Converts x to a long integer.|
|3||float(x): Converts x to a floating-point number.|
|4||str(x): Converts object x to a string representation.|
|5||tuple(s): Converts s to a tuple.|
|6||list(s): Converts s to a list.|
|7||set(s): Converts s to a set.|
|8||dict(d): Creates a dictionary. d must be a sequence of (key,value) tuples.|
|9||chr(x): Converts an integer to a character.|
Your info guy.