Python variable types

Python variable types

A variable stores a value in memory. This means that a space is allocated in memory when the variable is created.

Based on the data type of the variable, the interpreter allocates the specified memory and decides what data can be stored in the 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 a type declaration.

Each variable is created in memory, including the variable's identifier, name, and data.

Each variable must be assigned a value before it is used, and the variable will not be created until the variable is assigned.

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

The left side of the equals (=) operator is a variable name, and the right side of the equals (=) operator is the value stored in the variable. E.g:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 # Assign integer variable miles = 1000.0 # Float name = "John" # String print counter print miles print name


Running the instance »

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

Executing the above program will output the following results:

100
1000.0
John

 

multiple variable assignments

Python allows you to assign values ​​to multiple variables at the same time. E.g:

a = b = c = 1

The above example creates an integer object with a value of 1, and the three variables are allocated to the same memory space.

You can also specify multiple variables for multiple objects. E.g:

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

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

 

Standard data types

The data stored in memory can be of many types.

For example, a person's age can be stored in numbers and his name can be stored in characters.

Python defines some standard types for storing various types of data.

Python has five standard data types:

  • Numbers
  • String (string)
  • List
  • Tuple (tuple)
  • Dictionary (dictionary)

 

Python numbers

Numeric data types are used to store numeric values.

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

Number objects are created when you specify a value:

var1 = 1
var2 = 10

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

The syntax of the del statement is:

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

You can delete references to single or multiple objects by using the del statement. E.g:

del var
del var_a, var_b

Python supports four different numeric types:

  • int (signed integer)
  • long (long integer [can also represent octal and hexadecimal])
  • float
  • complex (plural)

example

Instances of some 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
  • A lowercase l can also be used for long integers, but it is recommended that you use an uppercase L to avoid confusion with the number 1. Python uses L to display long integers.
  • Python also supports complex numbers. A complex number consists of a real part and an imaginary part, which 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.

 

Python string

A string or string (String) is a string of characters consisting of numbers, letters, and underscores.

Generally recorded as:

s="a1a2···an"(n>=0)

It is a data type in programming languages ​​that represents text.

Python's string list has 2 value orders:

  • From left to right, the default index starts from 0, and the maximum range is 1 less than the length of the string
  • Right-to-left indexing starts from -1 by default, the maximum range is the beginning of the string

If you want to obtain a substring from a string, you can use the variable [head subscript: tail subscript] to intercept the corresponding string, where the subscript starts from 0 and can be a positive number or Negative numbers, the subscript can be empty, which means to get the head or tail.

for example:

s = 'ilovepython'

The result of s[1:5] is love.

When using a colon-separated string, python returns a new object containing the contiguous content identified by the pair of offsets, starting on the left and including the lower bound.

The above result includes the value l of s[1], and the maximum range obtained does not include the upper boundary, which is the value p of s[5].

The plus sign (+) is the string concatenation operator, and the asterisk (*) is the repeat operation. The following example:

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- str = 'Hello World!' print str # prints the complete string print str[0] # prints the first character in the string print str[2:5] # prints the string between the third and fifth character in the string print str[2:] # prints the string starting at the third character print str * 2 # prints the string twice print str + "TEST" # print the concatenated string

The output of the above example is:

Hello World!
H
I cry
lo World!
Hello World!Hello World!
Hello World!TEST

 

Python list

List is the most frequently used data type in Python.

Lists can complete the data structure implementation of most collection classes. It supports characters, numbers, strings and can even contain lists (i.e. nested).

Lists are identified by [ ] and are python's most general composite data type.

The variable [head subscript: tail subscript] can also be used to cut the values ​​in the list, and the corresponding list can be intercepted. The default index from left to right starts with 0, and the default index from right to left starts with -1. The subscript can be Empty means to take the head or tail.

The plus sign + is the list concatenation operator, and the asterisk * is the repeat operation. The following 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 full list print list[0] # prints the first element of the list print list[1:3] # prints the second to third elements print list[2:] # prints all items from the third to the end of the list element print tinylist * 2 # print list twice print list + tinylist # print combined list

The output of the above example is:

 

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

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

Tuples are identified with "()". Inner elements are separated by commas. But tuples cannot be assigned twice, and are equivalent to 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 full tuple print tuple[0] # print the first element of the tuple print tuple[1:3] # print the second to third elements print tuple[2:] # print from the third to the list all elements at the end print tinytuple * 2 # print tuple twice print tuple + tinytuple # print combined tuple

The output of the above example is:

('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 are invalid tuples, because tuples are not allowed to update. And the list is allowed to be updated:

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 # tuple is illegal application list[2] = 1000 # list is legal application

 

Python dictionary

A dictionary is the most flexible built-in data structure type in python other than lists. 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 key, not by offset.

Dictionaries are identified with "{ }". A dictionary consists of an index (key) and its corresponding value value.

Example (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {' name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # print the value with the key 'one' print dict[2] # print the value with the key 2 print tinydict # prints the full dictionary print tinydict.keys() # prints all keys print tinydict.values() # prints all values

The output is:

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

 

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 conversions between data types. These functions return a new object representing the converted value.

function describe

int(x [,base])

convert x to an integer

long(x [,base] )

convert x to a long integer

float(x)

convert x to a float

complex(real [,imag])

create a plural

str(x)

convert object x to string

repr(x)

convert object x to expression string

eval(str)

Evaluates a valid Python expression in a string and returns an object

tuple(s)

convert the sequence s to a tuple

list(s)

convert the sequence s to a list

set(s)

Convert to mutable collection

dict(d)

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

frozenset(s)

Convert to Immutable Collection

chr(x)

Convert an integer to a character

unichr(x)

Convert an integer to Unicode character

word (x)

converts a character to its integer value

hex(x)

Convert an integer to a hex string

oct(x)

Convert an integer to an octal string

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325066029&siteId=291194637