Home > Article > Backend Development > Analyze examples of variables, operators, and flow control in Python.
Enter "python3" in the terminal, and then enter python code
Enter "python3 text file path" in the terminal
Variables in Python do not need to be declared. Each variable must be assigned a value before use. The variable will not be created until the variable is assigned a value.
In Python, a variable is a variable, it has no type. What we call "type" is the type of the object in memory pointed by the variable.
The equal sign (=) is used to assign values to variables.
The left side of the equal sign (=) operator is a variable name, and the right side of the equal sign (=) operator is the value stored in the variable.
Variable name = variable value.
The variable name is used to receive the variable value
name = 'nick' age = 19
The variable name has A certain meaning
consists of numbers/letters/underscores, and cannot start with numbers and underscores
Cannot use Python keywords
['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']
Camel case:NameOfNick
Underscore:name_of_nick
(recommended)
Constants are a convention, and constant names are defined in all uppercase letters. can actually be modified.
AGE_OF_NICK = 19 print(AGE_OF_NICK)
Number of references to variable values
x = 257 # 257的引用计数为1 y = x # 257的引用计数为2 del x # 257的引用计数为1
When the reference count of the variable value is 0, the variable value will be automatically recycled by Python to occupy its memory
[-5, 256] integers will automatically open a memory to store these integers when the Python interpreter starts. In other words, these small integers will not be deleted because the reference count is 0.
Getting the id of a variable can be understood as the address of the variable in memory.
x = 10 print(x) # 获取变量的变量值 print(id(x) ) # 获取变量的id,可以理解成变量在内存中的地址 print(type(x) ) # 获取变量的数据类型,下章会详细介绍数据类型
Result:
10
8790885504960
Variables with equal ids must have equal values because they point to the same memory address;
Variables with equal values may not have equal ids.
x = 11 y = x z = 11 print(x == y) # True print(x is y) # True print(x is z) # True,整数池的原因 x = 255 z = 255 print(id(x) is id(z) ) # False
The following example creates an integer object with a value of 10 and assigns three values from back to front. Variables are assigned the same numerical value.
a = b = c = d = 10 print(f'a:{a}, b:{b}, c:{c}, d:{d}') #a:10, b:10, c:10, d:10
# 交叉赋值 x = 10 y = 20 x, y = y, x print(x, y) #20 10 # 相当于使用临时变量 x = 10 y = 20 temp = x x = y y = temp print(x, y) #20 10
You can also specify multiple variables for multiple objects. For example:
a, b, c = 1, 2, "runoob"
In the above example, two integer objects 1 and 2 are assigned to variables a and b, and the string object "runoob" is assigned to variable c.
Write a Fibonacci series:
# 两个元素的总和确定了下一个数 a, b = 0, 1 while b < 10: print(b, end=',') a, b = b, a+b # 1,1,2,3,5,8,
name = input('请输入你的姓名:') pwd = input('请输入你的密码:') print(type(name)) print(type(pwd)) # 请输入你的姓名:a # 请输入你的密码:1 # # 'str'>
No matter the value we enter is a numeric type, a string type, or a list type , the input values received are all string types.
%s: receive arbitrary data Type data
%d: Receive numeric type data
name = 'nick' age = 19 print('my name is %s my age is %d' % (name, age)) # my name is nick my age is 19
{}: Receive data of any data type.
name = 'nick' age = 19 #1、括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。 print("Hello, {}. You are {}.".format(name, age)) # Hello, nick. You are 19. 2、在括号中的数字用于指向传入对象在 format() 中的位置 print("Hello, {1}. You are {0}-{0}.".format(age, name)) # Hello, nick. You are 19-19. 3、如果在 format() 中使用了关键字参数, 那么它们的值会指向使用该名字的参数。 print("Hello, {name}. You are {age}-{age}.".format(age=age, name=name))# Hello, nick. You are 19-19. 4、位置及关键字参数可以任意的结合: print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'Runoob', other='Taobao'))
{
<.precision> | ||||||
---|---|---|---|---|---|---|
symbol padded single character |
< ;: left-aligned | >: right-aligned^: center-aligned The output width set by the slot |
Thousands separator for numbers | Floating point number decimal | or maximum output length of string |
|
%c: 格式化字符及其ASCII码
%s: 格式化字符串
%d: 格式化整数
%u: 格式化无符号整型
%o: 格式化无符号八进制数
%x: 格式化无符号十六进制数
%X: 格式化无符号十六进制数(大写)
%f: 格式化浮点数,可指定小数点后的精度
%e: 用科学计数法格式化浮点数
%E: 作用同%e,用科学计数法格式化浮点数(大写)
%g: %f和%e的简写
%G: %f 和 %E 的简写
%p: 用十六进制数格式化变量的地址
print("{0: =^20 }".format("PYTHON")) # '=======PYTHON=======' 使用等号,居中对齐 print("{0: *>20 }".format("BIT")) # '*****************BIT' 使用星号,文字右对齐 print("{:10}".format("BIT")) # 'BIT ' 总长度为10,不足以空格补足。在:后传入一个整数, 可以保证该域至少有这么多的宽度。 用于美化表格时很有用。 print("{0: ,.2f}".format(12345.6789)) # '12,345.68' 使用千分符,同时保留到小数点后两位 print("{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(425)) # '110101001,Ʃ,425,651,1a9,1A9' print("{0:e},{0:E},{0:f},{0:%}".format(3.14)) # '3.140000e+00,3.140000E+00,3.140000,314.000000%'
可以使用 bin,oct,hex 可输出数字的二进制,八进制,十六进制形式,例如:
a = 0b111100 print(bin(a)) # '0b111100' print(oct(a)) # '0o74' print(hex(a)) # '0x3c'
字典, 然后使用方括号 [] 来访问键值 :
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} print('{0[Runoob]:d}; {0[Google]:d}; {0[Taobao]:d}'.format(table)) # 2; 1; 3
也可以通过在 table 变量前使用 ** 来实现相同的功能:
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} print('{Runoob:d}; {Google:d}; {Taobao:d}'.format(**table)) # 2; 1; 3
f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。
在字符串前面加上f或F,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去。
用了这种方式明显更简单了,不用再去判断使用 %s,还是 %d。
name = "nick" age = 19 print(F"Hello, {name}. You are {age}.")#Hello, nick. You are 19. print(f'{age*2}')#38 salary = 6.6666 print(f'{salary:.2f}')#6.67 w = {'name': 'Runoob', 'url': 'www.runoob.com'} print(f'{w["name"]}: {w["url"]}') # 'Runoob: www.runoob.com'
在 Python 3.8 的版本中可以使用 = 符号来拼接运算表达式与结果:
x = 1 print(f'{x+1}') # Python 3.6 # 2 x = 1 print(f'{x+1=}') # Python 3.8 # 'x+1=2'
+、 - 、* 、/ 、 //、 % 、**
# 除 print(10 / 3) # 3.3333333333333335 # 除,只取整数部分 print(10 // 3) # 3 print(10 // 4) # 2 # %:取余 print(10 % 3) # 1 # **,幂 print(10 ** 3) # 1000
and、 or、 not 。
优先级:not>and>or
# 从左到右的方式找到逻辑运算符,找到逻辑运算符的左边,左边成立,再去找到逻辑运算符的右边 print(3 > 3 and 1 > 2 or 2 > 1) # False
>、 >=、 运算符,可以使用 != 代替)
=、 +=、 -=、 *=、 /=、 //=、 **=、 %=、:=(海象运算符,可在表达式内部为变量赋值。Python3.8 版本新增运算符。)
is、 is not
is和==的区别:
is:用于判断两个变量引用对象是否为同一个(是否在同一块内存空间中),
==:用于判断引用变量的值是否相等。
& : 按位与运算符
| : 按位或运算符
^: 按位异或运算符
~ : 按位取反运算符
>> : 右移动运算符
a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0 c = a & b print( c)# 12 = 0000 1100 c = a | b print(c)# 61 = 0011 1101 c = a ^ b print( c)# 49 = 0011 0001 c = ~a print( c)# -61 = 1100 0011 c = a << 2 print(c)# 240 = 1111 0000 c = a >> 2 print(c)# 15 = 0000 1111
in、 not in
包括字符串,列表或元组等
a = 10 b = 20 list = [1, 2, 3, 4, 5] print(a in list) # false
如果需要某个运算符优先运算,则加个括号,使用a and b is c == d
的是傻逼
hobby_list = ['read','run','sleep','fishing','piao'] # 如果取第2-3个爱好 _,hobby2,hobby3,*_ = hobby_list print(hobby2, hobby3) #run sleep
字典也是可以的,但是字典解压缩的是key。
info = {'name': 'nick', 'age': 18} x, y = info print(x, y) #name age
Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。
注意:
1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句。
# if if 条件: 代码块 # if...else if 条件: 代码块 else: 代码块 # if...elif....elif...else if 条件: 代码块 elif 条件: 代码块 elif 条件: 代码块 ...(可以写任意个elif) else: 代码块
同样需要注意冒号和缩进。另外,在 Python 中没有 do..while 循环。
#while while 条件: 代码块 #while + break while 条件: 代码块 break # 结束本层循环,跳出循环 # while + continue while 条件: 代码块 if 条件: 代码块 cotinue # 不执行下面代码,然后继续循环,即跳出本次循环 代码块 #while + else while 条件: 代码块 else: print('如果我没有被break,我就会被打印出来')
实例:
n = 1 while n < 4: print(n) n += 1 else: print("a") # 1,2,3,a
使用循环嵌套来实现99乘法法则:
# 外边一层循环控制行数 # i是行数 i = 1 while i <= 9: # 里面一层循环控制每一行中的列数 j = 1 while j <= i: mut = j * i print("%d*%d=%d" % (j, i, mut), end=" ") j += 1 print("") i += 1 # 1*1=1 # 1*2=2 2*2=4 # 1*3=3 2*3=6 3*3=9 # 1*4=4 2*4=8 3*4=12 4*4=16 # 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 # 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 # 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 # 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 # 1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
for循环的循环次数受限于容器类型的长度,而while循环的循环次数需要自己控制。
#for for i in range/str/list/tuple/dict/set(可迭代对象): print(i) #for + break for i in range/str/list/tuple/dict/set(可迭代对象): print(i) break # 结束本层循环 # for + continue for i in range/str/list/tuple/dict/set(可迭代对象): print(i) if 条件: continue # 结束本次循环,即不执行下面代码,继续循环 代码块 #for + else for i in range/str/list/tuple/dict/set(可迭代对象): print(i) else: print('如果我没有被break,我就会被打印出来')
实例:
# for循环按照索引取值 name_list = ['nick', 'jason', 'tank', 'sean'] for i in range(len(name_list)): print(i, name_list[i]) # 0 nick # 1 jason # 2 tank # 3 sean
如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列,例如:
for i in range(5): print(i) # 0 1 2 3 4
你也可以使用range指定区间的值:
for i in range(5, 9): print(i) # 5 6 7 8
也可以使range以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做'步长'):
for i in range(0, 10, 3): print(i) # 0 3 6 9
负数:
for i in range(-10, -100, -30): print(i) # -10 -40 -70
您可以结合range()和len()函数以遍历一个序列的索引,如下所示:
a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] for i in range(len(a)): print(i, a[i]) # 0 Google 1 Baidu 2 Runoob 3 Taobao 4 QQ
还可以使用range()函数来创建一个列表:
a = list(range(5)) print(a) # [0, 1, 2, 3, 4]
1-100 的和:
print(sum(range(101)))
Python pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句,如下实例
while True: pass # 等待键盘中断 (Ctrl+C)
最小的类:
class MyEmptyClass: pass
The above is the detailed content of Analyze examples of variables, operators, and flow control in Python.. For more information, please follow other related articles on the PHP Chinese website!