Python basic in...login
Python basic introductory tutorial
author:php.cn  update time:2022-04-18 16:14:50

Python variable types


The value that a variable stores in memory. This means that when a variable is created, a space is created in memory.

Based on the data type of the variable, the interpreter allocates the specified memory and determines what data can be stored in the memory.

Therefore, variables can specify 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 and includes information such as the variable's identification, name and data.

Each variable must be assigned a value before use. The variable will not be created until the variable is assigned a value.

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

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:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

counter = 100 #Assign integer variable
miles = 1000.0 # Floating point type
name = "John" # String

print counter
print miles
print name

Running 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 variables Assignment

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

a = b = c = 1

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

You can also specify multiple variables for multiple objects. For example:

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

In the above example, two integer objects 1 and 2 are assigned to variables a and b, 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 is stored as a numeric value and his or her address is stored as alphanumeric characters.

Python has some standard types for defining operations on them and storage methods possible for each of them.

Python has five standard data types:

  • Numbers (numbers)

  • String (strings)

  • List(List)

  • Tuple(Tuple)

  • Dictionary(Dictionary)



Python Number

Number data type is used to store numerical values.

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

When you specify 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 References to single or multiple objects can be deleted by using the del statement. For example:

del var
del var_a, var_b

Python supports four different number types:

  • int (signed integer type)

  • long (long integer type [can also represent octal and hexadecimal])

  • float ( Floating point type)

  • complex (plural number)

Examples

Examples of some numeric types:

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.20 45.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e100 3e+26J
0x69-4721885298529L70.2-E124.53e-7j
  • Long integers can also use lowercase "L", but it is recommended that you use uppercase "L" to avoid confusion with the number "1". Python uses "L" to display long integers.

  • Python also supports complex numbers. Complex numbers are composed of real parts and imaginary parts, and 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

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

Generally recorded as:

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

It is the representation text in programming language data type.

Python's string list has two value orders:

  • The index starts from left to right by default 0, and the maximum range is 1 less than the string length

  • The right-to-left index starts from -1 by default, and the maximum range is the beginning of the string

If you actually want to get a substring, You can use the variable [head subscript: tail subscript] to intercept the corresponding string. The subscript starts from 0 and can be a positive or negative number. The subscript can be empty to indicate that the head or tail is retrieved.

For example:

s = 'ilovepython'

s[1:5]The result of 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 boundary.

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 repetition operation. The following example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

str = 'Hello World!'

print str         # Output the complete string
print str[0]       # Output the first character in the string
print str[2:5]   # Output the third to fifth characters in the string A string between
print str[2:] # Output the string starting from the third character
print str * 2 # Output the string twice
print str + "TEST" # Output Connected string

The above example output result:

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


Python List


List (list) is the most frequently used data type in Python.


List can complete the data structure implementation of most collection classes. It supports characters, numbers, strings and can even contain lists (so-called nesting).

Lists are marked with [ ]. It is the most common composite data type in Python. Just look at this code to understand.

The variable [head subscript: tail subscript] can also be used to split the values ​​in the list, and the corresponding list can be intercepted. The index from left to right defaults to 0, and the index from right to left defaults to - Starting from 1, the subscript can be empty to indicate getting to the beginning or end.

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-

list = [ 'abcd', 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 starting from the third to the end of the list
print tinylist * 2 # Output List twice
print list + tinylist #Print the combined list

The above example output result:


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


Python tuple

Tuple is another data type, similar to List (list).

Tuples are identified with "()". Internal elements are separated by commas. However, tuples cannot be assigned values ​​twice and are equivalent to read-only lists.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

tuple = ( 'abcd', 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 third elements
print tuple[2:] # Output all elements from the third to the end of the list
print tinytuple * 2 # Output element Group twice
print tuple + tinytuple #Print the combined tuple

The above example output result:

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

The following tuples are invalid because tuples are not allowed to be updated. The list is allowed to be updated:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

tuple = ( 'abcd ', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Illegal application in tuple
list[2] = 1000 #The list is a legal application


Python meta-dictionary

The dictionary is a python other than the list The most flexible built-in data structure type. A list is an ordered combination 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 through keys, not offsets.

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

#!/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'] # Output the value with the key 'one'
print dict[2] # Output the value with the key 2
print tinydict # Output the complete Dictionary
print tinydict.keys() #Output all keys
print tinydict.values() #Output all values

The output result 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. To convert the data type, 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.

##ord(x)Convert a character to its integer valuehex(x)Convert a Convert an integer to a hexadecimal stringoct(x)Convert an integer to a Octal string
FunctionDescription
##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 string

repr(x)

Convert object x to expression string

eval(str)

Used to evaluate a valid Python expression in a string and return an object

tuple(s)

Convert sequence s into a tuple

list(s)

Convert sequence s to a list

set(s)

Convert to a variable set

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 characters