Python variable type, python variable type

Source: Internet
Author: User

Python variable type, python variable type
Python variable type

The value of the variable stored in the memory. This means that a space is opened in the memory when a variable is created.

For variable-based data types, the interpreter allocates the specified memory and determines what data can be stored in the memory.

Therefore, variables can specify different data types, which can store integers, decimals, or characters.

Variable assignment

In PythonVariable does not need to be declaredVariable assignment is a process of variable declaration and definition.

Each variable created in the memory contains the variable identifier, name, and data.

Each variable must be assigned a value before it can be used.

Equals sign (=) is used to assign values to variables.

On the left side of the equal sign (=) operator is a variable name, and on 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 a value to the integer variable miles = 1000.0 # Floating Point name = "John" # string print counterprint milesprint name

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

Execute the above program and output the followingResult:

1001000.0John

 

Assign values to multiple variables

Python allows youAssign values to multiple variables. For example:

a = b = c = 1

For the above instance, create an integer object with a value of 1. The three variables are allocated to the same memory space.

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

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

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

Standard Data Type

Data stored in the memory can be of multiple types.

For example, the person. s age is stored as a numerical value and his or her addresses are stored as alphanumeric characters.

Python has some standard types used to define operations, and they are possible for each of them to store methods.

Python hasFive Standard Data Types:

  • Numbers (number)
  • String (String)
  • List)
  • Tuple (tuples)
  • Dictionary)

 

Python numbers

The numeric data type is usedStorage Value.

TheyIs an unchangeable Data TypeThis means that changing the numeric data type will allocate a new object.

When you specify a value, the Number object will be created:

var1 = 1var2 = 10

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

The syntax of the del statement is:

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

You can use the del statement to delete one or more objects. For example:

del vardel var_a, var_b

Python supports four different numeric types:

  • Int (signed integer)
  • Long (long integer [can also represent octal and hexadecimal])
  • Float (float type)
  • Complex (plural)

Instance

Some numeric instances:

Int Long Float Complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45. j
-786 0122L -21.9 9.322e-36j
080 0 xDEFABCECBDAECBFBAEl 32.3 + e18 . 876j
-0490 535633629843L -90. -. 6545 + 0J
-0x260 -052318172735L -32.54e100 3e + 26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
  • Long integers can also use lowercase "L", but we recommend that you use uppercase "L" to avoid confusion with numbers "1. Python uses "L" to display long integers.
  • Python also supports the complex number. The complex number consists of the real number and the virtual number. It can be expressed by a + bj or complex (a, B). The real part a and virtual Part B of the complex number are float.

 

Python string

A String is a String of numbers, letters, and underscores.

It is generally recorded:

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

It is the data type that represents text in programming languages.

The python string list has two values:

  • From left to right index starts from 0 by default, and the maximum range is 1 less String Length
  • From right to left index start from-1 by default. The maximum range is the start of the string.

If you wantObtainSectionSubstringYes.Use the variable [header Subscript: tail subscript]To extract the corresponding string. The subscript starts from 0 and can be a positive or negative number. The subscript can be null to indicate that the header or the end is obtained.

For example:

s = 'ilovepython'

S [1: 5]The result is love.

When a string separated by a colon is used, python returns a new object. The result contains the continuous content identified by the offset, and the start on the left contains the lower boundary.

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

The plus sign (+) is a String concatenation operator, and the asterisk (*) is a repeated operation. Example:

#! /Usr/bin/python #-*-coding: UTF-8-*-str = 'Hello World! 'Print str # print str [0] # print str [2] # print str [] # print str [2] between the third and fifth characters in the output string :] # print str * 2 # print str + "TEST" # output the connected string twice

Output result of the above instance:

Hello World!Hllollo World!Hello World!Hello World!Hello World!TEST
Python list

List is the most frequently used data type in Python.

The list can implement the data structure of most collection classes. It supports characters, numbers, strings, and even lists (so-called nesting ).

  The list is identified []. Is the most common Composite data type in python. You can see this code.

