零基础入门学习Python(6)--Python之常用操作符
2018-02-05 15:00
597 查看
前言
Python当中常用操作符,有分为以下几类。幂运算(**),正负号(
+,
-),算术操作符(
+,
-,
*,
/,
//,
%),比较操作符(
<,
<=,
>,
>=,
==,
!=),逻辑运算符(
not,
and,
or)。
操作符介绍
幂运算(**)
>>> 3 ** 3 27
正负号(
+,
-)
幂运算的优先级比较特殊, 因为幂操作进行运算的时候,他和一元操作符的运算关系比较暧昧,减号(-)当作负号(-)来使用时,他是一元操作符,表示负数。 幂操作符比其左边的操作符优先级高,比起右边的优先级低。例如: >>> -3 ** 2 -9 >>> -(3 ** 2) -9 >>> 3 ** -2 0.1111111111111111 >>> 3 ** (-2) 0.1111111111111111
算术操作符(
+,
-,
*,
/,
//,
%)
算术操作符中,a = a + 5 可以写成 a + = 5,其他算数操作符也适用,例如: >>> a = b = c = d = 10 >>> a += 1 >>> b -= 3 >>> c *= 10 >>> d /= 8 >>> a 11 >>> b 7 >>> c 100 >>> d 1.25 '//' 表示floor除 >>> 3 // 2 1 >>> 3.2 // 2.0 1.0 >>> 3.2 // 2 1.0 '%' 表示求余数 >>> 9 % 2 1 >>> 9 % 7 2
比较操作符(
<,
<=,
>,
>=,
==,
!=)
根据表达式的值真假来返回bool类型的值,例如: >>> 1 < 2 True >>> 3 > 4 False >>> 2 == 2 True >>> 2 != 2 False
逻辑运算符(
not,
and,
or)
逻辑运算符的优先级是不同的,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) 4
操作符优先级
练练手
把上篇博客中求闰年,用%改写
temp = input('请输入一个年份:') while not temp.isdigit(): temp = input("抱歉,您的输入有误,请输入一个整数:") year = int(temp) if year%400 == 0: print(temp + ' 是闰年!') else: if (year%4 == 0) and (year%100 != 0): print(temp + ' 是闰年!') else: print(temp + ' 不是闰年!')
写一个程序打印出0 ~ 100所有的奇数
i = 0 while i<= 100: if i < 4000 span class="hljs-comment">% 2 != 0: print(i,end=' ') i += 1 else: i += 1
爱因斯坦的难题
i = 1 x = 7 flag = 0 while i<=100: if (x%2 ==1) and (x%3 ==2) and (x%5 ==4) and (x%6 ==5): flag = 1 else: x = 7 * (i + 1) i += 1 if flag == 1: print('阶梯数是:',x) else: print('在程序限定范围内找不到答案!') ------------------------------------------------------------------------------------------------ x = 0 while 1: if (x%2 ==1) and (x%3 ==2) and (x%5 ==4) and (x%6 ==5) and (x%7 ==0): print('阶梯数是:',x) break else: x += 1
相关文章推荐
- 【零基础入门学习Python笔记006】Python之常用操作符
- 零基础入门学习Python(6)--Python之常用操作符
- 零基础入门学习Python(4):常用操作符
- Python基础学习笔记(七)——常用操作符
- Pyhon之常用操作符 - 零基础入门学习Python006
- Python学习入门基础教程(learning Python)--8.3 字典常用的方法函数介绍
- 我和Python的第一次亲密接触 - 零基础入门学习Python001
- Python学习入门基础教程(learning Python)--2.3 Python自定义函数传参
- Python学习入门基础教程(learning Python)--6.4 Python的list与函数
- Python学习入门基础教程(learning Python)--3.2 if-else分支语句
- Python学习入门基础教程(learning Python)--2.3.1 Python传参函数设计
- Python学习入门基础教程(learning Python)--8.1 字典数据添加与删除
- Python学习入门基础教程(learning Python)--1.2Python输入输出与处理 .
- Python学习入门基础教程(learning Python)--6 Python下的list数据类型
- Python学习入门基础教程(learning Python)--5.7 Python文件数据记录存储与处理
- Python学习入门基础教程(learning Python)--1.2.1 Python输出语句print基本使用 .
- Python学习入门基础教程(learning Python)--3.3.1 Python下的布尔表达式
- Python学习入门基础教程(learning Python)--5.1 Python下文件处理基本过程
- Python学习入门基础教程(learning Python)--5 Python文件处理
- Python学习入门基础教程(learning Python)--6.3 Python的list切片高级