Learn python · basic data types

Basic Usage

notes

In Python, #+ statement is a comment, or you can use 'comment block'

#Life is short. I use Python

output

In Python, print() is the output function

print("Hello World!")

variable

What are variables?

Memory space and stored values

Understanding of num = 10

Assign 10 to the memory space of the variable named num

Naming conventions

  • Variable names can use letters, numbers, underscores "",
  • Cannot start with a number
  • Strictly case sensitive
  • Do not use Chinese
  • Do not use keywords

In addition, the naming conventions of variables are applicable to script names, later function names and other command specifications

How variables are defined

In Python, defining variables does not need to specify the data type

#The first variable definition method
a = 10
b = 20

#The second definition method
a,b = 30,40

Thinking: how to realize the data exchange between the following two variables

# Define two variables
a = 10
b = 20

'''
Common method to complete the exchange of variable data
c = a
a = b
b = c
'''

# The data exchange of variables is realized by using the syntax of defining ratio variables in python
a,b = b,a



Data type of python

The type() function can return the current data type

Data type classification

  • String string
  • Number type number
  • Integer int
  • Floating point float
  • complex
  • Boolean bool
  • List list
  • Tuple tuple
  • Dictionary dict
  • Set set

Variable data types: list, dictionary, set
Immutable data types: string, number, tuple

Container type data: string, list, tuple, set, dictionary
Non container type data: numeric, Boolean

String type

  • Both single and double quotation marks can define a string, which needs to be wrapped manually
  • Three quotation marks define a string that wraps automatically
  • Quotes can be nested within each other, but not within themselves
  • Escape characters can be used in strings, such as \ r \n \t
  • If you don't want to escape characters in a string, you can add love = r'\nihao \shijie' when defining characters
# The definition is to use single quotation marks or double quotation marks
love = 'iloveyou'
hello = "Hello world"

# You can also use three quotation marks to define a large string, which is generally used to define a large text string, and a large string can wrap
s = '''
Like this one
 A long, long article...
'''

Number type

# Number type number
'''
int   integer
float Floating point type
complex complex
bool  Boolean types can be automatically converted to numeric types( True 1,False 0)
'''
varn = 521
varn = -1111

varn = 3.1415926

varn = 0x10  # hexadecimal

varn = b'001100111' # bytes

# complex
varn = 5+6j  # complex

# Numeric types can participate in operations
a = 10
b = 20
print(a+b)

List list type

  • A list is used to represent a series of data
  • The data stored in the list can be of any type
  • Use brackets to define [],
  • Each data is separated by commas,
  • Each set of data stored in the list is called an element
  • Get element by subscript
  • A list in the list is called a two-level list or a multi-level list
'''
About subscripts in lists
  0   1   2    3    4 
['a','b',521,'pai',3.1415926]
 -5   -4   -3  -2   -1
'''

Tuple tuple type definition

  • Tuples are defined with parentheses ()
  • The only difference between tuples and lists is that values cannot be changed
vart = (1,2,3,'a','b')
# Other ways to define tuples
vart = 1,2,3

Note that when defining a tuple, if there is only one element in the tuple, you need to add "," otherwise it is not a tuple type

vart = (1,)

Dict dictionary type

  • Use * * braces {} * * to define

  • Dictionary is the storage method of key value pairs name: admin

  • The key must be of string or numeric type, and the value can be of any type

  • The key name cannot be repeated, and the value can be repeated

# For example, you need to record the relevant data of a book, book title, author, price,...
vard = {'title':'<<Guiguzi>>','author':'Guiguzi','price':'29.99'}
# print(vard,type(vard))
# {'title': '< Guiguzi > >','author ':' Guiguzi ','price':'29.99 '} < class' dict' >

# Gets the value in the dictionary
print(vard['title'])
# The keys in the dictionary cannot be reused, or they will be overwritten
vard = {'a':10,'b':10,'c':20,'a':'aa',1:'abcdef','2':'2222'}
# print(vard)

Set set type

  • A set set is a data type of an unordered set with no duplicate elements
  • The set set is defined using brackets or the set() method
  • If you need to define an empty set, you can only use the set() method, because curly braces are empty dictionaries
  • Sets are mainly used for operations, intersection, difference, union and symmetric sets
a = {1,2,3,'a'}
# Adding elements to a collection
# a.add('b')
# Individual elements in the collection cannot be obtained, but can be added and deleted
# a.discard('a')
# print(a)
# Check whether the current element is in the collection
# print(1 in a)


# Sets are mainly used for operations, intersection, difference, union and symmetric sets
a = {1,2,3,'a','b'}
b = {1,'a',22,33}

print(a & b) # Intersection {1, 'a'}
print(a - b) # The difference set {'b', 2,3} a set has, and b set does not
print(a | b) # Union set {1, 2, 3, 33, 'a', 'b', 22} two sets, put them together, and remove the duplication
print(a ^ b) # Symmetric difference set {33, 2, 3, 'b', 22} 

Data type conversion

  • What is data type conversion?
    • Converts one data type to another, such as a string to a number
  • Why do I need data type conversion?
    • Because operations cannot be performed between different data types
  • Form of data type conversion?
    • Automatic type conversion
    • Cast type

Automatic type conversion

  • When two different values are calculated, the result will be calculated with higher accuracy
    True = = > integer = = > floating point = = > complex
  • True is converted to the number 1 and False to the number 0 when calculating with a number

Cast type

Each data type in python has a corresponding method, which can convert the data type

  • str()
  • int() string is purely numeric. Convertible container type cannot be converted to numeric int type
  • The float() conversion rule is the same as the int type, and the result is a float type
  • bool() can convert other types to Boolean True or False
    False: '',0,0.0,False,[],{},(),set()
  • list() list / tuple() tuple / set() set
    • Number type cannot be converted
    • String conversion treats each character as an element
    • The three can be transformed into sets, and the results are disordered
    • The dictionary is not completely converted and only the keys in the dictionary are retained
  • dict() dictionary
    • The number type is not a container type and cannot be converted to a dictionary
    • Strings cannot be converted directly to dictionaries
    • The list / tuple can be converted into a dictionary. It is required to be a secondary list / tuple, and each secondary element can only have two values

Keywords: Python

Added by pedro_silva on Fri, 24 Dec 2021 13:12:52 +0200