数据类型:
- 整形(int) 布尔类型(bool) 浮点型(float,e记法1.5e11=1.5*10的11次方) 字符串(str)
- 类型的获取**type()**函数
type('abc') <class 'str'>
**isinstance()**函数isinstance('abc',str) >>True
扩展:
s 为字符串
s.isalnum() 所有字符都是数字或者字母,为真返回 True,否则返回 False。
s.isalpha() 所有字符都是字母,为真返回 True,否则返回 False。
s.isdigit() 所有字符都是数字,为真返回 True,否则返回 False。
s.islower() 所有字符都是小写,为真返回 True,否则返回 False。
s.isupper() 所有字符都是大写,为真返回 True,否则返回 False。
s.istitle() 所有单词都是首字母大写,为真返回 True,否则返回 False。
s.isspace() 所有字符都是空白字符,为真返回 True,否则返回 False - 常用操作符:x%y 求x除以y的余数; x//y 地板除取小的整数(3//2==1); abs(x)绝对值; dirmod(x,y)=(x//y,x%y); pow(x,y)x的y次方; complex(re,im)复数(实部,虚部);
a=a+1 可化简为 a += 1 c = c*5 c *=5 - 优先级:幂运算 >:正负号>算术操作符>比较操作符>逻辑运算符(not>and>or)
not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9 ==4 ;(not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9)=0 or 0 or 4 or 6 or 9= 4
爱因斯坦曾出过这样一道有趣的数学题:有一个长阶梯,若每步上2阶,最后剩1阶;若每步上3阶,最后剩2阶;若每步上5阶,最后剩4阶;若每步上6阶,最后剩5阶;只有每步上7阶,最后刚好一阶也不剩。>
i=1
while(True):
if (i%2==1) and (i%3==2) and (i%5==4) and (i%7==0) and (i%6==5):
print(i)
break
else:
i += 1
分支和循环
- python能有效避免else与if不能正确匹配的问题,毕竟是靠的缩进(深受C语言的苦啊)
- 条件表达式(三元操作符):
a = x if 条件 else y
比较x,y,z的大小small = x if (x<y and x<z) else y if y<z else z
- 断言(assert) 当后面的条件为假时,程序自动崩溃返回AssertionError的异常。用于程序测试,让错误出现
- while循环语句:
while 条件:\n 循环体
- for循环:
for 变量 in 可迭代对象 : 循环体
in成员资格运算符,当对象在里面时返回True - range()函数生成一个数字序列 range(start,stop,step) range(10)生成0-9十个可迭代数字。
- break语句 跳出循环,continue 终止本轮循环,重新测试循环条件开始下一轮。
- else语句:while条件: 循环体 else: 条件不成立时执行的内容 ; for 变量 in 迭代对象: 循环体 else: 条件不成立时执行的内容
- 简单的输入密码的小代码,详见小甲鱼的书吧。。。。。。
times = 3
password = '123456'
while times:
user = input('请输入密码:')
if '*' in user:
times -= 1
print('不能有*号,您还有',times,'次机会')
continue
else:
if user == password:
print('密码正确。。。')
break
else:
times -=1
print('密码错误,你还有',times,'次机会')
continue