Details of Python variables and data types

  • 2020-05-26 09:27:42
  • OfStack

Python variable type

The value of a variable stored in memory. This means that when you create a variable, you create a space in memory.

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

Thus, variables can specify different data types that can store integers, decimals, or characters.

Variable assignment

The variable assignment in Python does not require a type declaration.

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

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

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

The left of the equal sign (=) operator is a variable name, and the right of the equal sign (=) operator is the value stored in the variable. Such as:


#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
counter = 100 #  Assign an integer variable 
miles = 1000.0 #  floating-point 
name = "John" #  string 
 
print(counter)
print(miles)
print(name)

In the above example, 100,1000.0 and "John" are assigned to the counter, miles, 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. Such as:

[

a = b = c = 1

]

For the example above, create an integer object with a value of 1 and 3 variables assigned to the same memory space.

You can also specify multiple variables for multiple objects. Such as:

[

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

]

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

Note:

The following keywords cannot be declared as variables:

[

and, as, assert, break, class, continue, def, del, elif, else, except, exec, elif, global, if, import, in, is, pass, print, raise, return, try, while, ES1 01EN, yield, id

]

Data types in Python

1. The integer

[

int = 20
print int
print 45678 + 0x12fd2

]

2. The floating point number

[

float = 2.3
print float

]

3. The string

