# python - 判断奇偶数，==和！=哪个效率更高

python 专栏收录该内容
110 篇文章 1 订阅

Python 大小等于比较效率

a=int(input("输入一个整数："))
odevity=str(a)+"是奇数"
if a%2==0:odevity=str(a)+"是偶数"
print(odevity)


#运行效率
import time
a=6
ss=time.time()
for i in range(1000000):
ode=str(a)+"是奇数"
if a%2==0:ode=str(a)+"是偶数"
print(ode)
t1=time.time()-ss

ss=time.time()
for i in range(1000000):
if a%2==0:print(str(a)+"是偶数")
else:print(str(a)+"是奇数")
print(t1,time.time()-ss,sep="\n")


if，如果成功，则直接输出对应结果。如果失败，else另一种结果。其间不定义额外变量，直接输出。

6.606092929840088
6.018859386444092

6.128280162811279
5.943890333175659

6.246928453445435
6.241985559463501

6.013113498687744
5.886185169219971

6.429988622665405
5.974666118621826

import time

time.sleep(3)
a = 10
ss = time.time()
for i in range(10000000):
if a == 10: ""
print(time.time() - ss)

ss = time.time()
for i in range(10000000):
if a != 10: ""
print(time.time() - ss)



#运行效率
import time
a=6
ss=time.time()
for i in range(1000000):
ode=str(a)+"是偶数"
if a%2!=0:ode=str(a)+"是奇数"
print(ode)
t1=time.time()-ss

ss=time.time()
for i in range(1000000):
if a%2!=0:print(str(a)+"是奇数")
else:print(str(a)+"是偶数")
t2=time.time()-ss

ss=time.time()
for i in range(1000000):
ode=str(a)+"是偶数"
if a%2!=0:ode=str(a)+"是奇数"
print(ode)
t3=time.time()-ss

ss=time.time()
for i in range(1000000):
if a%2!=0:print(str(a)+"是奇数")
else:print(str(a)+"是偶数")
t4=time.time()-ss

print(t1,t2,t3,t4,sep="\n")


a=6
5.995797872543335
5.967499017715454
5.999722242355347
5.997941017150879

a=5
6.284368515014648
5.9603111743927
6.601690053939819
6.005819797515869

N年前，老师也是讲，现在计算机性能提升，不在乎这么点效率。

• 0
点赞
• 3
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

07-16 1万+
10-17 16万+

04-30 287
08-09 5万+
11-24 423
11-05 4631
11-26 15
05-19 238
04-20 513
08-12 2533