1 Data type
Different types of variables can perform different operations, so the type of the variable must be understood. Data types in python can be divided into:
Built-in types :
Numeric type: Integer type int, floating point type float, complex number (complex) 3 5j
str:String
bool:Boolean value [True, False]
None: Null value, indicating that the variable has no determined value
list: List
tuple:tuple
dict:dict
set:Collection
Custom type:
##class: Class
Numeric type:
Integer type (int): There is only one type of int in python3, which can represent integers, for example: 10, -5, 10000
Floating point type (float): represents a real number with a decimal point, There are two representations:
- Decimal representation: 1.9 .23
- Scientific notation: Use e to represent the exponent of 10 , 1e2 represents 100. Note that e must be preceded by a numerical value, and e must be followed by an integer
Complex: represents an irrational number in mathematics , in the form: a bj
Boolean type (bool): represents the two states of the transaction, male and female, cloudy and sunny, light and dark Wait, it has only two values: True, False
None: represents an empty object, generally used for judgment, different from 0 and empty characters
String (str): In python, use quotes (single quotes, double quotes, triple quotes) to represent strings
Representation of string:
# Use single quotes to express: 'hello'# Use double quotes to express: "I use python"
# Use 3 A single quotation mark means: it can represent multi-line text, for example:
'''The great
's
motherland
'''
# It means 3 double quotation marks: it can represent multi-line text , for example:
"""Be optimistic about life and death,
Just do it if you don't accept it"""
Escape characters: Some special characters cannot Input from the keyboard can be represented by escape characters. In addition, whether it is a single quotation mark, double quotation mark or triple quotation mark string, the quotation mark is the string delimiter, and the quotation mark is not the content of the string. So how to enter a single quotation mark string? Indicates a single quote, which can also be expressed using escape characters. Common escape characters
Escape characters | Description | Escape characters | Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
##\' | represents an ordinary character single quote \n | line break |
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
\" | represents an ordinary character double quote \r | ##Enter | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
\\ |
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
\a | Ring | ##\t |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
\b | Delete one character back |
The computer cannot store it directly String, but we can encode the characters, for example, use 65 to represent uppercase character A, 66 to represent uppercase character B... etc. This representation method is the American ASCII code, which can only represent 127 characters, but for Americans That's enough. Once we can use integers to represent characters, we can easily represent integers in binary, and strings can be easily stored in the computer. 1.2 Type judgmentWe can use type and isinstance to test and judge the data type #type用法: type(obj) 功能:返回obj的数据类型 参数:obj是你要测试变量或数值 示例: age = 10 name = 'hello' print(type(name),type(age)) #判断变量是否是指定类型 if type(age) is int: print('是') else: print('否') #isinstance用法: isinstance(obj,typename) 功能:判断obj是否是指定类型,是返回True,否返回False 参数: objobj是你要判断的变量或数值 typename是指定数据类型,可以是int,float,str等。也可是一个 类型的元组,例如:(int,float) 示例: age = 10 name = 'hello' print(isinstance(age,int)) print(isinstance(name,(str,int)) #只要name是str或int的一种就返回True if isinstance(age,int): print('是') else: print('否') #type和isinstance的区别 type判断基本类型是没问题的,但无法判断子类对象是父类的一种 isinstance可以判断子类对象是父类的一种 class A: pass class B(A): pass objA = A() objB = B() #输出否 if type(objB) is A: print('是') else: print('否') print(isinstance(objB,A)) #True Conclusion:Use first isinstance 2. Operators and expressionsIn order to calculate the results in mathematics, we will write some formulas to calculate, for example:
This is a calculation formula in mathematics. There are similar formulas in python for calculation, called expressions. In the expression, 30 and 5 are called operands, called operators. The purpose of an expression is to compute a result. Expression composition:
Based on the above, the so-called expression is composed of operands and operators An expression that conforms to python syntax. To write expressions, you first need to learn operators. There are two things to know about operators
2.1 Arithmetic operatorsa = 20 b = 10
注意:
2.5 赋值运算符
注意:
a = 2 b = 3 a *= b + 2 #等价于 a = a * (b + 2) print(a) # a = 10 2.6 关系运算关系运算就是比较运算,如果表达式成立,返回True,否则返回False。关系运算的结果是布尔值。
注意:
2.7 逻辑运算逻辑运算符可以用于构造复杂条件。逻辑运算符包括:
在逻辑运算中,False、None、0、0.0、‘’(空字符串)被看做假(False),其它的看做真(True) 2.7.1 逻辑与
2.7.2 逻辑或
2.7.3 Logic Not
Summary: If a is true, the expression is False, otherwise the expression is True 2.8 Short-circuit calculation
2.9 Notes
2.10 Identity operatoris: Determine whether two identifiers refer to the same entity [object]. What is compared is whether the ids of the two objects are the same. If they are the same, it is true, otherwise it is false is not: Determine whether two identifiers refer to different entities [objects] If the ids of the two objects are different, the result is true, otherwise it is false id() function gets the id of the entity ( Address) Note: The difference between is and ==
2.11 Member operatoris mainly used in sequences in in: Returns True if the specified value is found in the specified sequence, otherwise returns False not in: Returns if the specified value is not found in the specified sequence True, otherwise it returns False 2.12 if-else expressionexpression 1 if condition else expression 2, if the condition is true or false, the result is the value of expression 1, otherwise the result is expression Value of equation 2 |
The above is the detailed content of How to use python variable data types and operators. For more information, please follow other related articles on the PHP Chinese website!

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.


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

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
