SoFunction
Updated on 2024-11-13

Explaining python variables and data types in detail

In this article we learn about Python variables and datatypes.

variant

Variables are derived from mathematics and are abstract concepts in computer languages that can store the result of a calculation or represent a value, and they can be accessed by their name. In Python, variable naming requires that they be a combination of upper- and lower-case English, numbers, and underscores (_), and that they not begin 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; upper and lower case letters are considered to be two different characters
  • Special keywords cannot be named as variable names

declare a variable

Variables in Python don't need to be declared; every variable must be assigned a value before it can be used, and a variable is not created until it is assigned a value. In Python, a variable is a variable; it has no type; what we mean by "type" is the type of the object in memory to which the variable refers.

name = "neo"

The above code declares a variable named: name, and the value of the variable name is "neo".

variable assignment

In Python, the equals sign = is an assignment statement that allows you to assign any data type to a variable, the same variable can be assigned repeatedly, and it can be a variable of a different type.

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

Languages in which the type of the variable itself is not fixed are called dynamic languages, and their counterparts are static languages. Static languages must specify the type of the variable when defining it, and if the type does not match when assigning a value, an error will be reported. For example, Java is a static language, so an assignment will result in an error:

Multiple variable assignment

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

a = b = c = 1

In the above example, an integer object is created with a value of 1. Assigning values from back to front, all three variables are given the same value.

You can also specify multiple variables for multiple objects. Example:

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

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

constant

A constant is a variable that can't be changed, such as the common math constant π. In Python, constants are usually denoted by all-caps variable names:

BI = 3.14

But the fact is that BI is still a variable, and Python can't guarantee that BI won't be changed at all, so it's only customary to use all capitalized variable names for constants, and the syntax won't report an error if you have to change it.

data type

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

of Python3's six standard data types:

  • Immutable data (3): Number, String, Tuple;
  • Variable data (3): List, Dictionary, Set.

We describe the use of each of these data types below.

Number

Python3 supports int, float, bool, and complex.

Numeric types are, as the name suggests, used to store numeric values, and it's important to keep in mind that, somewhat in the same flavor as Java's strings, memory space will be reallocated if the value of a numeric data type is changed.

Python supports three different numeric types:

  • Integer (Int) - Often referred to as being an integer or an integer, it is a positive or negative integer without a decimal point.Python3 integers are unlimited in size and can be used as Long types, so Python3 does not have the Long type of Python2.
  • Floating point (float) - Floating point consists of an integer part and a decimal part, floating point can also be expressed using scientific notation (2.5e2 = 2.5 x 102 = 250)
  • Complex number ((complex)) - A complex number consists of a real part and an imaginary part, and can be represented as a + bj, or complex(a,b), where both the real part a and the imaginary part b are floating point.

Example:

#!/usr/bin/python3
 
counter = 100     # Integer variables
miles  = 1000.0    # Floating-point variables
name  = "test"   # String
 
print (counter)
print (miles)
print (name)

Digit 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 with x in the real part and 0 in the imaginary part.
  • complex(x, y) converts x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions. Additional Notes

Like other languages, numeric types support a variety of common operations, but Python's operations are richer than those of most other common languages, and there are a large number of rich methods that 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 to get a floating point number Output 0.5
print (2 // 4) # Divide to get an integer Output 0
print (17 % 3) # Balance Output 2
print (2 ** 5) # calculate the square exports 32

String

To create a string you can use single quotes, double quotes, triple single quotes and triple double quotes, where triple quotes can be used to define a string on multiple lines, Python doesn't support the single character type, and the single character is also used as a string in Python as well.

We define a statement s='python', which executes in the computer in the order of first creating a string Python in memory, creating a variable s in the program stack register, and finally assigning Python's address to s.

Let's look at some more common operations on strings:

s = 'Learning Python'
# Slicing
s[0], s[-1], s[3:], s[::-1]	# 'Yo', 'n', 'Python', 'nohtyP's ya-yo'
# Replacement, and also regular expression replacement
('Python', 'Java')	# 'Learning Java'
# Find, find(), index(), rfind(), rindex()
('P')			# 3, return the subscript of the first occurrence of the substring
('h', 2)			# 6, set subscript 2 to start searching.
('23333')			# -1, returns -1 if not found
('y')			# 4, return the subscript of the first occurrence of the substring
('P')		# Unlike find(), which throws an exception if it doesn't find anything.
# Case conversion, upper(), lower(), swapcase(), capitalize(), istitle(), isupper(), islower()
()			# 'Learning PYTHON'
()			# 'Learn pYTHON', case-swapped
()			# True
()			# False
# Space removal, strip(), lstrip(), rstrip()
# Formatting
s1 = '%s %s' % ('Windrivder', 21)	# 'Windrivder 21' 
s2 = '{}, {}'.format(21, 'Windridver')	# Recommended formatting of strings using format
s3 = '{0}, {1}, {0}'.format('Windrivder', 21)
s4 = '{name}: {age}'.format(age=21, name='Windrivder')
# Join and split, use + to join strings, each operation will re-calculate, open and free memory, very inefficient, so it is recommended to use join
l = ['2017', '03', '29', '22:00']
s5 = '-'.join(l)			# '2017-03-29-22:00'
s6 = ('-')			# ['2017', '03', '29', '22:00']

These are some common operations.

Another thing to keep in mind is string encoding. All Python strings are Unicode strings, so when you need to save a file to a peripheral or transfer it over the network, you have to do an encoding conversion to convert characters to bytes for efficiency.

# encode Convert characters to bytes
str = 'Learning Python'   
print (())			# The default encoding is UTF-8 Output: b'\xe5\xad\xa6\xe4\xb9\xa0Python'
print (('gbk'))   # Output b'\xd1\xa7\xcf\xb0Python'
# decode Convert bytes to characters
print (().decode('utf8'))  # Output 'Learn Python'
print (('gbk').decode('gbk'))       # exports 'Learning Python'

List

Similar to the Java List collection interface

A list is a list of elements written between square brackets [] and separated by commas, lists can fulfill most data structure implementations of collection classes. The types of the elements in a list can be different, it supports numbers, strings can even contain lists (so-called nesting), and the elements in a list can be changed.

Example:

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

#list Search
print(("Wednesday"))

#list add element
("new")
print(Weekday)

# list Delete
("Thursday") 
print(Weekday)

Tuple

A tuple is similar to a list, except that the elements of a tuple cannot be modified. Tuples are written in parentheses (), the elements are separated by commas, and the types of the elements in the group can be different.

Example:

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

Sets

Similar to the Java Set collection interface

A set is an unordered sequence of non-repeating elements. Use either the curly brackets {} or the set() function to create a set. Note: To create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.

Sets cannot be sliced or indexed, and set elements can be added and deleted, except for set operations:

Example:

a_set = {1,2,3,4}
# Add
a_set.add(5)
print(a_set) # Output {1, 2, 3, 4, 5}
# Delete
a_set.discard(5)
print(a_set) # exports{1, 2, 3, 4}

Dictionary

Similar to the Java Map collection interface

A dictionary is a mapping type whose elements are key-value pairs, and whose keywords must be immutable and cannot be repeated. To create an empty dictionary, use {}.

Example:

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

summarize

This section introduces you to Python variables and the six standard datatypes, demonstrating the use of variables and common operations with the six standard datatypes.

Sample code:Python-100-days-day003

The above is a detailed explanation of python variables and data types in detail, more information about python variables and data types please pay attention to my other related articles!