Python Variables and Constants
Python Variables
A variable is a named location used to store data in memory.
Variables can be thought of as a container of data that can be modified later in the program.
For example, create a variable called salary and assign the value 1500:
salary = 1500
In addition, it is possible to replace the value of a variable at any time:
salary = 2000
salary = 1750.99
Fundamental points
- Python does not have a command to declare a variable, because a variable is automatically created the moment you assign it a value.
- Python is a type-inferred language, so you don't have to explicitly define the variable type. The Python interpreter automatically knows the real time of a variable.
- Variables do not need to be declared with a particular
typeand they can also change type after being set.
More in deep, Python doesn't actually assign values to the variables. Instead, it assigns the reference of the object(value) to the variable.
Assigning values to Variables in Python
The assignment operator = is used to assign a value to a variable.
For example, assign a value tutorialreference.com to the variable tutorial_website and then print out the value assigned to tutorial_website
tutorial_website = "tutorialreference.com`"
print(tutorial_website)
Changing the value of a variable
The assignment operator = is also used to change a value to a variable.
tutorial_website = "example.com"
print(tutorial_website) # print "example.com"
# assigning a new value to website
tutorial_website = "tutorialreference.com"
print(tutorial_website) # print "tutorialreference.com"
Assigning multiple values to multiple variables
If you want to assign different value to multiple variables at once, you can do in this way:
a, b, c = 1, 2.3, "Hello World"
print(a) # print 1
print(b) # print 2.3
print(c) # print "Hello World"
If you want to assign the same value to multiple variables at once, you can do in this way:
x = y = z = "same value"
print (x) # print "same value"
print (y) # print "same value"
print (z) # print "same value"