In this tutorial we will learn to work with variables in Python.
Variables are named memory locations which holds some value. And these values can be changed later.
We don't have to explicitly declare variables in Python to reserve memory space. They are automatically declared and memory is allocated when a variable is assigned a value.
Following are the rules that we must remember while naming a variable in Python.
Following are some of the valid variable names.
Following are invalid variable names.
1account # can't start with digit
user-name # con't use -
Variables are case-sensitive in Python which means lowercase variable name and uppercase variable name are treated differently.
Following variables are treated differently even though they are the same word.
score = 10
SCORE = 10
We use the = sign to assign value to a variable.
In the following example we are assigning integer value to a variable x.
x = 10
We can assign same value in one go to multiple variables in Python.
In the following example we are assigning value 10 to the three variables.
x = y = z = 10
We can assign different values in one go to different variables in Python.
In the following example we are assigning 1 to a, 3.14 to b, 'Hello World' to msg and 1+2j to c.
1 to a
3.14 to b
'Hello World' to msg
1+2j to c
a, b, msg, c = 1, 3.14, 'Hello World', 1 + 2j
If there are two variables and we want to swap their values without using any third variable then we can write the following code in Python.
var1, var2 = var2, var1
In the following example we have two variables a and b and they hold values 10 and "Happy" respectively and we are swapping their values.
a = 10
b = "Happy"
print("before:", a, b)
a, b = b, a
print("after:", a, b)
We will get the following output.
before: 10 Happy
after: Happy 10
Have fun learning :-)
Copyright © 2014 - 2019 DYclassroom. All rights reserved.
rendered in 0.0143 sec