python基础篇第二篇
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础篇第二篇相关的知识,希望对你有一定的参考价值。
一、数据运算
举个例子一目了然就明白什么是运算符了;例子10+20=30,其中10,20为操作符 ,“+” 称为运算符。
python支持支持的类型运算符有:算术运算、比较(关系)运算符、赋值运算符、逻辑运算符、位运算符、成员运算符、身份运算符、运算符优先级,下面我们一个个来看。
1、算数运算:
假设变量a=10,变量b=20:
运算符 | 描述 | 实例 |
---|---|---|
+ | 加 - 两个对象相加 | a + b 输出结果 30 |
- | 减 - 得到负数或是一个数减去另一个数 | a - b 输出结果 -10 |
* | 乘 - 两个数相乘或是返回一个被重复若干次的字符串 | a * b 输出结果 200 |
/ | 除 - x除以y | b / a 输出结果 2 |
% | 取模 - 返回除法的余数 | b % a 输出结果 0 |
** | 幂 - 返回x的y次幂 | a**b 为10的20次方, 输出结果 100000000000000000000 |
// | 取整除 - 返回商的整数部分 | 9//2 输出结果 4 , 9.0//2.0 输出结果 4.0 |
练习实例:
1 #!/usr/bin/env python 2 # -*- coding :utf-8 -*- 3 4 a = 10 5 b = 20 6 7 c = a + b #两数相加 8 print(c) 9 10 c = a - b #两数相减 11 print(c) 12 13 c = a * b #两数相乘 14 print(c) 15 16 c = a / b #两数相除 17 print(c) 18 19 c = a % b #取模,返回除法的余数 20 print(c) 21 22 c = a ** b #幂(次方) 23 print(c) 24 25 c = a // b #取整数,返回商的整数部分 26 print(c)
以上练习实例执行结果
1 C:\\Python\\Python35\\python.exe E:/Python课程/s13/day2/运算符.py 2 30 3 -10 4 200 5 0.5 6 10 7 100000000000000000000 8 0 9 10 Process finished with exit code 0
2、比较运算符:
运算符 | 描述 | 实例 |
---|---|---|
== | 等于 - 比较对象是否相等 | (a == b) 返回 False。 |
!= | 不等于 - 比较两个对象是否不相等 | (a != b) 返回 true. |
<> | 不等于 - 比较两个对象是否不相等(一般都用!=,在python3中已被移除) | (a <> b) 返回 true。这个运算符类似 != 。 |
> | 大于 - 返回x是否大于y | (a > b) 返回 False。 |
< | 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 | (a < b) 返回 true。 |
>= | 大于等于 - 返回x是否大于等于y。 | (a >= b) 返回 False。 |
<= | 小于等于 - 返回x是否小于等于y。 | (a <= b) 返回 true。 |
实例练习:
1 a=66 2 b=88 3 c=0 4 5 a = 10 6 b = 20 7 8 9 if (a == b): #等于 10 print(‘a等于b‘) 11 else: 12 print(‘a不等于b‘) 13 14 if (a != b): #不等于 15 print(‘a不等于b‘) 16 else: 17 print(‘a等于b‘) 18 19 # if (a <> b): #不等于(python2.x) 20 # print(‘a不等于b‘) 21 # else: 22 # print(‘a等于b‘) 23 24 25 if (a < b): #小于 26 print(‘a小于b‘) 27 else: 28 print(‘a不小于b‘) 29 30 if (a > b): #大于 31 print(‘a大于b‘) 32 else: 33 print(‘a不大于b ‘) 34 35 36 if (a <= b): #小于等于 37 print(‘a小于等于b‘) 38 else: 39 print(‘不对‘) 40 41 if (a >= b): #大于等于 42 print(‘a大于等于b‘) 43 else: 44 print(‘不对‘)
以上实例执行结果:
C:\\Python\\Python35\\python.exe E:/Python课程/s13/day2/运算符.py
错误
a不等于b
错误
a小于b
错误
a小于等于b
Process finished with exit code 0
3、赋值运算符:
运算符 | 描述 | 实例 |
---|---|---|
= | 简单的赋值运算符 | c = a + b 将 a + b 的运算结果赋值为 c |
+= | 加法赋值运算符 | c += a 等效于 c = c + a |
-= | 减法赋值运算符 | c -= a 等效于 c = c - a |
*= | 乘法赋值运算符 | c *= a 等效于 c = c * a |
/= | 除法赋值运算符 | c /= a 等效于 c = c / a |
%= | 取模赋值运算符 | c %= a 等效于 c = c % a |
**= | 幂赋值运算符 | c **= a 等效于 c = c ** a |
//= | 取整除赋值运算符 | c //= a 等效于 c = c // a |
实例练习:
1 a = 2 2 b = 3 3 c = 0 4 5 c = a + b #把a+b的变量和赋值给c变量 6 print(c) 7 8 c += a #意思是c = c + a 9 print(c) 10 11 c -= a #意思是c = c - a 12 print(c) 13 14 c *= a #意思是c = c * a 15 print(c) 16 17 c /= a #意思是c = c / a 18 print(c) 19 20 c %= a #意思是c = c % a 21 print(c) 22 23 c **= a #意思是c = c ** a 24 print(c) 25 26 c //= a #意思是c = c // a 27 print(c)
以上实例执行结果:
1 C:\\Python\\Python35\\python.exe E:/Python课程/s13/day2/运算符.py 2 5 3 7 4 5 5 10 6 5.0 7 1.0 8 1.0 9 0.0 10 11 Process finished with exit code 0
4、位运算符:
执行二进制运算
运算符 | 描述 | 实例 |
---|---|---|
& | 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 | (a & b) 输出结果 12 ,二进制解释: 0000 1100 |
| | 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。 | (a | b) 输出结果 61 ,二进制解释: 0011 1101 |
^ | 按位异或运算符:当两对应的二进位相异时,结果为1 | (a ^ b) 输出结果 49 ,二进制解释: 0011 0001 |
~ | 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 | (~a ) 输出结果 -61 ,二进制解释: 1100 0011, 在一个有符号二进制数的补码形式。 |
<< | 左移动运算符:运算数的各二进位全部左移若干位,由"<<"右边的数指定移动的位数,高位丢弃,低位补0。 | a << 2 输出结果 240 ,二进制解释: 1111 0000 |
>> | 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,">>"右边的数指定移动的位数 | a >> 2 输出结果 15 ,二进制解释: 0000 1111 |
实例练习:
#!/usr/bin/env python3 a = 10 b = 60 c = 0 #一下是数字转成二进制的方法 #例如取10,60数字的二进制 #128 64 32 16 8 4 2 1 #0 0 0 0 1 0 1 0 = 10 #0 0 1 1 1 1 0 0 = 60 #0 0 0 0 1 0 0 0 = 8 # # 所以数字10,60,的二进制分别为 # 10 = 1010 # 60 = 111100 c = a & b #按位与运算符:二进制位置中相对应的为1的则为1,否则为0 print(c) #128 64 32 16 8 4 2 1 #0 0 0 0 1 0 1 0 = a = 10 #0 0 1 1 1 1 0 0 = b = 60 #0 0 0 0 1 0 0 0 = c = a & b = 8 c = a | b #按位或运算符:只要对应的位置是1的时候就是1 print(c) #128 64 32 16 8 4 2 1 #0 0 0 0 1 0 1 0 = a = 10 #0 0 1 1 1 1 0 0 = b = 60 #0 0 1 1 1 1 1 0 = c = a | b = 62 c = a ^ b #按位异或运算符:就是相对应的位置不一样的时候等于1 print(c) #128 64 32 16 8 4 2 1 #0 0 0 0 1 0 1 0 = a = 10 #0 0 1 1 1 1 0 0 = b = 60 #0 0 1 1 0 1 1 0 = c = a ^ b = 54 c = a << 2 #做移动运算符:往左边移动两位相当于 10*(2**2)左移n位就是乘以2的n次方 print(c) #128 64 32 16 8 4 2 1 #0 0 0 0 1 0 1 0 = a = 10 #0 0 1 0 1 0 0 0 = c = a << 2 = 40 c = a >> 2 #右移动运算符:往右边移动两位 print(c) #128 64 32 16 8 4 2 1 #0 0 0 0 1 0 1 0 = a = 10 #0 0 0 0 0 0 1 0 = c = a >>2 = 2
以上事例执行结果:
C:\\Python\\Python35\\python.exe E:/Python课程/s13/day2/运算符.py 8 62 54 40 2 Process finished with exit code 0
5、逻辑运算符:
假设变量 a 为 10, b为 20:
运算符 | 逻辑表达式 | 描述 | 实例 |
---|---|---|---|
and | x and y | 布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 | (a and b) 返回 20 |
or | x or y | 布尔"或" - 如果 x 是 True,它返回 True,否则它返回 y 的计算值。 | (a or b) 返回 10 |
not | not x | 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 | not(a and b) 返回 False |
6、成员运算符:
运算符 | 描述 | 实例 |
---|---|---|
in | 如果在指定的序列中找到值返回 True,否则返回 False。 | x 在 y 序列中 , 如果 x 在 y 序列中返回 True。 |
not in | 如果在指定的序列中没有找到值返回 True,否则返回 False。 | x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。 |
二、数据类型:
1、数字数据类型
包含四种:
int整型 如:23、333
long长整型:就是比较大比较长的数字
在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
大于以上范围着都属于长整型,只不过局限于python2中,在python3中已经不存在了!
float(浮点型):顾名思义就是带有小数点的数字,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
complex(复数):复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
abs(x) | 返回数字的绝对值,如abs(-10) 返回 10 |
2、布尔值
1 class str(basestring): 2 """ 3 str(object=‘‘) -> string 4 5 Return a nice string representation of the object. 6 If the argument is a string, the return value is the same object. 7 """ 8 def capitalize(self): 9 """ 首字母变大写 """ 10 """ 11 S.capitalize() -> string 12 13 Return a copy of the string S with only its first character 14 capitalized. 15 """ 16 return "" 17 18 def center(self, width, fillchar=None): 19 """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """ 20 """ 21 S.center(width[, fillchar]) -> string 22 23 Return S centered in a string of length width. Padding is 24 done using the specified fill character (default is a space) 25 """ 26 return "" 27 28 def count(self, sub, start=None, end=None): 29 """ 子序列个数 """ 30 """ 31 S.count(sub[, start[, end]]) -> int 32 33 Return the number of non-overlapping occurrences of substring sub in 34 string S[start:end]. Optional arguments start and end are interpreted 35 as in slice notation. 36 """ 37 return 0 38 39 def decode(self, encoding=None, errors=None): 40 """ 解码 """ 41 """ 42 S.decode([encoding[,errors]]) -> object 43 44 Decodes S using the codec registered for encoding. encoding defaults 45 to the default encoding. errors may be given to set a different error 46 handling scheme. Default is ‘strict‘ meaning that encoding errors raise 47 a UnicodeDecodeError. Other possible values are ‘ignore‘ and ‘replace‘ 48 as well as any other name registered with codecs.register_error that is 49 able to handle UnicodeDecodeErrors. 50 """ 51 return object() 52 53 def encode(self, encoding=None, errors=None): 54 """ 编码,针对unicode """ 55 """ 56 S.encode([encoding[,errors]]) -> object 57 58 Encodes S using the codec registered for encoding. encoding defaults 59 to the default encoding. errors may be given to set a different error 60 handling scheme. Default is ‘strict‘ meaning that encoding errors raise 61 a UnicodeEncodeError. Other possible values are ‘ignore‘, ‘replace‘ and 62 ‘xmlcharrefreplace‘ as well as any other name registered with 63 codecs.register_error that is able to handle UnicodeEncodeErrors. 64 """ 65 return object() 66 67 def endswith(self, suffix, start=None, end=None): 68 """ 是否以 xxx 结束 """ 69 """ 70 S.endswith(suffix[, start[, end]]) -> bool 71 72 Return True if S ends with the specified suffix, False otherwise. 73 With optional start, test S beginning at that position. 74 With optional end, stop comparing S at that position. 75 suffix can also be a tuple of strings to try. 76 """ 77 return False 78 79 def expandtabs(self, tabsize=None): 80 """ 将tab转换成空格,默认一个tab转换成8个空格 """ 81 """ 82 S.expandtabs([tabsize]) -> string 83 84 Return a copy of S where all tab characters are expanded using spaces. 85 If tabsize is not given, a tab size of 8 characters is assumed. 86 """ 87 return "" 88 89 def find(self, sub, start=None, end=None): 90 """ 寻找子序列位置,如果没找到,返回 -1 """ 91 """ 92 S.find(sub [,start [,end]]) -> int 93 94 Return the lowest index in S where substring sub is found, 95 such that sub is contained within S[start:end]. Optional 96 arguments start and end are interpreted as in slice notation. 97 98 Return -1 on failure. 99 """ 100 return 0 101 102 def format(*args, **kwargs): # known special case of str.format 103 """ 字符串格式化,动态参数,将函数式编程时细说 """ 104 """ 105 S.format(*args, **kwargs) -> string 106 107 Return a formatted version of S, using substitutions from args and kwargs. 108 The substitutions are identified by braces (‘{‘ and ‘}‘). 109 """ 110 pass 111 112 def index(self, sub, start=None, end=None): 113 """ 子序列位置,如果没找到,报错 """ 114 S.index(sub [,start [,end]]) -> int 115 116 Like S.find() but raise ValueError when the substring is not found. 117 """ 118 return 0 119 120 def isalnum(self): 121 """ 是否是字母和数字 """ 122 """ 123 S.isalnum() -> bool 124 125 Return True if all characters in S are alphanumeric 126 and there is at least one character in S, False otherwise. 127 """ 128 return False 129 130 def isalpha(self): 131 """ 是否是字母 """ 132 """ 133 S.isalpha() -> bool 134 135 Return True if all characters in S are alphabetic 136 and there is at least one character in S, False otherwise. 137 """ 138 return False 139 140 def isdigit(self): 141 """ 是否是数字 """ 142 """ 143 S.isdigit() -> bool 144 145 Return True if all characters in S are digits 146 and there is at least one character in S, False otherwise. 147 """ 148 return False 149 150 def islower(self): 151 """ 是否小写 """ 152 """ 153 S.islower() -> bool 154 155 Return True if all cased characters in S are lowercase and there is 156 at least one cased character in S, False otherwise. 157 """ 158 return False 159 160 def isspace(self): 161 """ 162 S.isspace() -> bool 163 164 Return True if all characters in S are whitespace 165 and there is at least one character in S, False otherwise. 166 """ 167 return False 168 169 def istitle(self): 170 """ 171 S.istitle() -> bool 172 173 Return True if S is a titlecased string and there is at least one 174 character in S, i.e. uppercase characters may only follow uncased 175 characters and lowercase characters only cased ones. Return False 176 otherwise. 177 """ 178 return False 179 180 def isupper(self): 181 """ 182 S.isupper() -> bool 183 184 Return True if all cased characters in S are uppercase and there is 185 at least one cased character in S, False otherwise. 186 """ 187 return False 188 189 def join(self, iterable): 190 """ 连接 """ 191 """ 192 S.join(iterable) -> string 193 194 Return a string which is the concatenation of the strings in the 195 iterable. The separator between elements is S. 196 """ 197 return "" 198 199 def ljust(self, width, fillchar=None): 200 """ 内容左对齐,右侧填充 """ 201 """ 202 S.ljust(width[, fillchar]) -> string 203 204 Return S left-justified in a string of length width. Padding is 205 done using the specified fill character (default is a space). 206 """ 207 return "" 208 209 def lower(self): 210 """ 变小写 """ 211 """ 212 S.lower() -> string 213 214 Return a copy of the string S converted to lowercase. 215 """ 216 return "" 217 218 def lstrip(self, chars=None): 219 """ 移除左侧空白 """ 220 """ 221 S.lstrip([chars]) -> string or unicode 222 223 Return a copy of the string S with leading whitespace removed. 224 If chars is given and not None, remove characters in chars instead. 225 If chars is unicode, S will be converted to unicode before stripping 226 """ 227 return "" 228 229 def partition(self, sep): 230 """ 分割,前,中,后三部分 """ 231 """ 232 S.partition(sep) -> (head, sep, tail) 233 234 Search for the separator sep in S, and return the part before it, 235 the separator itself, and the part after it. If the separator is not 236 found, return S and two empty strings. 237 """ 238 pass 239 240 def replace(self, old, new, count=None): 241 """ 替换 """ 242 """ 243 S.replace(old, new[, count]) -> string 244 245 Return a copy of string S with all occurrences of substring 246 old replaced by new. If the optional argument count is 247 given, only the first count occurrences are replaced. 248 """ 249 return "" 250 251 def rfind(self, sub, start=None, end=None): 252 """ 253 S.rfind(sub [,start [,end]]) -> int 254 255 Return the highest index in S where substring sub is found, 256 such that sub is contained within S[start:end]. Optional 257 arguments start and end are interpreted as in slice notation. 258 259 Return -1 on failure. 260 """ 261 return 0 262 263 def rindex(self, sub, start=None, end=None): 264 """ 265 S.rindex(sub [,start [,end]]) -> int 266 267 Like S.rfind() but raise ValueError when the substring is not found. 268 """ 269 return 0 270 271 def rjust(self, width, fillchar=None): 272 """ 273 S.rjust(width[, fillchar]) -> string 274 275 Return S right-justified in a string of length width. Padding is 276 done using the specified fill character (default is a space) 277 """ 278 return "" 279 280 def rpartition(self, sep): 281 """ 282 S.rpartition(sep) -> (head, sep, tail) 283 284 Search for the separator sep in S, starting at the end of S, and return 285 the part before it, the separator itself, and the part after it. If the 286 separator is not found, return two empty strings and S. 287 """ 288 pass 289 290 def rsplit(self, sep=None, maxsplit=None): 291 """ 292 S.rsplit([sep [,maxsplit]]) -> list of strings 293 294 Return a list of the words in the string S, using sep as the 295 delimiter string, starting at the end of the string and working 296 to the front. If maxsplit is given, at most maxsplit splits are 297 done. If sep is not specified or is None, any whitespace string 298 is a separator. 299 """ 300 return [] 301 302 def rstrip(self, chars=None): 303 """ 304 S.rstrip([chars]) -> string or unicode 305 306 Return a copy of the string S with trailing whitespace removed. 307 If chars is given and not None, remove characters in chars instead. 308 If chars is unicode, S will be converted to unicode before stripping 309 """ 310 return "" 311 312 def split(sel
以上是关于python基础篇第二篇的主要内容,如果未能解决你的问题,请参考以下文章