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

Python Variable Types

Python Variable Types

Variables are values stored in memory, which means that creating a variable allocates a space in memory.

Based on the variable's data type, the interpreter allocates the specified memory and decides what data can be stored in memory.

Therefore, variables can be assigned different data types, and these variables can store integers, decimals, or characters.


Variable assignment

Variable assignment in Python does not require type declaration.

Each variable created in memory includes information such as the variable's identity, name, and data.

Every variable must be assigned a value before use; a variable is created only after it is assigned.

The equals sign = is used to assign values to variables.

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

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

counter

=

100

Assign integer variables

miles

=

1000.0

Floating-point

name

=

"

John

"

String

print

counter

print

miles

print

name

Run Example »

In the above example, 100, 1000.0, and "John" are assigned to the variables counter, miles, and name respectively.

Running the program above produces the following output:


100
1000.0
John

Assigning multiple variables

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 with value 1 is created, and the three variables are assigned to the same memory space.

You can also assign multiple variables to multiple objects. For example:

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

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


Standard data types

Data stored in memory can be of many types.

For example, a person's age can be stored as a number, and their name can be stored as characters.

Python defines several standard types for storing various kinds of data.

Python has five standard data types:


Python Numbers

Numeric data types are used to store numbers.

They are immutable data types, which means that changing a numeric data type allocates a new object.

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

var1 = 1
var2 = 10

You can also use the del statement to delete references to some objects.

The syntax of the del statement is:

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

You can use the del statement to delete references to single or multiple objects. For example:

del var
del var_a, var_b

Python supports four different numeric types:

Example

Some examples of numeric types:

int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3e+18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2E-12 4.53e-7j

Note:The long type exists only in Python 2.X. In versions after 2.2, int data that overflows is automatically converted to the long type. In Python 3.X, the long type was removed and replaced by int.


Python Strings

A string (String) is a sequence of characters composed of digits, letters, and underscores.

Generally written as:

s = "a1a2···an"   # n>=0

It is the data type used to represent text in a programming language.

Python's string indexing has two ordering schemes:

If you want to get a substring from a string, you can use [start_index:end_index] to slice the corresponding string. The indices start at 0 and can be positive or negative; an index can be left empty to indicate taking from the beginning or to the end.

The substring obtained by [start_index:end_index] includes the character at start_index but excludes the character at end_index.

For example:


>>> s = 'abcdef'
>>> s[1:5]
'bcde'

When using a string separated by a colon, Python returns a new object whose result contains the consecutive content marked by this pair of offsets, with the left starting boundary included.

The above result includes the value b of s[1], while the maximum range obtained does not includethe end index, which is the value f of s[5].

The plus sign (+) is the string concatenation operator, and the asterisk (*) is the repetition operator. As in the following example:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

str

=

'

Hello World!

'

print

str

Output the complete string

print

str

[

0

]

Output the first character of the string

print

str

[

2

:

5

]

Output the substring from the third to the sixth character of the string

print

str

[

2

:

]

Output the string starting from the third character

print

str

2

Output the string twice

print

str

"

TEST

"

Output the concatenated string

The example above produces the following output:


Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python Lists

List is the most frequently used data type in Python.

Lists can implement most collection-type data structures. They support characters, numbers, strings, and can even contain lists (i.e., nesting).

Lists are denoted by [ ] and are the most versatile compound data type in Python.

Slicing values in a list can also use the variable [start_index:end_index] to slice the corresponding list. Left-to-right indexing starts at 0 by default, right-to-left indexing starts at -1 by default, and an index can be left empty to indicate taking from the beginning or to the end.

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

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

list

=

[

'

runoob

'

,

786

,

2.23

,

'

john

'

,

70.2

]

tinylist

=

[

123

,

'

john

'

]

print

list

Output the complete list

print

list

[

0

]

Output the first element of the list

print

list

[

1

:

3

]

Output the second to third elements

print

list

[

2

:

]

Output all elements from the third to the end of the list

print

tinylist

2

Output the list twice

print

list

tinylist

Print the combined list

The example above produces the following output:


['runoob', 786, 2.23, 'john', 70.2]
runoob
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['runoob', 786, 2.23, 'john', 70.2, 123, 'john']

Python list slicing can accept a third parameter, which acts as the step of the slice. The following example slices the string from index 1 to index 4 with a step of 2 (skipping one position):


Python Tuple

A tuple is another data type, similar to a List.

Tuples are denoted by (), with internal elements separated by commas. However, tuples cannot be reassigned, making them like read-only lists.

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

tuple

=

(

'

runoob

'

,

786

,

2.23

,

'

john

'

,

70.2

)

tinytuple

=

(

123

,

'

john

'

)

print

tuple

Output the complete tuple

print

tuple

[

0

]

Output the first element of the tuple

print

tuple

[

1

:

3

]

Output the second to fourth (exclusive) elements

print

tuple

[

2

:

]

Output all elements from the third to the end of the list

print

tinytuple

2

Output the tuple twice

print

tuple

tinytuple

Print the combined tuple

The example above produces the following output:


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

The following operations on the tuple are invalid, because tuples do not allow updates while lists do:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

tuple

=

(

'

runoob

'

,

786

,

2.23

,

'

john

'

,

70.2

)

list

=

[

'

runoob

'

,

786

,

2.23

,

'

john

'

,

70.2

]

tuple

[

2

]

=

1000

Illegal operation on a tuple

list

[

2

]

=

1000

Legal operation on a list

Tuples do not allow updates, so the above code produces an error, as follows:

Traceback (most recent call last):
  File "test.py", line 6, in 
    tuple[2] = 1000    # 元组中是非法应用
TypeError: 'tuple' object does not support item assignment

Python Dictionary

A dictionary is the most flexible built-in data structure in Python besides lists. A list is an ordered collection of objects, while a dictionary is an unordered collection of objects.

The difference between the two is that elements in a dictionary are accessed by key, not by offset.

A dictionary is denoted by "{ }". It consists of an index (key) and its corresponding value.

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

dict

= {}

dict

[

'

one

'

]

=

"

This is one

"

dict

[

2

]

=

"

This is two

"

tinydict

= {

'

name

'

:

'

runoob

'

,

'

code

'

:

6734

,

'

dept

'

:

'

sales

'

}

print

dict

[

'

one

'

]

Output the value whose key is 'one'

print

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 output is:


This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'runoob'}
['dept', 'code', 'name']
['sales', 6734, 'runoob']

Python Data Type Conversion

Sometimes we need to convert built-in data types; to convert a data type you simply use the type as a function name.

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

function Description

int(x [,base])

Convert x to an integer

long(x [,base] )

Convert x to a long integer

float(x)

Convert x to a floating-point number

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)

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 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 a character

unichr(x)

Convert an integer to a Unicode character

ord(x)

Convert a character to its integer value

hex(x)

Convert an integer to a hexadecimal string

oct(x)

Convert an integer to an octal string