English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Variables, Constants, and Literals

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

Python variables

Variables are used to store named positions of data in memory. You can think of variables as containers for data that can be changed later in the program. For example,

number = 10

Here, we created a variable namednumberof the variable. We have assigned the value 10 assigned to the variable number.

You can think of a variable as a bag used to store books, and you can replace the books inside it at any time.

number = 10
number = 1.1

Initially, it was equal to10. Later, it was changed to1.1.

NoteIn Python, we actually do not assign values to variables. Instead, Python provides a reference to the object (value) to the variable.

Assigning values to variables in Python

You can see from the above example that you can use the assignment operator = to assign values to variables.

Example1: Declare and assign values to variables

website = "apple.com"
print(website)

When running the program, the output is:

apple.com

In the above program, we assigned a value to the variablewebsiteWas assigned a value 'apple.com'. Then, we printed out the value assigned towebsiteThe value, that is, 'apple.com',

Note: Python is aType inferenceLanguage, so you do not need to explicitly define the variable type. It will automatically know that 'apple.com' is a string, and willwebsiteVariables are declared as strings.

Example2: Change the value of a variable

website = "apple.com"
print(website)
# Assign a new value to the website variable 
website = "oldtoolbag.com"
print(website)

When running the program, the output is:

apple.com
oldtoolbag.com

In the above program, we initially assigned 'apple.com' towebsiteVariables. Then, change the value to oldtoolbag.com。

Example3: Assign multiple values to multiple variables

a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)

If we want to assign the same value to multiple variables at once, we can do it like this:

x = y = z = "same"
print (x)
print (y)
print (z)

The second program assigns the string 'same' to three variables simultaneouslyx,yandz.

Constants

Constants are also a type of variable, whose value cannot be changed once assigned. You can think of constants as containers that store information that cannot be changed later.

You can think of constants as a bag for storing books, once placed in the bag, they cannot be replaced with other books.

Assigning constants in Python

In Python, constants are usually declared and assigned within modules. Here, a module is a new file that contains variables, functions, etc., and is imported into the main file. Within the module, constants written entirely in uppercase letters with underscores separating words.

Example3: Declare values and assign them to constants

Create aconstant.py:

PI = 3.14
GRAVITY = 9.8

Create amain.py:

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

When running the program, the output is:

3.14
9.8

In the above program, we create a constant.py module file. Then, assign constant values toPIandGRAVITY. After that, we create a main.py  Import the constant module and finally print the constant values.

Note: In fact, we do not use constants in Python. Naming them with uppercase letters is a convention to differentiate them from ordinary variables, but it cannot actually prevent reassignment.

Rules and naming conventions for variables and constants

  1. Constant and variable names should be lowercase letters (a to z) or uppercase letters (A to Zor numbers (0 to 9or underscores (_composed. For example:

    snake_case
    MACRO_CASE
    camelCase
    CapWords
  2. Create a meaningful name. For example, vowel is more thanvmore meaningful.

  3. If you want to create a variable name with two words, use underscores to separate them. For example:

    my_name
    current_salary
  4. Use uppercase letters to declare constants. For example:

    PI
    G
    MASS
    SPEED_OF_LIGHT
    TEMP
  5. Do not use special symbols such as !, @, #, $, %, etc.

  6. Do not use variable names that start with numbers.

Literals

Literals are the original data given by variables or constants. In Python, there are many types of literals, as shown below:

Numeric literals

Numeric literals are immutable (cannot be changed). Numeric literals can belong to3There are three different numeric types: Integer, Float, and Complex.

Example4How to use numeric literals in Python?

a = 0b1010 #Binary literal
b = 100 #Decimal literal
c = 0o310 #Octal literal
d = 0x12c #Hexadecimal literal
#Float literal
float_1 = 10.5 
float_2 = 1.5e2
#Complex literal
x = 3.14j
print(a, b, c, d)
print(float_)1, float_2)
print(x, x.imag, x.real)

When running the program, the output is:

10 100 200 300
10.5 150.0
3.14j 3.14 0.0

In the above program

  • We assign integer literals to different variables. Here,ais a binary literal,bis a decimal literal,cis an octal literal,dis a hexadecimal literal.

  • When we print variables, all literals will be converted to decimal values.

  • 10.5 and 1.5e2 is a floating-point literal.1.5e2 expressed in exponential form, equals 1.5 * 102.

  • We assign integer literals to different variables. Here,xan assigned complex literal 3.14j. Then, we useImaginary numbersliterals (x.imag) and Real numbersliterals (x.real) to create the imaginary and real parts of a complex number.

For more information about numeric literals, please refer to  Python Numbers.

String literals

String literals are a series of characters enclosed in quotes. We can use single quotes, double quotes, or triple quotes for strings. And, character literals are single or double-quoted individual characters.

Example7How to use string literals in Python?

strings = "This is Python"
char = "C"
multiline_str = "
unicode = u"\u00dcnic\u00f6de"
raw_str = r"raw \n string"
print(strings)
print(char)
print(multiline_str)
print(unicode)
print(raw_str)

When running the program, the output is:

This is Python
C
This is a multiline string with more than one line of code.
Ünicöde
raw \n string

In the above program, 'This is Python' is a string literal and 'C' is a char character literal. Inin multiline_strThe value assigned with triple quotes "6de" is a Unicode text that supports characters other than English, and r"raw \n string" is a raw string literal.

Boolean literals

Boolean literals can have either of the two values: True or False.

Example8How to use boolean literals in Python?

x = (1 == True)
y = (1 == False)
a = True + 4
b = False + 10
print("x is", x)
print("y is", y)
print("a:", a)
print("b:", b)

When running the program, the output is:

x is True
y is False
a: 5
b: 10

In the above program, we used boolean literals True and False. In Python, True represents a value of1, False represents a value of 0. The value of x is true, because1 equal to True. The value of y is False, because1 not equal to False. Similarly, we can use True and False as values in numerical expressions. The value of a is 5, because we add True, which has a value of 1 added 4. Similarly, b is equal to 10, because we add 0 and 10 added together.

Special literals

Python contains a special literal, namely None. We use it to specify fields that have not been created.

Example9How to use special literals in Python?

drink = "Available"
food = None
def menu(x):
    if x == drink:
        print(drink)
    else:
        print(food)
menu(drink)
menu(food)

When running the program, the output is:

Available
None

In the above program, we defined a menu function. Inside the menu, when we set the parameter to drink, it will display Available. And when the parameter is food, it will display None.

Literal sets

There are four different literal collections: list literals, tuple literals, dictionary literals, and set literals.

Example10How to use literal collections in Python?

fruits = ['apple', 'mango', 'orange']  # list
numbers = (1, 2, 3)  # tuple
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}  # dictionary
vowels = {'a', 'e', 'i', 'o', 'u'}  # set
print(fruits)
print(numbers)
print(alphabets)
print(vowels)

When running the program, the output is:

['apple', 'mango', 'orange']
(1, 2, 3)
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'e', 'a', 'o', 'i', 'u'}

In the above program, we created a fruits list, anumberstuple, an alphabets dictionary, alphabets dictionaryofvalues with keys specified for each value, andvowels vowelsthe set of letters.

For more information about literal collections, please refer toPython data types.