This article brings you code examples about variables and operators in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
What is a variable
Assume two lists to perform mathematical operations
>>> [1,2,3,4,5,6] [1,2,3] Traceback (most recent call last): File "<pyshell>", line 1, in <module> [1,2,3,4,5,6] [1,2,3] TypeError: list indices must be integers or slices, not tuple //A B,先把A乘以3,然后加上B,最后再加上列表A >>> [1,2,3,4,5,6]*3+[1,2,3]+[1,2,3,4,5,6] [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2, 3, 4, 5, 6] >>> A = [1,2,3,4,5,6] >>> print(A) [1, 2, 3, 4, 5, 6] >>> B = [1,2,3] >>> A*3 + B + A [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2, 3, 4, 5, 6]</module></pyshell>
Naming rules for variable names
Variable names can only use letters, numbers, and underscores
>>> 1a = 2 //变量名的首字母不能是数字 SyntaxError: invalid syntax >>> A2 = '1' >>> _2 = '1' >>> A*B='1' SyntaxError: can't assign to operator
System keywords, cannot be used in variable names Reserved keywords
>>> and = 1 SyntaxError: invalid syntax >>> if = 2 SyntaxError: invalid syntax >>> import = 3 SyntaxError: invalid syntax >>> type = 3 //type不是系统保留关键字,但是不建议作为变量名,否则极易出错 >>> print(type) 3 >>> type = 1 >>> type(1) Traceback (most recent call last): File "<pyshell>", line 1, in <module> type(1) TypeError: 'int' object is not callable >>> 1(1) Traceback (most recent call last): File "<pyshell>", line 1, in <module> 1(1) TypeError: 'int' object is not callable</module></pyshell></module></pyshell>
Features of python dynamic language, not required when declaring Specify the variable type
>>> a = '1' >>> a = 1 >>> a = (1,2,3) >>> a = {1,2,3}
Value type and reference type
int, str, and tuple are value types (immutable), and list, set, and dict are reference types (can Change)
1.int
>>> a = 1 >>> b = a >>> a = 3 >>> print(b) 1
2.list
>>> a = [1,2,3,4,5] >>> b = a >>> a[0] = '1' >>> print(a) ['1', 2, 3, 4, 5] >>> print(b) ['1', 2, 3, 4, 5] >>> a = [1,2,3] >>> id(a) 4405825224 >>> hex(id(a)) '0x1069b8ec8' >>> a[0]='1' >>> id(a) 4405825224 >>>
3.str
>>> a = 'hello' >>> a = a + 'python' //a加上一个新的字符串,不再是原来的字符串了 >>> print(a) hellopython >>> b = 'hello' >>> id(b) 4405534032 >>> b = b + 'python' //加上新的字符串后,id改变 >>> id(b) 4355329456 >>> 'python'[0] 'p' >>> 'python'[0]='o' Traceback (most recent call last): File "<pyshell>", line 1, in <module> 'python'[0]='o' TypeError: 'str' object does not support item assignment</module></pyshell>
4.tuple
>>> a = (1,2,3) >>> a[0] = '1' Traceback (most recent call last): File "<pyshell>", line 1, in <module> a[0] = '1' TypeError: 'tuple' object does not support item assignment >>> b = [1,2,3] >>> b.append(4) >>> print(b) [1, 2, 3, 4] >>> c = (1,2,3) >>> c.append(4) Traceback (most recent call last): File "<pyshell>", line 1, in <module> c.append(4) AttributeError: 'tuple' object has no attribute 'append' >>> a = (1,2,3,[1,2,4]) >>> a[2] 3 >>> a[3] [1, 2, 4] >>> a[3][2] 4 >>> a = (1,2,3,[1,2,['a','b','c']]) >>> a[3][2][1] 'b' >>> a = (1,2,3,[1,2,4]) >>> a[2] = '3' Traceback (most recent call last): File "<pyshell>", line 1, in <module> a[2] = '3' TypeError: 'tuple' object does not support item assignment >>> a[3][2] = '4' >>> print(a) //元组内的列表可变 (1, 2, 3, [1, 2, '4'])</module></pyshell></module></pyshell></module></pyshell>
Operator
1. Arithmetic operators: ,-,*,/,//,%,**
>>> 'hello'+'world' 'helloworld' >>> [1,2,3]*3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> 3-1 2 >>> 3/2 1.5 >>> 3//2 //整除 1 >>> 5%2 //求余 1 >>> 2**2 //求N次方 4 >>> 2**5 32
2. Assignment operators: =, =,- =, *=, /=, %=, **=, //=
>>> c = 1 >>> c = c+1 >>> print(c) 2 >>> c+=1 >>> print(c) 3 >>> c-=1 >>> print(c) 2 >>> c++ //python中没有自增和自减运算符 SyntaxError: invalid syntax >>> c-- SyntaxError: invalid syntax >>> b=2 >>> a=3 >>> b+=a >>> print(b) 5 >>> b-=a >>> print(b) 2 >>> b*=a >>> print(b) 6
3. Comparison (relational) operators: ==, ! =, >, =,
>>> 1==1 True >>> 1>1 False >>> 1>=1 True >>> a>=b Traceback (most recent call last): File "<pyshell>", line 1, in <module> a>=b NameError: name 'a' is not defined >>> a=1 >>> b=2 >>> a!=b True >>> b=1 >>> b+=b>=1 //b=b+True >>> print(b) 2 >>> print(b>=1) True >>> 1>1 False >>> 2>3 False >>> 'a'>'b' False >>> ord('a') 97 >>> ord('b') 98 >>> 'abc'>> ord('abc') Traceback (most recent call last): File "<pyshell>", line 1, in <module> ord('abc') TypeError: ord() expected a character, but string of length 3 found >>> ord('c') 99 >>> ord('d') 100 >>> [1,2,3]>> (1,2,3)<p>4. Logical operators: and, or, not</p> <pre class="brush:php;toolbar:false">>>> True and True True >>> True and False False >>> True or False True >>> False or False False >>> not False True >>> not True False >>> not not True True
0 is considered False, non-0 means True
>>> 1 and 1 1 >>> 'a' and 'b' 'b' >>> 'a' or 'b' 'a' >>> not 'a' False >>> a = True >>> b = False >>> a or b True >>> b and a False
Empty string False
>>> not 0.1 False >>> not '' True >>> not '0' False
Empty list False
>>> not [] True >>> not [1,2] False >>> [1] or [] [1] >>> [] or [1] [1] >>> 'a' and 'b' 'b' >>> '' and 'b' '' >>> 1 and 0 0 >>> 0 and 1 0 >>> 1 and 2 2 >>> 2 and 1 1 >>> 0 or 1 1 >>> 1 or 0 1 >>> 1 or 2 1
5.Member operator: in, not in
>>> a = 1 >>> a in [1,2,3,4,5] True >>> b = 6 >>> b in [1,2,3,4,5] False >>> b not in [1,2,3,4,5] True >>> b = 'h' >>> b in 'hello' True >>> b not in (1,2,3,4,5) True >>> b not in {1,2,3,4,5} True >>> b = 'a' >>> b in {'c':1} False >>> b = 1 >>> b in {'c':1} False >>> b = 'c' >>> b in {'c':1} //字典里面根据key返回 True
6.Identity operation Symbol: is, is not
Three characteristics of the object: id, value, type, use "is" to judge id, use "==" to judge value, and use "isinstance" to judge type
>>> a = 1 >>> b = 1 >>> a is b True >>> a='hello' >>> b='world' >>> a is b False >>> c='hello' >>> a is c True >>> a=1 >>> b=2 >>> a==b False >>> a=1 >>> b=1 >>> a is b True >>> a==b True >>> a=1 >>> b=1.0 >>> a==b True >>> a is b //is不是比较值相等,比较的是两个变量的身份(内存地址)是否相等 False >>> id(a) 4374928384 >>> id(b) 4376239272 >>> a={1,2,3} >>> b={2,1,3} >>> a==b //集合是无序的 True >>> a is b False >>> id(a) 4433997384 >>> id(b) 4433996488 >>> c=(1,2,3) >>> d=(2,1,3) >>> c==d //元组是序列,是有序的 False >>> c is d False >>> a=1 >>> b=2 >>> a==b False >>> a is b False >>> a = 'hello' >>> type(a) == int False >>> type(a) == str True >>> isinstance(a,str) //isinstance是判断变量类型的函数 True >>> isinstance(a,int) False >>> isinstance(a,(int,str,float)) True >>> isinstance(a,(int,float)) False
7. Bitwise operators: (== Operate numbers as binary numbers==)
&bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise negation
>>Move right
Bitwise AND operation, compare each binary digit, two If both are 1, you get 1. As long as one of them is 0, you get 0
>>> a = 2 >>> b = 3 >>> a & b 2
Variable | Convert to decimal | |||
---|---|---|---|---|
1 | 0 | 2 | ||
1 | 1 | 3 | ||
0 | 2 |
Convert to decimal |
||||
---|---|---|---|---|
0 | 2 |
b |
||
1 | 3 |
Bitwise OR |
||
1 | 3 |
The above is the detailed content of Code examples of variables and operators in python. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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