The variable [header Subscript: tail subscript] can also be used to split the list. The corresponding list can be truncated, starting from left to right index with 0 by default, from right to left, the index starts from-1 by default. The subscript can be null to indicate that the header or tail is obtained.

The plus sign (+) is a list join operator, and the asterisk (*) is a repeated operation. Example:

#! /Usr/bin/python #-*-coding: UTF-8-*-list = ['abcd', 786, 2.23, 'john', 70.2] tinylist = [123, 'john'] print list # print list of output complete list [0] # print list [] # print list of elements from the second to the third output [2 :] # print tinylist * 2 # print list + tinylist # print the combined list twice

Output result of the above instance:

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

Tuples are another data type, similar to List ).

The tuples are identified. Internal elements are separated by commas. However, an element cannot be assigned a value twice, which is equivalent to a read-only list.

#! /Usr/bin/python #-*-coding: UTF-8-*-tuple = ('abcd', 786, 2.23, 'john', 70.2) tinytuple = (123, 'john ') print tuple # print tuple [0] # print tuple [] # print tuple [] # print tuple [2:] # print tinytuple * 2, all elements from the third end to the end of the list # print tuple + tinytuple twice output tuples # print the combination of tuples

Output result of the above instance:

('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')

Below isInvalid tuplesBecause the tuples cannot be updated. The list can 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 # list of illegal applications in the tuples [2] = 1000 # list of valid applications

 

Python dictionary

A dictionary is the most flexible built-in data structure type in python except the list. A list is a combination of ordered objects, and a dictionary is a collection of unordered objects.

The difference between the two is that the elements in the dictionary are accessed by keys, rather than by offset.

  The dictionary is identified "{}". 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'] # print dict [2] # print tinydict # print the complete dictionary print with the output key 'one' tinydict. keys () # print all keys. values () # output all values

Output result:

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 data types and convert the data types. You only need to use the data type as the function name.

The following built-in functions can be used to convert data types. These functions return a new object, indicating the converted value.

Function Description

Int (x [, base])

Converts x to an integer.

Long (x [, base])

Converts x to a long integer.

Float (x)

Convert x to a floating point number.

Complex (real [, imag])

Create a plural number

Str (x)

Convert object x to a string

Repr (x)

Convert object x to an expression string

Eval (str)

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

Tuple (s)

Converts the sequence s into a single tuples.

List (s)

Converts sequence s to a list.

Set (s)

Convert to a variable set

Dict (d)

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

Frozenset (s)

Convert to an unchangeable set

Chr (x)

Converts an integer to a character.

Unichr (x)

Converts an integer to a Unicode character.

Ord (x)

Converts a character to an integer.

Hex (x)

Converts an integer to a hexadecimal string.

Oct (x)

Converts an integer to an octal string.

1. int functions:

(1) convert a numeric string in a mathematical format to an integer.
(2) convert a floating point number to an integer, but simply round it, instead of rounding it.

aa = int("124")    #Correctprint "aa = ", aa  #result=124bb = int(123.45) #correctprint "bb = ", bb #result=123cc = int("-123.45")  #Error,Can't Convert to intprint "cc = ",ccdd = int("34a")    #Error,Can't Convert to intprint "dd = ",ddee = int("12.3") #Error,Can't Convert to intprint ee

 

2. the float function converts integers and strings into floating-point numbers.

aa = float("124")     #Correctprint "aa = ", aa     #result = 124.0 bb = float("123.45")  #Correctprint "bb = ", bb     #result = 123.45cc = float(-123.6)    #Correctprint "cc = ",cc      #result = -123.6dd = float("-123.34") #Correctprint "dd = ",dd      #result = -123.34ee = float('123v')    #Error,Can't Convert to floatprint ee

 

3. The str function converts a number to a character.

aa = str(123.4)     #Correctprint aa            #result = '123.4'bb = str(-124.a)    #SyntaxError: invalid syntaxprint bbcc = str("-123.45") #correctprint cc            #result = '-123.45'dd = str('ddd')     #correctprint dd            #result = dddee = str(-124.3)    #correctprint ee            #result = -124.3

 

  Thank youThank you for your patience!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.