Python variables and data types

In this article, we'll learn Python variables and data types


Variables come from mathematics and are computer languages that store calculation results or represent abstract concepts of values. Variables can be accessed through variable names. Variable naming rules in Python must be case, numeric, and underscore () And cannot start with a number.

Variable Naming Rules:

  • Variable names can only be any combination of letters, numbers, and underscores
  • The first character of a variable name cannot be a number
  • Variable names are case sensitive and case letters are considered two different characters
  • Special keywords cannot be named variable names

Declare Variables

Variables in Python do not need to be declared; each variable must be assigned before it can be used, and the variable will not be created until it is assigned. In Python, a variable is a variable. It has no type. What we call a type is the type of object in memory that the variable refers to.

name = "neo"

The code above declares a variable named name with a value of "neo".

Variable assignment

In Python, equal sign = is an assignment statement that assigns any data type to a variable, the same variable can be assigned repeatedly, and it can be of different types.

a = 123 # a is an integer
a = 'abc' # A is a string

Languages of variable types are called dynamic languages, which correspond to static languages. Static languages must specify variable types when defining variables, and errors will occur if types do not match when assigning values. For example, Java is a static language, so assignments will fail:

Multiple variable assignments

Python allows you to assign values to multiple variables at the same time. For example:

a = b = c = 1

In the example above, an integer object with a value of 1 is created, and three variables are assigned the same value.

You can also specify multiple variables for multiple objects. For example:

a, b, c = 1, 2, "neo"

In the above example, two integer objects 1 and 2 are assigned to variables a and b, and the string object "neo" is assigned to variable c.


Constants are variables that cannot be changed, such as the common mathematical constant pi, which is a constant. In Python, constants are usually represented by variable names in all uppercase:

BI = 3.14

In fact, BI is still a variable, and Python can't guarantee that BI won't be changed at all, so using all uppercase variable names to represent constants is just a common use, and if you do, the syntax will not error.

data type

There are six standard data types in Python3: Number, String, List, Tuple, Sets, Dictionary.

Of the six standard data types for Python 3:

  • Invariant data (3): Number (number), String (string), Tuple (tuple);
  • Variable data (3): List (list), Dictionary (dictionary), Set (collection).

Next, we will describe the use of these data types.

Number (number)

Python 3 supports int, float, bool, complex (complex numbers).

Number types, as the name implies, are used to store numeric values, and it is important to remember that they taste a bit like Java strings and that if you change the value of a numeric data type, memory space will be reallocated.

