Python learning notes 2 - basic data types

Variables in Python do not need to be declared. Each variable must be assigned before use, and the variable will not be created until it is assigned. In Pyhton, a variable is a variable. It has no type. The type we refer to is the type of the object in memory referred to by the variable.

The equal sign (=) is used to assign values to variables

To the left of the equal sign (=) operator is a variable name, and to the right of the equal sign (=) operator is the value stored in the variable. For example:

counter = 100  #Integer variable
miles = 1000.0 #Floating point variable
name = 'pyhton' #character string

print(counter)
print(miles)
print(name)

After performing the above procedure, the following results will appear:

100
1000.0
python

Assignment of multiple variables  

python allows you to assign values to multiple variables, for example:

a=b=c=1

In the above example, create an integer object with a value of 1, assign values from back to front, and the three variables are given the same value.

You can also specify multiple variables for multiple objects, for example:

a,b,c = 1, 2, 'pyhton'

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

Standard data type

There are six standard data types in Python:
Number

String (string)

List

Tuple (tuple)

Set

Dictionary

Of the six standard data types in Python:
Immutable data types (3): Number, String, Tuple

Variable data types (3): List, dictionary, Set

Number:
int, float, bool and complex are supported in Python

In Python, there is only one integer type Int, where long does not exist

Like most languages, the assignment and calculation of numeric types are intuitive. The built-in type () function can be used to directly query the object type referred to by the variable.

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

In addition, you can use the instance() function to judge. For example:

a = 111
isinstance(a,int)
True

isinstance differs from type in that:
Type () does not consider a subclass to be a parent type

isinstance () considers a subclass to be a parent type

Numerical operation

Numerical operations include +, -, *, /, / /,%, * * (power)

The key points to note are / and / / where / is to get a floating-point result, for example, 1 / 2 gets 0.5, and / / is to get an integer result, for example: 2 / / 4 = 0

be careful:

  • 1. Python can assign values to multiple variables at the same time, such as a, b = 1, 2.
  • 2. A variable can be assigned to different types of objects.
  • 3. The division of a numeric value consists of two operators:/   Returns a floating point number//   Returns an integer.
  • 4. In mixed computation, Python converts integers to floating-point numbers.

  Python also supports complex numbers. Complex numbers are composed of real and imaginary parts, which can be represented by a + bj or complex(a,b). Both real part a and imaginary part B of complex numbers are floating-point

String (string)

Strings in Python are enclosed in single quotation marks' 'and double quotation marks'', and backslashes \ are used to escape special characters

The format of string interception is as follows: variable [header subscript: tail subscript: step size]

The index value starts with 0 and - 1 is the starting position from the end

  The plus sign + is the connector of the string, the asterisk * indicates the copy of the current string, and the number combined with it is the number of copies.

python uses backslash \ to escape special characters. If you don't want the backslash to escape, you can add an r in front of the string to represent the original string.

In addition, the backslash can be used as a continuation character to indicate that the next line is the continuation of the previous line, or you can use ""... "" or ""... '' to realize multiple lines. Note that python does not have a separate character type. A character is a string with a length of one.

Unlike C strings, Python strings cannot be changed. Assigning a value to an index location, such as word [0] ='m 'will cause an error.

be careful:
1. Escape characters can be escaped by backslash, in which r can prevent backslash from escaping.

2. Strings can be concatenated with the + operator and repeated with the * operator.

3. There are two indexing methods for strings in python, one is from left to right, and the other is from right to left.

4. Strings in python cannot be changed

List

List is the most frequently used data type in python.

List can complete the data structure implementation of most collection classes. The types of elements in the list can be different. It supports numbers, strings, and even contains a new list (so-called nesting)

The list is a comma separated list of elements written between square brackets []

Like strings, lists can also be indexed and intercepted. After being intercepted, a new list containing the required elements is returned.

The syntax format of list interception is as follows: variable [header subscript: tail subscript]

Index value in   0   Is the start value, - 1   Is the starting position from the end

  plus  +  Is a list join operator, asterisk  *  Is a repeat operation. Examples are as follows:

be careful:

  • 1. List is written between square brackets, and elements are separated by commas.
  • 2. Like strings, list s can be indexed and sliced.
  • 3. List s can be spliced using the + operator.
  • 4. The elements in the List can be changed.
  • Python list interception can receive the third parameter. The parameter is used to intercept the step size. The following examples are at the positions from index 1 to index 4 and set the step size to 2 (one position apart) to intercept the string:

If the third parameter is negative, it means reverse reading. The following example is used to flip the string:

def reverseWords(input):
     
    # Separate each word into a list by separating the string separator with spaces
    inputWords = input.split(" ")
 
    # Flip string
    # Suppose list = [1,2,3,4],  
    # list[0]=1, list[1]=2, and - 1 indicates that the last element list[-1]=4 (the same as list[3]=4)
    # inputWords[-1::-1] has three parameters
    # The first parameter - 1 represents the last element
    # The second parameter is empty, which means moving to the end of the list
    # The third parameter is step size, - 1 indicates reverse
    inputWords=inputWords[-1::-1]
 
    # Recombine strings
    output = ' '.join(inputWords)
     
    return output
 
if __name__ == "__main__":
    input = 'I like runoob'
    rw = reverseWords(input)
    print(rw)

  Tupe (tuple)

Tuples are similar to list items, except that the elements of tuples cannot be modified. Tuples are written in (), and the elements are separated by commas.

Element types in tuples can also be different

tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2  )
tinytuple = (123, 'runoob')

print (tuple)             # Output full tuple
print (tuple[0])          # The first element of the output tuple
print (tuple[1:3])        # The output starts from the second element to the third element
print (tuple[2:])         # Outputs all elements starting with the third element
print (tinytuple * 2)     # Output tuple
print (tuple + tinytuple) # Join tuple

Output results of the above examples:

('abcd', 786, 2.23, 'runoob', 70.2)
abcd
(786, 2.23)
(2.23, 'runoob', 70.2)
(123, 'runoob', 123, 'runoob')
('abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob')

  Tuples are similar to strings. They can be indexed, and the subscript index starts from 0 and - 1 is the position from the end. It can also be intercepted

In fact, a string can be regarded as a special tuple.

example:

>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11  # It is illegal to modify tuple elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Although the tuple element cannot be changed, it can contain mutable objects, such as list s

It is special to construct tuples containing 0 or 1 elements, so there are some additional syntax rules:

tup1 = ()    # Empty tuple
tup2 = (20,) # For an element, you need to add a comma after the element

string, list, and tuple all belong to sequence

be careful:
1. Like strings, elements of tuples cannot be modified

2. Tuples can also be indexed and sliced in the same way

3. Note the special syntax rules for constructing tuples containing 0 or 1 elements

4. Tuples can also be spliced using the + operator

Set

A Set is composed of one or several large and small entities with different shapes. The things or objects constituting the Set are called elements or members

The basic function is to test membership and delete duplicate elements

You can use brace {} or set () function to create a set. Note: to create an empty set, you must use se() instead of {}, because {} is used to create an empty dictionary

Create format:
parame = (value01,value02,...)

perhaps

set(value)

Examples are as follows:

sites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}

print(sites)   # Output set, duplicate elements are automatically removed

# Member test
if 'Runoob' in sites :
    print('Runoob In collection')
else :
    print('Runoob Not in collection')


# Set can perform set operations
a = set('abracadabra')
b = set('alacazam')

print(a)

print(a - b)     # Difference sets of a and b

print(a | b)     # Union of a and b

print(a & b)     # Intersection of a and b

print(a ^ b)     # Elements in a and b that do not exist at the same time

Dictionary

dictionary

Is another very useful built-in data type in Python.

A list is an ordered collection of objects, and a dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

Dictionary is a mapping type. Dictionary uses   { }   Identification, it is an unordered   Key: value   A collection of.

Keys must be of immutable type.

Keys must be unique in the same dictionary.

dict = {}
dict['one'] = "1 - "
dict[2]     = "2 - "

tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'}


print (dict['one'])       # The output key is the value of 'one'
print (dict[2])           # The output key is a value of 2
print (tinydict)          # Output complete dictionary
print (tinydict.keys())   # Output all keys
print (tinydict.values()) # Output all values

Output results:

1 - 
2 - 
{'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name', 'code', 'site'])
dict_values(['runoob', 1, 'www.runoob.com'])

The constructor dict() can build a dictionary directly from the sequence of key value pairs as follows:

>>> dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
{'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> dict(Runoob=1, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>>

In addition, dictionary types also have some built-in functions, such as clear(), keys(), values(), and so on.

be careful:

  • 1. A dictionary is a mapping type whose elements are key value pairs.
  • 2. Dictionary keywords must be immutable and cannot be duplicated.
  • 3. Create an empty dictionary to use   { }.

  Python data type conversion

Sometimes, we need to convert the built-in type of data. For data type conversion, you only need to use the data type as the function name.

The following built-in functions can perform conversion between data types. These functions return a new object representing the converted value.

functiondescribe
int(x,[base])Convert x to an integer
float(x)Convert x to a floating point number
comples(real,imag)Create a complex number
str(x)Convert object x to string
repr(x)Converts object x to an expression string
eval(str)Used to evaluate a valid Python expression in a string and return an object
tuple(s)Convert sequence s to a tuple
list(s)Convert sequence s to a list
set(s)Convert to variable set
dict(d)Create a dictionary. d must be a (key, value) tuple sequence.
frozenset(s)Convert to immutable set

chr(x)

Converts an integer to a character
ord(x)Converts a character to its integer value

Keywords: Python Back-end

Added by Toby on Sun, 31 Oct 2021 20:54:17 +0200