Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Basic Data Types

Python3 Basic Data Types

Variables in Python do not need to be declared. Every variable must be assigned a value before use; the variable is created only after the assignment.

In Python, a variable is just a variable and has no type; the type we speak of is the type of the object in memory that the variable refers to.

The equals sign = is used to assign a value to a variable. The left side is the variable name and the right side is the value stored in the variable. For example:

Example (Python 3.0+)

#!/usr/bin/python3

counter

=

100

         

Integer variable

miles  

=

1000.0

     

Floating-point variable

name    

=

"runoob"

   

String

print

(

counter

)

print

(

miles

)

print

(

name

)

Run Example »

Running the program above produces the following output:


100
1000.0
runoob

Assigning multiple variables

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

a = b = c = 1

The example above creates an integer object with value 1, and three variables are given the same value.

You can also assign different values to multiple variables at once. For example:

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

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

You can check a variable's type with the type() function:

Example

Variable definition

x

=

10

         

Integers

y

=

3.14

       

Float (floating point number)

name

=

"Alice"

 

String

is_active

=

True

Boolean

Multiple variable assignment

a

,

b

,

c

=

1

,

2

,

"three"

Check the data type

print

(

type

(

x

)

)

       

print

(

type

(

y

)

)

       

print

(

type

(

name

)

)

     

print

(

type

(

is_active

)

)


Standard data types

Python3 has 6 standard data types plus the bool type (bool is a subclass of int and is sometimes listed separately):

By mutability, they can be divided into the following two groups:

There are also some advanced data types, such as the byte array type bytes.


Number

Python3 supports int, float, bool, complex。

In Python 3 there is only one integer type, int, represented as a long integer; there is no Long as in Python 2.

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


>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
   

You can also use isinstance() to check:

Example

a

=

111

isinstance

(

a

,

int

)

True

isinstance and type The difference between them is:


>>> class A:
...     pass
...
>>> class B(A):
...     pass
...
>>> isinstance(A(), A)
True
>>> type(A()) == A
True
>>> isinstance(B(), A)
True
>>> type(B()) == A
False

Note:In Python3, bool is a subclass of int, and True and False can be added to numbers,True==1、False==0 returns True, but you can use is to check object identity.


>>> issubclass(bool, int) True >>> True == 1 True >>> False == 0 True >>> True + 1 2 >>> False + 1 1 >>> 1 is True :1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="? False >>> 0 is False :1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="? False

Why does a SyntaxWarning appear?

Python detects that you are using is to compare a literal integer (such as 1) with True, which is usually a coding error - because is compares object identity (whether they are the same object), not value equality. Python recommends using == to compare values, unless you really need to check whether they are the same object.

In Python 2 there was no boolean type; it used the number 0 to represent False and 1 to represent True.

When you assign a value, a Number object is created:


var1 = 1
var2 = 10

You can delete an object reference with the del statement:


del var1[, var2[, var3[...., varN]]]

For example:


del var
del var_a, var_b

Numeric operations

Example

5

4

 

Addition

9

4.3

2

Subtraction

2.3

3

7

 

Multiplication

21

2

/

4

 

Division, produces a float

0.5

2

//

4

 

Floor division, produces an integer

0

17

%

3

 

Remainder

2

2

**

5

 

Exponentiation

32

Note:

Numeric type examples

int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
0o17 32.3e+18 .876j
-0o112 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2E-12 4.53e-7j

Note: in Python 3, integer literals cannot have leading zeros (such as 080); octal numbers must use the 0o prefix (such as 0o17), hexadecimal uses 0x prefix (such as 0x69), and binary uses 0b prefix.

Python also supports complex numbers, which consist of a real part and an imaginary part and can be written as a + bj or complex(a, b); the real part a and imaginary part b are both floats.


String

Strings in Python are enclosed in single quotes ' or double quotes ", and a backslash is used to escape special characters.

The syntax for string slicing is as follows:

变量[头下标:尾下标]

Index values start at 0, with -1 being the position starting from the end.

The plus sign + is the string concatenation operator, and the asterisk * means repeating the current string, with the number combined with it giving the repeat count. Example:

Example

#!/usr/bin/python3

my_str

=

'Runoob'

     

Define a string variable (avoid using str as a variable name, as it shadows the built-in type)