Python supports three different numeric types:

  • Integer (Int) - Often referred to as an integer or integer, it is a positive or negative integer with no decimal point. Python3 integers are of unlimited size and can be used as Long types, so Python3 does not have a Long type of Python2.
  • Floating-point type (float) - Floating-point type is composed of integer part and decimal part. Floating-point type can also be represented by scientific counting (2.5e2 = 2.5 x 102 = 250)
  • Complex ((complex) - Complex numbers are composed of real and imaginary parts and can be expressed as a + bj or complex(a,b). The real part a and imaginary part B of a complex number are floating point types.


counter = 100          # Integer variable
miles   = 1000.0       # Float
name    = "test"     # Character string
print (counter)
print (miles)
print (name)

Number Type Conversion

  • int(x) converts x to an integer.
  • float(x) converts x to a floating point number.
  • complex(x) converts x to a complex number, where the real part is x and the imaginary part is 0.
  • complex(x, y) converts X and y to a complex number, where the real part is x and the imaginary part is y. X and y are numeric expressions. Additional instructions

Like other languages, number types support a variety of common operations, but Python is much richer than most other common languages, and there are a number of rich methods to provide more efficient development.

Examples of numerical operations:

print (5 + 4)  # Addition Output 9
print (4.3 - 2) # Subtraction Output 2.3
print (3 * 7)  # Multiplication Output 21
print (2 / 4)  # Divide and get a floating point output of 0.5
print (2 // 4) Division to get an integer output of 0
print (17 % 3) # Remaining Output 2
print (2 ** 5) # Multiplier Output 32

String (string)

Strings can be created using single quotes, double quotes, three single quotes, and three double quotes, where three quotes define a string in multiple lines, Python does not support single character types, and single characters are also used as a string in Python.

We define an s='python'statement that executes on a computer in the order of creating a string Python in memory, creating a variable s in the stack register, and assigning the address of Python to s.

Let's look at some of the common operations of strings:

s = 'Study Python'
# Section
s[0], s[-1], s[3:], s[::-1]	# 'excellent','n','Python','elegance of nohtyP'
# Replace, or replace with regular expressions
s.replace('Python', 'Java')	# 'Learn Java'
# find(), index(), rfind(), rindex()
s.find('P')			# 3, returns the subscript of the first occurrence of the substring
s.find('h', 2)			# 6, set subscript 2 to start searching
s.find('23333')			# -1, cannot find Return-1
s.index('y')			# 4, returns the subscript of the first occurrence of the substring
s.index('P')		# Unlike find(), find does not throw an exception
# upper(), lower(), swapcase(), capitalize(), istitle(), isupper(), islower()
s.upper()			# 'Learn PYTHON'
s.swapcase()			# 'Learn pYTHON', case-switching
s.istitle()			# True
s.islower()			# False
# strip(), lstrip(), rstrip()
# Format
s1 = '%s %s' % ('Windrivder', 21)	# 'Windrivder 21' 
s2 = '{}, {}'.format(21, 'Windridver')	# Recommended format formatting string
s3 = '{0}, {1}, {0}'.format('Windrivder', 21)
s4 = '{name}: {age}'.format(age=21, name='Windrivder')
# Join and split, use + join string, each operation will recalculate, open up, release memory, inefficient, so join is recommended
l = ['2017', '03', '29', '22:00']
s5 = '-'.join(l)			# '2017-03-29-22:00'
s6 = s5.split('-')			# ['2017', '03', '29', '22:00']

These are some common operations.

It is also important to note that string encoding, where all Python strings are Unicode strings, requires encoding conversions to convert characters to bytes when files need to be saved to peripherals or for network transmission to improve efficiency.

# encode converts characters to bytes
str = 'Study Python'      
print (str.encode())			# The default encoding is UTF-8 output: b'\xe5xadxa6xe4xb9xa0Python'
print (str.encode('gbk'))      # Output b'xd1\xa7xcfxb0Python'
# decode converts bytes to characters
print (str.encode().decode('utf8'))   # Output'Learn Python'
print (str.encode('gbk').decode('gbk'))             # Output'Learn Python'

List (List)

Similar to Java List collection interface

A list is a comma-separated list of elements written between brackets [], and can complete the data structure implementation of most collection classes. Elements in lists can be of different types, support numbers, strings can even contain lists (so-called nestings), and elements in lists can be changed.


Weekday = ['Monday','Tuesday','Wednesday','Thursday','Friday']
print(Weekday[0])   # Output Monday

#list search

#list add element

# list deletion

Tuple (tuple)

Tuples are similar to lists, except that elements of tuple s cannot be modified. Tuples are written in parentheses (), separated by commas, and the element types in groups can be different.


letters = ('a','b','c','d','e','f','g')
print(letters[0])  # Output'a'
print(letters[0:3])  # Output a set ('a','b','c')

Sets (Sets)

Similar to Java Set collection interface

A set is a sequence of unordered, non-repeating elements that are created using curly braces {} or set() functions. Note that to create an empty set, you must use set() instead of {} because {} is used to create an empty dictionary.

Collections cannot be sliced or indexed. In addition to performing set operations, set elements can be added and deleted:


a_set = {1,2,3,4}
# Add to
print(a_set)  # Output {1, 2, 3, 4, 5}
# delete
print(a_set)  # Output {1, 2, 3, 4}


Similar to Java Map Collection Interface

A dictionary is a mapping type whose elements are key-value pairs and whose keys must be of an immutable type and cannot be repeated. Create an empty dictionary using {}.


Logo_code = {
# Output {'BIDU':'Baidu','YOKU':'Youku','SINA':'Sina'}
print (Logo_code['SINA'])       # Value with output key of'one'
print (Logo_code.keys())   # Output all keys
print (Logo_code.values()) # Output all values
print (len(Logo_code))  # Output field length

Sample code in this article: python-100-days


This section introduces Python variables and six standard data types, demonstrates the use of variables, and common operations of six standard data types.

Tags: Python

Posted by imcookie on Thu, 22 Sep 2022 22:13:20 +0530