1. Variables: Rules for variable definition: 1. The variable name can only be any combination of letters, numbers or underscores
2. The first character of the variable name cannot be a number
3. The following keywords Cannot be declared as a variable name
['and', 'as', 'assert',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else ', 'except', 'exec',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] Data type: 2. Numeric type : int (integer type) On a 32-bit machine, the number of integers is 32 bits, and the value range is -2**31~2**31-1, that is, -2147483648~2147483647. On a 64-bit system, the integer The number of digits is 64, and the value range is -2**63~2**63-1, that is, -9223372036854775808~9223372036854775807 long (long integer). Unlike C language, Python's long integer does not specify the bit width, that is: Python does not limit the size of long integer values, but in fact due to limited machine memory, the long integer values we use cannot be infinitely large. Note that since Python 2.2, if an integer overflow occurs, Python will automatically convert the integer data to a long integer, so now not adding the letter L after the long integer data will not cause serious consequences. float (Floating point type) Floating point numbers are used to deal with real numbers, that is, numbers with decimals. Similar to the double type in C language, it occupies 8 bytes (64 bits), of which 52 bits represent the base, 11 bits represent the exponent, and the remaining bit represents the symbol. Complex (complex number) A complex number consists of a real part and an imaginary part. The general form is x+yj, where x is the real part of the complex number and y is the imaginary part of the complex number. Here x and y are both real numbers. Note: There is a small number pool in Python: -5 ~
257 3. Boolean value True or False1 or 0 (values other than 0 are True) How to check the bool type of a variable? >>>bool(0) 4. The evil string splicing of strings: The string in python is reflected as a character array in C language. Every time you create a string, you need to open a continuous block in the memory. Empty, and once you need to modify the string, you need to open up space again. Every time the evil + sign appears, a new space will be opened up inside it. A simple understanding is to use the plus sign to splice strings, which wastes resources. String formatting name = 'ian'age = 12print('%s is %d years
old.' %(name,age))#The string is % s; integer %d; floating point number %f Commonly used functions of strings: str = 'ian is 12!! '# Remove blanks #This method will remove leading and trailing spaces and trailing \n newlines str.strip() # Split #split() will put the split fields into a list, separated by spaces by default, str.split(',') separated by commas s = str.split()print(type(s))print(s[ 1]) # Length print(len(str)) # Index # gives a string, which can output any character. If the index is a negative number, it is equivalent to counting from back to front. print(str[10])print(str[-4]) #Slice#Slicing is to separate part of the content from the given string print(str[0:3])print(str[:3]) 5. List creation list: list1 =
['apple','pear','peach'] or list1 =
list(['apple','pear','peach']) Common functions of lists: list =
['apple','pear','peach',66] # Index print(list[0]) # Slice, same as string print(list[0:2]) # Append list.append( 'banana')print(list) #Delete #remove method, delete elements, no return value #pop method, delete elements, return the value of the element, delete list from back to front by default.remove('banana')print(list) print('*' * 20)a = list.pop()print(a)print(list.pop(2)) #Delete peach, or use pop(-2) #Length, display the number of list elements print( len(list)) # Loop, how to loop a list? x = 0 #Add serial numbers to list elements for i in list: x += 1 print(x,i) #Include if 'apple' in list: print('in')else: print('out') 6. Origin Create a tuple: tuple1 =
('apple','pear','peach') or tuple1 =
tuple(('apple','pear','peach')) Commonly used operations for tuples: tuple1 =
('apple','pear','peach')#Tuples are basically the same as lists, but tuples cannot be modified after they are created, while lists can be modified# Index print(tuple1[1]) # Slice print(tuple1[1:3 ]) # Loop x = 0for i in tuple1: x += 1 print(x,i) # Length print(len(tuple1)) # Contains if 'apple' in tuple1: print('in')else: print(' out') 7. Dictionary Dictionary is unordered! ! ! ! Create a dictionary: dic =
{'k1':'v1','k2':'v2'} or dic =
dict({'k1':'v1','k2':'v2'} )Common operations on dictionary: dic =
{'k1':'v1','k2':'v2'} # Index #The index of the dictionary uses key as the key print(dic['k1']) # Add dic['k3'] = 'v3 'print(dic) # Delete #del is the same as remove in the list, the pop() method is still the same, delete the value and return del dic['k3']print(dic)del_key = dic.pop('k2')print( del_key)print(dic) #Key, value, key-value pair print('*'*20)dic =
{'k1':'v1','k2':'v2','k3':'v3 '}print(dic.keys()) #Only display keyprint(dic.values()) #Only display valueprint(dic.items()) #Display key and value # Loop for i in dic: #Default is .keys( ), you can use dic.values() or dic.items() print(i) # Length print(len(dic)) 8. Loop/range/break/continue#Loop #A simple for loop is as follows for i in [1,2,3]: print(i) #range function>>> range(1,5)
# represents from 1 to 5 (excluding 5)[1, 2, 3, 4] >>>
range(1,5,2) #Represents from 1 to 5, interval 2 (excluding 5)[1, 3]>>> range(5)
# Represents from 0 to 5 (excluding 5) [0, 1, 2, 3, 4] ps: The above is the display method of 2.0. It is not applicable in 3.0. In 3.0, you can use the loop to take out the #breakbreak statement, which can be used in for In loops and while loop statements. Simply put, the break statement will exit the loop immediately, and the loop body following it will not be executed. The #continuecontinue statement is also used in for loops and while loop statements. Using continue, you can skip this loop. The unfinished loop body does not loop, but directly proceeds to the next loop.
The above is the detailed content of Python basic content: data types. For more information, please follow other related articles on the PHP Chinese website!

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

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

Dreamweaver Mac version
Visual web development tools

Atom editor mac version download
The most popular open source editor