a, single quotation marks (')
Use single quotes to represent strings, for example:

[

str = 'this is string'
print str

]

b, use double quotation marks (")
Strings in double quotes are used exactly the same as strings in single quotes, for example:

[

str = "this is string";
print str

]

c, use 3 quotes (" ")
Use 3 quotation marks to represent multi-line strings. You can use single and double quotation marks freely in 3 quotation marks. For example:

[

str = '''this is string
this is pythod string
this is string'''
print str

]

4. The Boolean value

and: and operations, and is True only if all are True.
or: or operation, as long as one of them is True, the result of or operation is True.
not: non-operator, which is a single unary operator that turns True into False and False into True.

bool = False
print bool
bool = True
print bool

5. A null value

The null value is a special value in Python, represented by None.
None cannot be understood as 0 because 0 is meaningful and None is a special null value.

A list of 6.


# -*- coding:utf-8 -*-

lst = ['A', 'B', 1996, 2017]
nums = [1, 3, 5, 7, 8, 13, 20]

#  Access the values in the list 
print "nums[0]:", nums[0] # 1
print "nums[2:5]:", nums[2:5] # [5, 7, 8]
print "nums[1:]:", nums[1:] # [3, 5, 7, 8, 13, 20]
print "nums[:-3]:", nums[:-3] # [1, 3, 5, 7]
print "nums[:]:", nums[:] # [1, 3, 5, 7, 8, 13, 20]

#  Update the list 
nums[0] = "ljq"
print nums[0]

#  Delete list elements 
del nums[0]
'''nums[:]: [3, 5, 7, 8, 13, 20]'''
print "nums[:]:", nums[:]

#  List script operator 
print len([1, 2, 3]) # 3
print [1, 2, 3] + [4, 5, 6] # [1, 2, 3, 4, 5, 6]
print ['Hi!'] * 4 # ['Hi!', 'Hi!', 'Hi!', 'Hi!']
print 3 in [1, 2, 3] # True
for x in [1, 2, 3]:
  print x, # 1 2 3

#  List the interception 
L = ['spam', 'Spam', 'SPAM!']
print L[2] # 'SPAM!'
print L[-2] # 'Spam'
print L[1:] # ['Spam', 'SPAM!']

#  The list of functions & methods 
lst.append('append') #  Add a new object to the end of the list 
lst.insert(2, 'insert') #  Insert the object into the list 
lst.remove(1996) #  Removes the th of a value from the list 1 A match 
lst.reverse() #  Reverse the elements in the list, inverting 
print lst.sort() #  Sort the original list 
print lst.pop(1) #  Remove from the list 1 An element ( By default the last 1 An element ) , and returns the value of that element 
print lst
print lst.count('obj') #  Counts the number of times an element appears in a list 
lst.index('append') #  Find a value from the list 1 The index position of the matching item and the index from 0 start 
lst.extend(lst) #  At the end of the list 1 Secondary adjoin another 1 Multiple values in a sequence of ( Extend the original list with the new list )
print 'End:', lst

7. The dictionary
Dictionaries (dictionary) are the most flexible built-in data structure type in python after 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 of a dictionary are accessed by keys, not by offsets.


# -*- coding:utf-8 -*-

dit = {'name': 'Zara', 'age': 7, 'class': 'First'}
dict1 = {'abc': 456}
dict2 = {'abc': 123, 98.6: 37}
seq = ('name', 'age', 'sex')
#  Access the dictionary values 
print "dit['name']: ", dit['name']
print "dit['age']: ", dit['age']

#  To modify a dictionary 
dit["age"] = 27 #  Modify the value of the existing key 
dit["school"] = "wutong" #  Add a new key / The value of 
print "dict['age']: ", dit['age']
print "dict['school']: ", dit['school']

#  To delete a dictionary 
del dit['name'] #  The delete key is 'name' The entry of 
dit.clear() #  Empty the dictionary of all entries 
del dit #  Delete the dictionary 

dit = {'name': 'Zara', 'age': 7, 'class': 'First'}

#  Dictionary built-in function & methods 
cmp(dict1, dict2) #  Compare two dictionary elements. 
len(dit) #  Count the number of dictionary elements, that is, the total number of keys. 
str(dit) #  Output the printable string representation of the dictionary. 
type(dit) #  Returns the type of the input variable, or the dictionary type if the variable is a dictionary. 
dit.copy() #  return 1 A shallow copy of a dictionary 
dit.fromkeys(seq) #  create 1 A new dictionary to sequence seq Is the key to the dictionary, val Is the initial value corresponding to all the keys of the dictionary 
dit.get(dit['name']) #  Returns the value of the specified key if the value is not returned in the dictionary default value 
dit.has_key('class') #  If the key is in the dictionary dict In return true Otherwise return false
dit.items() #  Returns traversable as a list ( key ,  value )  Tuples array 
dit.keys() #  Return as a list 1 All the keys to a dictionary 
dit.setdefault('subject', 'Python') #  and get() similar ,  But if the key does not already exist in the dictionary, the key is added and the value is set to default
dit.update(dict2) #  Put the dictionary dict2 The key of / The value pair is updated to dict In the 
dit.values() #  Returns all values in the dictionary as a list 
dit.clear() #  Delete all elements in the dictionary 

8 yuan

The tuples of Python (tuple) are similar to lists, except that the elements of the tuples cannot be modified; Tuples use parentheses (), lists use square brackets []; The creation of tuples is as simple as adding elements in parentheses separated by commas (,).


# -*- coding:utf-8 -*-

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = "a", "b", "c", "d"

#  Access to a tuple 
print "tup1[0]: ", tup1[0] # physics
print "tup1[1:3]: ", tup1[1:3] # ('chemistry', 1997)

#  Modify the tuple 
tup4 = tup1 + tup2
print tup4 # (12, 34.56, 'abc', 'xyz')

#  To delete a tuple 
tup = ('tup3', 'tup', 1997, 2000)
print tup
del tup

#  Tuples index & The interception 
L = ('spam', 'Spam', 'SPAM!')
print L[0] # spam
print L[1] # Spam
print L[2] # 'SPAM!'
print L[-2] # 'Spam'
print L[1:] # ['Spam', 'SPAM!']

#  Tuple built-in functions 
print cmp(tup3, tup2) #  Compare two tuple elements. 
len(tup3) #  Count the number of tuple elements. 
max(tup3) #  Returns the maximum value of an element in a tuple. 
min(tup3) #  Returns the minimum value of an element in a tuple. 
L = [1, 2, 3, 4]
print L
print tuple(L) #  Converts a list to a tuple. 

9. Define a string

[

\n for newline
\t represents a TAB character
\\ represents \ character itself

]

10. Unicode string

[

Python default encoding ASCII encoding

# -*- coding: utf-8 -*-

]

101. Numeric type conversion

[

int(x [,base]) converts x to an integer
float(x) converts x to a floating point number
complex(real [,imag]) creates a complex number
str(x) converts the object x to a string
repr(x) converts the object x to an expression string
eval(str) is used to evaluate a valid Python expression in a string and return an object
tuple(s) converts the sequence s to a tuple
list(s) converts the sequence s to a list
chr(x) converts an integer to a character
unichr(x) converts an integer to Unicode characters
ord(x) converts a character to its integer value
hex(x) converts an integer into a base 106 string
oct(x) converts an integer into an 8-base string

]

This site this site from a number of articles collated and combined, just 1 from learning python.


Related articles: