Chapter 2 python data types
Section 1 Number and string types
Is 123 the same as "123"
() [] {}
Computers are used to assist people, and the classification of the real world is also mapped in programming. to facilitate abstract analysis.
Number
String
List
Tuple
Dictionary
We look at some simple data types through data types, python will automatically identify the type of data
> ;>> num1=123
>>> type(123)
>>> num2=9999999999999999999
>>> type (num2)
>>> num='hello'
>>> type(num)
The range represented by integer int in python is -2,147, 483,648 to 2,147,483,6 47
For example: 0,100,,100
The range example of Int is as shown above.
>
Example:
>>> type(num)
>>> type(num)
> 3.14j, 8.32e-36j
Example:
>>> num=3.14j
>>> type(num)
>>> num
> ;>> print num
3.14j
>>>
We distinguish the following two different types of variables here
>>> a=123
>> ;> stra="123"
>>> print a
123
>>> print stra
>>> a+stra Here we find these two different types Variables cannot be operated on
Traceback (most recent call last):
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
>> collection.
>>> str1='hello world'
>>> str2="hello world"
>>> say='let's go' There is an error in this definition because When we define it here, it also contains a single quote
File "", line 1
say='let's go'
^
SyntaxError: invalid syntax
>>> say="let's go" We will Just change the outer single quotes to double quotes
>>> say="let's "go"" If there are double quotes inside our double quotes, we have to use escape characters
File "" , line 1
^
SyntaxError: invalid syntax
>>> print say
let's "go"
Let’s look at the use of some escape characters
>>> mail='tom: hello i am jack'
>>> print mail
> >> mail='tom:n hellon i am jack' For the above characters, if we want to use line breaks to output
>>> mail
>> > print mail
tom:
hello
i am jack
Below we use triple quotes to achieve the line break effect:
>>> mail="""tom:
... i am jack
... goodbye
... "" "
>>> print mail
tom:
i am jack
goodbye
>>> mail Here we can see that when we use triple quotes, he will record our input
'tom a=' abcde'
'a'
'b'
>> ;> a[0]+a[1] If we want to take multiple, we can use the + sign in the middle to connect
Use slicing to get the value
>>> a
'abcde'
Let's take a look at the operation here, a[start position: end position + 1: step size]
'bcd'
>>> a[:4] This means cutting off from the beginning to d
'abcd'
>> ;> a[4:] >> a[::1] Get the value by step size. It is more clear when the step size is 2 below'abcde'
>>> a[::2]
>>> a[-4:-1] Get the value through negative index, here we start from back to front, -1 represents the second to last value
'bcd'
> >> a[-2:-4:-1] He first reverses all the numbers, and then cuts off the value from the second position to the third position of 'dc'
'dcb'
Section 2 Sequence
a. Lists, tuples and strings are all sequences
b. Two of the sequence The main features are index operators and slicing operators.
—The index operator allows us to grab a specific item from a sequence.
——The slice operator allows us to obtain a slice of the sequence, that is, a part of the sequence.
c. The index can also be a negative number, and the position is calculated from the end of the sequence.
——Note: The returned sequence starts from the start position and ends just before the end position. That is, the starting position is included in the sequence slice, and the ending position is excluded from the slice.
a.shoplist[1:3] returns a sequence slice starting at position 1, including position 2, but stopping at position 3, therefore returning a slice containing two items. shoplist[:] returns a copy of the entire sequence. You can do slicing with negative numbers. Negative numbers are used starting from the end of the sequence. For example, shoplist[:-1] returns a sequence slice containing all but the last item.
Basic operations on sequences
1.len(): Find the sequence length
2.+: Connect 2 sequences
3.*: Repeating sequence elements
4.in: Determine whether the element is
5.max () in the sequence: the maximum value of the return
6.min (): return to the minimum value
7.cmp (tuplel, tuple2) whether the sequence value compares the two sequence values of 2 sequence values Same
Let’s do it now:
>>> a
'abcde'
>>> len(a)
5
>>> str1='123'
> ;>> str2='adbs'
>>> str1+str2
'123adbs'
>>> str1*5 This way str1 will be repeated five times
'12312312312 3123 '
>>> "#"*40
'################################# #####'
>>> str2
'adbs'
>>> 'c' in str2 Check whether the character 'c' is not in the string str2 and returns False. Return True
False
>>> 'a' in str2
True
You can also use not in to judge if it is not inside
>>> 'c' not in str2
True
>> ;> max(str1)
'3'
>>> max(str2)
's'
>>> min(str2)
'a'
cmp(str1, str2) used for comparison of two strings
>>> str1='12345'
>>> str2='abcde'
>>> cmp(str1,str2)
-1
>>> str2='123'
>>> cmp(str1,str2)
1
>>> str2='12345' At this time, the two values are equal , returns 0 when comparing
>>> cmp(str1,str2)
0
Section 3 Tuple ()
Tuples are very similar to lists, except that tuples and characters Strings are immutable i.e. you cannot modify tuples.
— Tuples are defined by comma-separated items in parentheses.
- Tuples are usually used when a statement or user-defined function can safely take a set of values, that is, the value of the used tuple will not change.
>>> str2='12345'
>>> id(str2)
139702043552192
>>> gt; id(str2)
>>> userinfo="milo 30 male"
>>> userinfo[:4]
'milo'
>>> userinfo1="zou 25 famale"
>>> ; userinfo1[:4]
'zou '
>>> t=("milo",30,"male") If we use the tuple definition here, it will be much more convenient to get the value
>>> t[0]
'milo'
>>> t[1]
30
>>> t[2]
Create a tuple
——An empty tuple consists of a pair of empty parentheses
. ——General tuples
a.zoo = ('wolf','elephant','penguin')
b.new_zoo = ('monkey','dolphin',zoo)
>>> t1=(2,) using using using out out out out out out out of - ‐ ‐ ‐‐‐ defining an empty tuple
> type (t)
>
——Tuple values are also immutable
>>> t=('milo',30,'male')
>>> t
>>> t[1]
30
Traceback (most recent call last):
File "" , line 1, in
>>> t
('milo', 30, 'male')
>>> name,age,gender=t
>>> name
'milo'
>>> age
30
>>> gender
'male'
Section 4 Sequence-Tuple
List[]
1) List is a data structure that handles a set of ordered items, that is, you can store a sequence in a list s project.
2) Lists are variable type data
3) List composition: Use [] to represent a list, which contains multiple numbers or strings separated by commas.
——List1=['Simon','David','Clotho','Zhang San']
——List2=[1,2,3,4,5]
——List3= ["str1","str2","str3","str4","str5"]
>>> listmilo=[] Definition of empty list
>>> type(listmilo)
> ; t[0]
'milo'
'milo'
>>> listmilo[0:2] Get value from list
> ;> l3=['abc']
>>> type(l3) Here we can see that it is a list
>>> type(t3)
List operation
——Value
a. Slicing and indexing
b.list[]
——Delete
a.del (list[]) .var in list
>>> listmilo[0] Here we find that lists can change the value of stored elements
'milo'
>>> listmilo[0]='zou'
>>> listmilo [0]
'zou'
Let's introduce how to add an element to the list
>>> listmilo
['milo', 30, 'male']
>>> listmilo.append("123444555")
>>> listmilo
['milo', 30, 'male', '123444555'] At this time we found that the fourth element has been added to the listmilo list
> del(listmilo[1]) We can also use del to delete values in the list through the index of the list
>>> listmilo
['milo', 'male']
>>> help(list.remove)
remove(...)
Raises ValueError if the value is not present.
(END)
>>> help(len) This is how to view the usage of some internal functions
Quick Start with Objects and Classes
1) Objects and classes, better understand lists.
2) Object = Attribute + Method
3) List is an example of using objects and classes.
——When you use variable i and assign a value to it, such as assigning an integer 5, you can think that you have created an object (instance) i of class (type) int.
——help(int)
4) Classes also have methods, which are functions defined only for the class.
——These functions can only be used by objects of this class.
——For example:
a. Python provides the append method for the list class. This method allows you to add an item at the end of the list.
b.mylist.append('an item') adds a string to the list mylist. Note the use of dot notation to use object methods.
5) Classes also have variables, variables defined only for classes.
——These variables/names can only be used in objects of this class.
——Used through dots, such as mylist.field.
Section 5 Dictionary {}
1) Dictionary is the only mapping type (hash table) in python
2) Dictionary objects are mutable, but dictionary keys must be immutable Object, and different types of key values can be used in a dictionary.
3) key() or values() returns a key list or a value list
4) items() returns a tuple containing key-value pairs.
Create dictionary:
- {}
- Use factory method dict()
Example: fdict=dict(['x',1],['y',2])
- Built-in method: fromkeys(), the elements in the dictionary have the same value, the default is None
Example: ddict={}.fromkeys(('x','y'),-1)
>>> dic [0]
0
1
>>> dic[2]
2
>>> dic1={'name':'milo' ,'age':25,'gender':'male'} It will be more meaningful to define it like this
>>> dic1['name'] It will be more purposeful when we take the value
>>> dic1['age']
25
'male'
>>> dic2={1:'123','name':'milo','x':456}
>>> dic2
{1: '123', ' name': 'milo', 'x': 456}
Next let's look at another example:
>>> a=1 Here we first define two variables
>>> b =2
>>> dic3={a:'aaa','b':'bbb'} If a is not defined, an error will appear here
>>> dic3[1]
'aaa'
>>> dic3[2] Here we finally see the difference. In fact, in the dictionary, he does not use the value defined before b
Traceback (most recent call last):
File "", line 1, in
KeyError: 2
>>> dic3['b']
'bbb'
>>> dic1
{'gender': 'male', 'age ': 25, 'name': 'milo'}
>>> for k in dic1: Here we can see the convenience of using a dictionary
... Print k
...
gender
age
name
>
- Access updates directly using key values; the built-in uodate() method can copy the contents of the entire dictionary to another dictionary.
- del dict1['a'] deletes the element with key a in the dictionary
a. dict1.pop('a') deletes and returns the element with key 'a'
b. dict1. clear() deletes all elements of the dictionary
c. del dict1 deletes the entire dictionary
>>> l
>>> l[5 ]=7
Traceback (most recent call last):
IndexError: list assignment index out of range
>>> dic1
>>> dic1['tel']='123454565' Here we see that when using a dictionary, we can add a value without error
>> ;> dic1
We see that he is not added to the end , because the dictionary itself is not fixed, the dictionary is disordered, and the hash type value can directly operate the elements in the dictionary through the dictionary key
>>> dic1['tel']=' 888888888'
>>> dic1
{'gender': 'male', 'age': 25, 'tel': '888888888', 'name': 'milo'}
& gt; & gt; & gt; DIC1.pop ('Age') The corresponding value of the pop -up key 'ag', there is no Age in the dictionary, the key value of the AGE
25 & gt; & gt; {{'genre': ':': ':': ': male', 'tel': '888888888', 'name': 'milo'}
>>> dic1.clear() Clear the dictionary
>>> dic1
>>> ; del(dic1) Delete the dictionary directly
>>> dic1
File "", line 1, in
NameError: name 'dic1' is not defined
Dictionary-related built-in functions:
- type(), str(), cmp() (cmp is rarely used for dictionary comparison, and the comparison is the size, key, and value of the dictionary in order).
Factory function dict():
- For example: dict(zip('x','y'),(1,2)) or dict(x=1,y=2)
- - { 'y':2,'x':1}
- Using a dictionary to generate a dictionary is slower than using copy, so it is recommended to use copy() in this case.
1) len(), hash() (used to determine whether an object can be used as a dictionary key, non-hash types report TypeError).
2) dict.clear(): Delete all elements in the dictionary.
3) dict.fromkeys(seq, val=None): Create and return a dictionary with the elements in seq as keys, and val is the specified default value.
4) dict.get(key, default=None): Returns the value of key. If the key does not exist, returns the value specified by default.
5) dict.has_key(key): Determine whether the key exists in the dictionary. It is recommended to use in and not in instead.
6) dict .items(): Returns a list of key-value pair tuples.
7) dict.keys(): Returns the list of keys in the dictionary.
8) dict.iter*(): iteritems(), iterkeys(), itervalues() return iteration instead of list.
9) dict.pop(key[,default]): Same as get(), the difference is that if the key exists, delete and return its dict[key], if it does not exist, the default value is not specified, and a KeyError exception is thrown.
10) dict.setdefault(key, default=None): Same as set(), if key exists, its value is returned. If key does not exist, dict[key]=default.
11) dict.update(dict2): Add the key-value pairs in dict2 to the dictionary dict. If there are repeated overwrites, entries that do not exist in the original dictionary are added.
12)dict. values(): Returns a list of all values in the dictionary.
>>> dic.get(3) We check the dictionary
>>> dic.get(3,'error') When it does not exist in the dictionary, the definition returns error
'error'
We can practice other examples. If we don’t understand, we can use the help function.
>>> dic1={'a':123,'b':456,1:111,4:444}
>>> dic1.keys()
['a', 1, 'b', 4]
>>> dic1.values()
[123, 111, 456, 444]
The above is the content of Chapter 2 python data types. For more related content, please Follow the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