print

(

my_str

)

         

Print the whole string: Runoob

print

(

my_str

[

0

:-

1

]

)

   

Print index 0 up to the second-to-last character (excluding the last): Runoo

print

(

my_str

[

0

]

)

       

Print the first character: R

print

(

my_str

[

2

:

5

]

)

     

Print characters at indexes 2, 3, 4 (excluding index 5): noo

print

(

my_str

[

2

:

]

)

     

Print from index 2 to the end: noob

print

(

my_str *

2

)

     

Print twice: RunoobRunoob

print

(

my_str +

"TEST"

)

 

String concatenation: RunoobTEST

Running the program above produces the following output:


Runoob
Runoo
R
noo
noob
RunoobRunoob
RunoobTEST

Python uses a backslash to escape special characters; if you do not want the backslash to escape, add an r before the string to make it a raw string:

Example

print

(

'Ru\noob'

)

Ru

oob

print

(

r

'Ru\noob'

)

Ru\noob

In addition, a backslash can act as a line continuation character, meaning the next line continues the previous one. You can also use """...""" or '''...''' to span multiple lines.

Note that Python has no separate character type; a character is a string of length 1.

Example

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 to an index position, such as word[0] = 'm', causes an error.

Note:


bool

The boolean type is either True or False. In Python, True and False are keywords representing boolean values.

The boolean type can control program flow, such as checking whether a condition holds, or executing a block of code when a condition is satisfied.

Characteristics of the boolean type:

Example

Boolean values and types

a

=

True

b

=

False

print

(

type

(

a

)

)

 

print

(

type

(

b

)

)

 

Integer behavior of the boolean type

print

(

int

(

True

)

)

 

1

print

(

int

(

False

)

)

 

0

Conversion with the bool() function

print

(

bool

(

0

)

)

         

False

print

(

bool

(

42

)

)

       

True

print

(

bool

(

''

)

)

       

False

print

(

bool

(

'Python'

)

)

 

True

print

(

bool

(

[

]

)

)

       

False

print

(

bool

(

[

1

,

2

,

3

]

)

)

 

True

Boolean logical operations

print

(

True

and

False

)

 

False

print

(

True

or

False

)

 

True

print

(

not

True

)

       

False

Boolean comparison operations

print

(

5

3

)

 

True

print

(

2

==

2

)

 

True

print

(

7

<

4

)

 

False

Boolean values in control flow

if

True

:

   

print

(

"This will always print"

)

if

not

False

:

   

print

(

"This will also always print"

)

x

=

10

if

x:

   

print

(

"x is a nonzero value and is True in a boolean context"

)

**Note:** in Python, all nonzero numbers and non-empty strings, lists, tuples, and other data types are treated as True; only 0, empty strings, empty lists, empty tuplesand similar are treated as False. Therefore, when converting to a boolean, pay attention to the truthiness of the data type.


List

List is the most frequently used data type in Python.

Lists can implement most collection-class data structures. Elements in a list can be of different types; they support numbers, strings, and can even contain lists (i.e. nested lists).

A list is written between square brackets [] as a comma-separated list of elements.

Like strings, lists can be indexed and sliced; slicing a list returns a new list containing the required elements.

The syntax for list slicing is as follows:

变量[头下标:尾下标]

Index values start at 0, with -1 being the position starting from the end.

The plus sign + is the list concatenation operator, and the asterisk * is the repetition operation. Example:

Example

#!/usr/bin/python3

my_list

=

[

'abcd'

,

786

,

2.23

,

'runoob'

,

70.2

]

 

Avoid using list as a variable name, as it shadows the built-in type

tinylist

=

[

123

,

'runoob'

]

print

(

my_list

)

           

Print the whole list: ['abcd', 786, 2.23, 'runoob', 70.2]

print

(

my_list

[

0

]

)

         

Print the first element (index 0): abcd

print

(

my_list

[

1

:

3

]

)

       

Print elements at indexes 1 and 2 (excluding index 3): [786, 2.23]

print

(

my_list

[

2

:

]

)

       

Print all elements from index 2 to the end: [2.23, 'runoob', 70.2]

print

(

tinylist *

2

)

       

Print tinylist twice: [123, 'runoob', 123, 'runoob']

print

(

my_list + tinylist

)

 

Concatenate two lists

The example above produces the following output:


['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']

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

Example

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 values to an empty list, i.e. delete those elements

a

[

9

,

2

,

6

]

List has many built-in methods, such as append()、pop() and so on, which will be covered later.

Note:

Python list slicing accepts a third argument that sets the step size; the following example sets step 2 at indexes 1 to 4 (taking every other element):

If the third argument is negative, it reads backwards; the following example reverses the word order in a string:

Example

def

reverseWords

(

input

)

:

   

Split the string on spaces, turning each word into a list element

    inputWords

=

input

.

split

(

" "

)

   

The three arguments of inputWords[-1::-1]:

   

The first argument -1 means start from the last element

   

The second argument is empty, meaning move to the beginning of the list

   

The third argument -1 means a reverse step (move one position to the left each time)

    inputWords

=

inputWords

[

1

::-

1

]

   

Join the words back together with spaces

    output

=

' '

.

join

(

inputWords

)

   

return

output

if

name

==

"main"

:

   

input

=

'I like runoob'

    rw

=

reverseWords

(

input

)

   

print

(

rw

)

The output is:

runoob like I

Tuple

A tuple is similar to a list, except that its elements cannot be modified. Tuples are written in parentheses () with elements separated by commas.

Elements in a tuple can also be of different types:

Example

#!/usr/bin/python3

my_tuple

=

(

'abcd'

,

786

,

2.23

,

'runoob'

,

70.2

)

 

Avoid using tuple as a variable name

tinytuple

=

(

123

,

'runoob'

)

print

(

my_tuple

)

             

Output the complete tuple

print

(

my_tuple

[

0

]

)

           

Output the first element: abcd

print

(

my_tuple

[

1

:

3

]

)

         

Output elements at indexes 1 and 2: (786, 2.23)

print

(

my_tuple

[

2

:

]

)

         

Output all elements from index 2

print

(

tinytuple *

2

)

         

Output tinytuple twice

print

(

my_tuple + tinytuple

)

 

Concatenate two tuples

The example above produces the following output:


('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, like strings, can be indexed with subscripts starting at 0, with -1 as the position starting from the end, and can also be sliced.

In fact, a string can be viewed as a special kind of tuple.

Example

tup

=

(

1

,

2

,

3

,

4

,

5

,

6

)

print

(

tup

[

0

]

)

1

print

(

tup

[

1

:

5

]

)

(

2

,

3

,

4

,

5

)

tup

[

0

]

=

11

 

Modifying a tuple's elements is illegal

Traceback

(

most recent call last

)

:

  File

""

,

line

1

,

in

<

;

module>

;

TypeError

:

'tuple'

object

does

not

support item assignment

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

Constructing tuples with 0 or 1 element is special and has some extra syntax rules:


tup1 = ()    # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号

If you want to create a tuple with a single element, add a comma after the element to distinguish it from a plain value, because without the comma Python interprets the parentheses as those used in mathematical expressions:

not_a_tuple = (42)  # 这是整数 42,不是元组

string、list and tuple all belong to sequence types.

Note:


Set

A Set in Python is an unordered, mutable data type used to store unique elements. Elements in a set do not repeat, and common set operations such as intersection, union, and difference are supported.

In Python, sets use braces {} with elements separated by commas, and can also be created with the set() function.

Note:An empty set must be created with set() instead of {}, because {} creates an empty dictionary.

Creation format:


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

Example

#!/usr/bin/python3

sites

=

{

'Google'

,

'Taobao'

,

'Runoob'

,

'Facebook'

,

'Zhihu'

,

'Baidu'

}

print

(

sites

)

 

Output the set (unordered, duplicate elements are removed automatically)

Membership test

if

'Runoob'

in

sites:

   

print

(

'Runoob is in the set'

)

else

:

   

print

(

'Runoob is not in the set'

)

Sets support set operations

a

=

set

(

'abracadabra'

)

b

=

set

(

'alacazam'

)

print

(

a

)

         

Unique characters in a

print

(

a - b

)

     

Difference of a and b (in a but not in b)

print

(

a | b

)

     

Union of a and b (in a or in b)

print

(

a & b

)

     

Intersection of a and b (in both a and b)

print

(

a ^ b

)

     

Symmetric difference of a and b (in a or b, but not both)

The example above produces the following output:


{'Zhihu', 'Baidu', 'Taobao', 'Runoob', 'Google', 'Facebook'}
Runoob 在集合中
{'b', 'c', 'a', 'r', 'd'}
{'r', 'b', 'd'}
{'b', 'c', 'a', 'z', 'm', 'r', 'l', 'd'}
{'c', 'a'}
{'z', 'b', 'm', 'r', 'l', 'd'}

Dictionary

A dictionary is another very useful built-in data type in Python.

A dictionary is a mapping type identified by {}, and it is a collection of key : value pairs. Keys must be of an immutable type and must be unique within the same dictionary.

Note:Starting with Python 3.7, dictionaries preserve theinsertion orderof elements and are no longer unordered. If you need the features of an ordered dictionary, just use a plain dict .

Example

#!/usr/bin/python3

my_dict

=

{

}

my_dict

[

'one'

]

=

"1 - Runoob Tutorial"

my_dict

[

2

]

   

=

"2 - Runoob Tools"

tinydict

=

{

'name'

:

'runoob'

,

'code'

:

1

,

'site'

:

'www.runoob.com'

}

print

(

my_dict

[

'one'

]

)

     

Output the value of key 'one'

print

(

my_dict

[

2

]

)

         

Output the value of key 2

print

(

tinydict

)

           

Output the complete dictionary

print

(

tinydict.

keys

(

)

)

     

Output all keys

print

(

tinydict.

values

(

)

)

   

Output all values

The example above produces the following output:


1 - Runoob Tutorial
2 - 菜鸟工具
{'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name', 'code', 'site'])
dict_values(['runoob', 1, 'www.runoob.com'])

