home PYTHONJAVA
 

Python3 basic data type

Variables in Python do not need to be declared. Each variable must be assigned before it is used, and the variable will be created after the variable is assigned.

In Python, a variable is a variable, it has no type, and what we mean by "type" is the type of object in memory that the variable refers to.

The equal sign (=) is used to assign a value to a variable.

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

Instance (Python 3.0+)

#!/usr/bin/python3 counter = 100< Span class="hl-code"> # Integer Variable miles= 1000.0< Span class="hl-code"> # floating point variable name= "< Span class="hl-string">Welookups" # string print (counter) print (miles) print (name)

Number(number)

Python3 supports int, float, bool, complex(plural).

In Python 3, there is only one integer type int, which is represented as a long integer, and there is no Long in python2.

As with most languages, the assignment and calculation of numeric types is straightforward.

The built-in type() function can be used to query the type of object that the variable refers to.

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

In addition, you can use isinstance to judge:

Instance...

>>>a = 111 >>> isinstance(a, int) True >>>

isinstance The difference between type and type is

  • Type() does not consider a subclass to be a parent class type.
  • Isinstance() considers a subclass to be a parent class type.
>>> class A:
... pass
...
>>> class B(A):
... pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False

Note: There is no Boolean in Python 2, which uses the number 0 for False and 1 for True. In Python 3, True and False are defined as keywords, but their values are still 1 and 0, which can be added to the numbers.

Numerical operations

Instance

...
>>>5 + 4 # addition 9 >>> 4.3 - 2 # Subtraction 2.3 >>> 3 * 7 # Subtraction multiplication 21 >>> 2 / 4 # Divide, get a floating point number 0.5 >>> 2 // 4 # Divide, get an integer 0 >>> 17 % 3 # Residual 2 >>> 2 ** 5 # Take the margin 32

Note:

  • 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 a different type of object by assignment.
  • 3. The division of values consists of two operators: / returns a floating point number, // returns an integer.
  • 4. In mixed computing, Python converts integers to floating point numbers.

Value type instance

intfloatcomplex
100.03.14j
10015.2045.j
-786-21.99.322e-36j
08032.3e+18.876j
-0490-90.-.6545+0J
-0x260-32.54e1003e+26J
0x6970.2E-124.53e-7j

Python also supports complex numbers. The complex number consists of a real part and an imaginary part. It can be represented by a + bj, or complex(a,b). The real part a and the imaginary part b of the complex number are both floating point types


String(string)

Strings in Python are enclosed in single quotes ' or double quotes " with a backslash \ Escape special characters.

The syntax of the interception of a string is as follows:

variables [header subscript: tail subscript]

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

The plus sign + is the string's connector, and the asterisk * means copying the current string, followed by the number The number of times of copying. An example is as follows:

Instance

#!/usr/bin/python3 str = 'Welookups' print (str) # Output string print (str[0:-1]) # Output all characters from the first to the second last print (str[0]) # Output string first character print (str[2:5]) # Output characters from the third to the fifth print (str[2:]) # Output all characters after the third start print (str * 2) # Output string string twice... print (str + "TEST") # Connection string

Executing the above program will output the following results:

Welookups
Runoo
R
Noo
Noob
WelookupsWelookups
    WelookupsTEST

Python uses a backslash (\) to escape special characters. If you don't want the backslash to be escaped, you can add an r to the front of the string to represent the original string:

>>> print('Ru\noob')< Span class="pln">
Ru
Oob
>>> print(r'Ru\noob')< /span>
Ru\noob
>>> 

In addition, the backslash (\) can be used as a continuation character, indicating that the next line is a continuation of the previous line. You can also use """...""" or '''......''' to span multiple lines.

Note that Python does not have a separate character type, a character is a string of length 1.

Instance

>>>word = 'Python' >>> print(word[0], word[5]) P n >>> print(word[-1], word[-6]) n P

Unlike C strings, Python strings cannot be changed. Assigning an index position, such as word[0] = 'm', will result in an error.

