python的数值类型
int
float
complex
python字符串
1
2a='this is a new n line' print (a)
我们知道输出结果为
1
2
3this is a new line
若改为
1
2a=repr('this is a new n line') print (a)
则输出结果不会换行,因为命令repr是用于将字符串转为供计算机读取的字符串,所有换行等符号变为普通字符串。
python的赋值运算符
num//=1 等价于num=num//1, 求商运算符。
num%=1等价于num=num%1,求余数运算符。
num*=1等价于num=num*1,求乘运算符。
num**=1等价于num=num**1,求对数运算符。
python的逻辑运算符
一共有三种:not, and , or
这三个运算符的优先级是不同的
not最大优先级, and 和 or 就看它在语句中的前后顺序而定
*注意python里面有括号优先级,例如
a>b and (c>d or (not f))
计算机会先判断括号里面的内容
1
25>3 and 4<3 or 6>5
15>3 and (4<3 or 6>5)
这两个代码是不同的
身份运算符 is,is not
用来判断字符串的类型(int,str,list,dict。。。),输出为布尔值
1
2
3a=[1,2] if type(a) is list: print('a is a list')
注意判断的时候一定要加type(),因为单独输出list会得到结果<class 'list'>,a虽然确实是个list,但是需要靠type(a)来得出结果<class 'list'>,这样 type(a) is list 这个判断才能得出正确结果True。如果仅仅是 a is list,得到结果一定是False。
成员运算符 in not in
短路原则
对于条件1 and 条件2,如果条件1为假,那么条件2就不会被计算
对于条件1 or 条件2,如果条件1为真,则条件2不被计算
while 循环及其用法
1while 条件:
while循环的结束方法
1.利用布尔值结束循环
1
2
3TiaoJian=True while Tiaojian: Tiaojian=False
2.利用break结束循环
1
2while True: break
注意,break是用来停止它所在的最内循环,但是不会停止外部的大循环,例如
1
2
3
4
5
6
7
8
9a=1 b=1 while a<10: a+=1 print('a=',a) while b<10: break b+=1 print('b=',b)
这个循环因为有break不会输出b,但是a的循环不受影响
continue在while的用法
1
2
3
4
5
6
7
8a=1 b=1 while a<10: a+=1 print('a=',a) continue b+=1 print('b=',b)
continue被识别之后,直接忽略循环内后部的语句的计算,直接进行下次循环,所以上部代码的b一直不能被print。
else在while中的用法
else表示在while循环的条件不满足的前提之下(正常结束,而不是因为break导致循环中断)的执行命令
1
2
3
4
5
6
7a=1 b=1 while a<10: a+=1 print('a=',a) else: print('b=',b)
1
2
3
4
5
6
7
8
9a=1 b=1 while a<10: a+=1 print('a=',a) if a==3: break else: print('b=',b)
因为第二个代码有break的存在,else内的代码不会执行
用while 实现猜年龄
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20judgement=True ageTop=100 ageBot=0 ageJudge=40 while judgement==True: age=input('are you older than %d? Y/N'%ageJudge) if age=='Y':#erder than ageJudge ageBot=ageJudge ageJudge=int((ageTop+ageJudge)/2) if ageBot==ageJudge: ageBot+=1 print('You are %d'%ageBot) judgement=False elif age=='N': ageTop=ageJudge ageJudge=int((ageTop+ageBot)/2) if ageBot==ageJudge: print('You are %d'%ageBot) judgement=False
print()中end的用法
如果想实现print的东西后面换行或者空格,可以
1print('words',end='n')
'n'代表换行,如果不加end一般都是默认换行,也可以换成别的,比如'b'空格,'t' tab。
例题
1.利用 while循环创建99乘法表
1
2
3
4
5
6
7
8
9
10l=1 w=1 while l<=9: while w<=l: print('%d*%d=%d'%(w,l,l*w),end=' ') w+=1 print(end='n') l+=1 w=1
如果用for循环似乎稍微麻烦一点
1
2
3
4
5
6
7
8
9Hlength=range(1,10) Hwidth=range(1,10) width=1 for length in Hlength: for width in Hwidth: if width<=length: print('%d*%d=%d'%(width,length,length*width),end=' ') if width==length: print(end='n')
最后
以上就是呆萌小伙最近收集整理的关于Python day04:运算符以及while循环,print中end用法的全部内容,更多相关Python内容请搜索靠谱客的其他文章。
发表评论 取消回复