constructor dict() A dictionary can be built directly from a sequence of key/value pairs:

Example

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

}

{x: x**2 for x in (2, 4, 6)} uses a dictionary comprehension; for more on comprehensions see:Python Comprehensions。

In addition, the dictionary type has some built-in functions, such as clear()、keys()、values() , etc.

Note:


The bytes type

In Python3, the bytes type represents an immutable binary sequence. Unlike strings, elements of bytes are integer values (integers between 0 and 255), not Unicode characters.

The bytes type is typically used to handle binary data such as image, audio, and video files. In network programming, bytes are also commonly used to transmit binary data.

The most common way to create a bytes object is with the b prefix:

Example

x

=

b

"hello"

         

Create a bytes object with the b prefix

print

(

x

)

             

b'hello'

print

(

type

(

x

)

)

       

print

(

x

[

0

]

)

           

104 (the ASCII value of 'h'; bytes elements are integers)

You can also use bytes() The function converts objects of other types to bytes; the second argument specifies the encoding:

x = bytes("hello", encoding="utf-8")

Like strings, bytes supports slicing, concatenation, searching, replacement, and other operations. Because bytes is immutable, modifying it requires creating a new bytes object:

Example

x

=

b

"hello"

y

=

x

[

1

:

3

]

         

Slicing, yielding b'el'

z

=

x + b

"world"

   

Concatenation, yielding b'helloworld'

print

(

y

)

           

b'el'

print

(

z

)

           

b'helloworld'

Note that bytes elements are integer values, so comparisons must use the corresponding integer values. You can use the ord() function to convert a character to its integer value:

Example

x

=

b

"hello"

if

x

[

0

]

==

ord

(

"h"

)

:    

ord("h") returns 104

   

print

(

"The first element is 'h'"

)


Python data type conversion

Sometimes we need to convert built-in data types; simply use the data type as a function name. In the next chapter Python3 Data Type Conversion it is explained in detail.

The following built-in functions perform conversions between data types; they return a new object representing the converted value:

function Description

int(x [,base])

Convert x to an integer

float(x)

Convert x to a float

complex(real [,imag])

Create a complex number

str(x)

Convert object x to a string

repr(x)

Convert object x to an expression string

eval(str)

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 a mutable set

dict(d)

Create a dictionary. d must be a sequence of (key, value) tuples.

frozenset(s)

Convert to an immutable set

chr(x)

Convert an integer to the corresponding character

ord(x)

Convert a character to its integer value (Unicode code point)

hex(x)

Convert an integer to a hexadecimal string

oct(x)

Convert an integer to an octal string