Note:

  • 1, backslash can be used to escape, use r can make the backslash not escape.
  • 2. Strings can be concatenated with the + operator and repeated with the * operator.
  • 3. Strings in Python have two indexing methods, starting with 0 from left to right and starting with -1 from right to left.
  • 4, the string in Python can not be changed.

List(list)

List is the most frequently used data type in Python.

The

list can do the data structure implementation of most collection classes. The types of elements in the list can be different, it supports numbers, and strings can even contain lists (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, and the list is truncated to return a new list containing the required elements.

The syntax for list interception is as follows:

variables [header subscript: tail subscript]< /pre>

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

Plus + is a list join operator, and the asterisk * is a repeat operation. The following example:

Instance

#!/usr/bin/python3 list = [ 'abcd', 786 , 2.23, 'Welookups', 70.2 ] tinylist = [123, 'Welookups'] print (list) # Output complete list print (list[0]) # Output list first element print (list[1:3]) # Output from the second to the third element print (list[2:]) # Output all elements starting with the third element... print (tinylist * 2) #Output twice list print (list + tinylist) # Connection list

The output of the above example:

['abcd', 786, 2.23, 'Welookups', 70.2]
abcd
[786, 2.23]
[2.23, 'Welookups', 70.2]
[123, 'Welookups', 123, 'Welookups']
['abcd', 786, 2.23, 'Welookups', 70.2, 123, 'Welookups']

Unlike Python strings, the elements in the list can be changed:

Instance

>>>a = [1, 2, 3, 4, 5, 6] >>> a[0] = 9 >>> a[2:5] = [13, 14, 15] >>> a [9, 2, 13, 14, 15, 6] >>> a[2:5] = [] # Set the corresponding element value to [] >>> a [9, 2, 6]

List has a lot of built-in methods, such as append(), pop(), etc., which will be covered later.

Note:

  • 1, List is written between square brackets, elements are separated by commas.
  • 2. Like strings, lists can be indexed and sliced.
  • 3, List can be spliced using the + operator.
  • 4. The elements in the List can be changed.

The Python list interception can receive the third parameter, which is the step size of the interception. The following example is located at index 1 to index 4 and is set to a step size of 2 (interval by one position) to intercept the string:


Tuple (tuple)

Tuples are similar to lists, except that the elements of the tuple cannot be modified. Tuples are written in parentheses () with elements separated by commas.

The element types in the tuple can also be different:

Instance

#!/usr/bin/python3 tuple = (< Span class="hl-code"> 'abcd', 786 , < /span>2.23, 'Welookups', 70.2 ) tinytuple = (123, 'Welookups') print (tuple) # Output complete 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:]) # Output all elements starting with the third element print (tinytuple * 2) # Output two tuples print (tuple + tinytuple) # Connection tuple

The above example output:

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

Instance

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

Although the tuple's elements cannot be changed, it can contain mutable objects, such as a list of lists.

Constructing a tuple containing 0 or 1 elements is special, so there are some additional grammar rules:

tup1 = () # Empty group
tup2 = (20,) # An element,Need to add a comma after the element

string, list, and tuple are all sequences.

Note:

  • 1. Like a string, the elements of a tuple 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. The tuple can also be spliced using the + operator.

Set(collection)

A set is composed of one or several different shapes, and the things or objects that make up the set are called elements or members.

The basic function is to perform membership testing and remove duplicate elements.

You can create a collection using braces { } or set() functions. Note: Creating an empty collection must use < Span class="marked"> set() instead of { } because { } is used to create An empty dictionary.

Create a format:

parame = {value01,value02,...}
or
set(value)

Instance

#!/usr/bin/python3 student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'} print(student) # Output collection, duplicate elements are automatically removed # Member test if 'Rose' in student : print('Rose In the collection') else : print('Rose Not in collection') # setCan perform set operations a = set('abracadabra') b = set('alacazam') print(a) print(a - b) # a with b Difference set print(a | b) # a with b Union print(a & b) # a with b Intersection print(a ^ b) # a And elements that do not exist in b





javacodegeeks is optimized for learning.© javacodegeeks. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.