Python Variables and Constants#

In this class, you will learn about Python variables, constants, literals and their use cases.

Python Variables#

A variable is a named location used to store data in the memory. Variable also known as identifier and used to hold value. It is helpful to think of variables as a container that holds data that can be changed later in the program.

>>>number = 90

You can think of variables as a bag to store books in it and that book can be replaced at any time.

>>>number = 90
>>>number = 9.1

Initially, the value of number was 90. Later, it was changed to 9.1.

Note: In Python, we don’t actually assign values to the variables. Instead, Python gives the reference of the object(value) to the variable.

In Python, we don’t need to specify the type of variable because Python is a type infer language and smart enough to get variable type.

Python Variable Name Rules

  • A variable name must start with a letter A-z or the underscore _ character

  • A variable name cannot start with a number 0-9

  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

  • Variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME) are different variables). It is recomended to use lowercase letters for variable name.

Let us see valid variable names#

firstname
lastname
age
country
city
first_name
last_name
capital_city
_if          # if we want to use reserved word as a variable
year_2021
year2021
current_year_2021
birth_year
num1
num2

Invalid variables names:

first-name
first@name
first$name
num-1
1num

Python developers use snake case(snake_case) variable naming convention. We use underscore character after each word for a variable containing more than one word (eg. first_name, last_name, engine_rotation_speed). The example below is an example of standard naming of variables, underscore is required when the variable name is more than one word.

Assigning values to Variables in Python#

Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance

Example 1: Declaring and assigning value to a variable#

number = 90
number = 9.1
number
9.1
website = "github.com"  # `website` is my variable and `github.com` is an argument
print(website)
github.com

In the above program, we assigned a value github.com to the variable website. Then, we printed out the value assigned to website i.e. github.com.

Note: Python is a type-inferred language, so you don’t have to explicitly define the variable type. It automatically knows that github.com is a string and declares the website variable as a string.

print('Hello',',', 'World','!') # it can take multiple arguments, 4 arguments have been passed
Hello , World !
first_name = 'Milaan'
last_name = 'Parmar'
country = 'Finland'
city = 'Tampere'
age = 96
is_married = True
skills = ['Python', 'Matlab', 'JS', 'C', 'C++']
person_info = {
   'firstname':'Milaan',
   'lastname':'Parmar',
   'country':'Finland',
   'city':'Tampere'
    }

Let us print and also find the length of the variables declared at the top:

# Printing the values stored in the variables

print('First name:', first_name)
print('First name length:', len(first_name))
print('Last name: ', last_name)
print('Last name length: ', len(last_name))
print('Country: ', country)
print('City: ', city)
print('Age: ', age)
print('Married: ', is_married)
print('Skills: ', skills)
print('Person information: ', person_info)
First name: Milaan
First name length: 6
Last name:  Parmar
Last name length:  6
Country:  Finland
City:  Tampere
Age:  96
Married:  True
Skills:  ['Python', 'Matlab', 'JS', 'C', 'C++']
Person information:  {'firstname': 'Milaan', 'lastname': 'Parmar', 'country': 'Finland', 'city': 'Tampere'}

Example 2: Declaring multiple variables in one line** using comma , and semicolon ;#

a, b, c = 6, 9.3, "Hello"

print (a)
print (b)
print (c)
6
9.3
Hello
a = 1; b = 2; c = 3
print(a,b,c)  # outout: 1 2 3
a,b,c         # outout: 1 2 3
1 2 3
(1, 2, 3)
first_name, last_name, country, age, is_married = 'Milaan', 'Parmar', 'Finland', 96, True

print(first_name, last_name, country, age, is_married)
print('First name:', first_name)
print('Last name: ', last_name)
print('Country: ', country)
print('Age: ', age) # Don't worry it is not my real age ^_^
print('Married: ', is_married)
Milaan Parmar Finland 96 True
First name: Milaan
Last name:  Parmar
Country:  Finland
Age:  96
Married:  True

If we want to assign the same value to multiple/chained variables at once, we can do this as:

x = y = z = "same"

print (x)
print (y)
print (z)
same
same
same

The second program assigns the same string to all the three variables x, y and z.

p = q = r = 300   # Assigning value together
print(p, q, r)    # Printing value together
300 300 300

Example 3: Changing the value of a variable#

website = "github.com"
print(website)

# assigning a new variable to website
website = "baidu.com"

print(website)
github.com
baidu.com

In the above program, we have assigned github.com to the website variable initially. Then, the value is changed to baidu.com.

n=300
print(n)
300
m=n
print(n)

m = 1000   # assigning a new value to n
print(m)
300
1000
# Declare & Redeclare variables
m = "Python is Fun"
m = 10
print (m)
10

Constants#

A constant is a type of variable whose value cannot be changed.

Assigning value to constant in Python#

In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file.

Inside the module, constants are written in all capital letters and underscores separating the words.

Example 1: Declaring and assigning value to a constant#

Create a constant.py:

>>>PI = 3.14
>>>GRAVITY = 9.8

Create a main.py:

>>>import constant
>>>print(constant.PI)
>>>print(constant.GRAVITY)

3.14
9.8

In the above program, we create a constant.py module file. Then, we assign the constant value to PI and GRAVITY. After that, we create a main.py file and import the constant module. Finally, we print the constant value.

Note: In reality, we don’t use constants in Python. Naming them in all capital letters is a convention to separate them from variables, however, it does not actually prevent reassignment.

Rules and Naming Convention for Variables and constants#

  1. Constant and variable names should have a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. For example:

snake_case
MACRO_CASE
camelCase
CapWords
  1. Create a name that makes sense. For example, vowel makes more sense than v.

  2. If you want to create a variable name having two words, use underscore to separate them. For example:

my_name
current_salary
  1. Use capital letters possible to declare a constant. For example:

PI
G
MASS
SPEED_OF_LIGHT
TEMP
  1. Never use special symbols like !, @, #, $ % , etc.

  2. Don’t start a variable name with a digit.

Note: One of the additions to Python 3 was full Unicode support, which allows for Unicode characters in a variable name as well. You will learn about Unicode in greater depth in a future tutorial.

For example, all of the following are valid variable names:

name = "Bob"
Age = 54
has_W2 = True
print(name, Age, has_W2)
Bob 54 True

But this one is not, because a variable name can’t begin with a digit:

1099_filed = False    # cannot start name of a variable with a number.
  File "<ipython-input-16-8cc0f1bdc5ed>", line 1
    1099_filed = False    # cannot start name of a variable with a number.
        ^
SyntaxError: invalid decimal literal

Note that case is significant. Lowercase and uppercase letters are not the same. Use of the underscore character is significant as well. Each of the following defines a different variable:

>>>age = 1
>>>Age = 2
>>>aGe = 3
>>>AGE = 4
>>>a_g_e = 5
>>>_age = 6
>>>age_ = 7
>>>AGe = 8
>>>print(age, Age, aGe, AGE, a_g_e, age, age, AGe)

1 2 3 4 5 6 7 8 
age = 1
Age = 2
aGe = 3
AGE = 4
a_g_e = 5
_age = 6
age_ = 7
AGe = 8
print(age, Age, aGe, AGE, a_g_e, age, age, AGe)
1 2 3 4 5 1 1 8