首页 > 编程语言 > 详细

Python学习笔记8—语句

时间:2016-09-05 19:06:00      阅读:218      评论:0      收藏:0      [点我收藏+]

条件语句

有的程序里写的是 /usr/bin Python,表示 Python 解释器在/usr/bin 里面。但是,如果写成 /usr/bin/env,则表示要通过系统搜索路径寻找 Python 解释器。不同系统,可
能解释器的位置不同,所以这种方式能够让代码更将拥有可移植性。

#/usr/bin/env python
#coding=utf-8
number = int(raw_input("请输入任意一个整数:"))
if number == 10:
        print "您输入的数字是:  %d"%number
elif number > 10:
    print "This number is more than 10."
elif number < 10:
    print "This number is less than 10."
else:
    print "Are you a human?"

三元操作符

三元操作,是条件语句中比较简练的一种赋值方式,它的模样是这样的:

>>> a = "5" if 6>5 else 3
>>> a
5
>>> a = "5" if 6<5 else 3
>>> a
3

循环语句

for

#/usr/bin/env python
fruits=["apple","orange","banana"]
for i in fruits:
    print i

多个

a=[(1,2),(3,4),(5,6)]
d=[]
for x,y in a:
    d.append(x+y)
print d

while

#!/usr/bin/env python
#coding:utf-8
a = 9
while a:
    if a%2 == 0:
      break
    else:
      print "%d is odd number"%a
      a = 0
print "%d is even number"%a

while...else

一遇到 else 了,就意味着已经不在 while 循环内了。

#!/usr/bin/env Python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"

for...else

这个循环也通常用在当跳出循环之后要做的事情。

#!/usr/bin/env python
# coding=utf-8
from math import sqrt
for n in range(99, 1, -1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Nothing."

 

Python学习笔记8—语句

原文:http://www.cnblogs.com/zydev/p/5842982.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!