python语句

简介: python语句

一、条件语句

Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if语句实现:

age = 20
if age >= 18:
    print('your age is', age)
    print('adult')

根据Python的缩进规则,如果if语句判断是True,就把缩进的两行print语句执行了,否则,什么也不做。

也可以给if添加一个else语句,意思是,如果if判断是False,不要执行if的内容,去把else执行了:

age = 3
if age >= 18:
    print('your age is', age)
    print('adult')
else:
    print('your age is', age)
    print('teenager')

注意不要少写了冒号:

当然上面的判断是很粗略的,完全可以用elif做更细致的判断:

age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

elifelse if的缩写,完全可以有多个elif,所以if语句的完整形式就是:

if <条件判断1>:
    <执行1>
elif <条件判断2>:
    <执行2>
elif <条件判断3>:
    <执行3>
else:
    <执行4>

if语句执行有个特点,它是从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的elifelse,所以,请测试并解释为什么下面的程序打印的是teenager

age = 20
if age >= 6:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')

if判断条件还可以简写,比如写:

if x:
    print('True')

只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False

二、循环语句

1、while循环

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件(condition):

   执行语句(statements)……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

当判断条件假 false 时,循环结束。

比如我们要计算100以内所有奇数之和,可以用while循环实现:

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

在循环内部变量n不断自减,直到变为-1时,不再满足while条件,循环退出。

while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:

# continue 和 break 用法
 
i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print i         # 输出双数2、4、6、8、10
 
i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break

无限循环

如果条件判断语句永远为 true,循环将会无限的执行下去,如下实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
var = 1
while var == 1 :  # 该条件永远为true,循环将无限执行下去
   num = raw_input("Enter a number  :")
   print "You entered: ", num
 
print "Good bye!"

循环使用 else 语句

在 python 中,while … else 在循环条件为 false 时执行 else 语句块:

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

输出

0 is less than 5

1 is less than 5

2 is less than 5

3 is less than 5

4 is less than 5

5 is not less than 5

简单语句组

类似 if 语句的语法,如果你的 while 循环体中只有一条语句,你可以将该语句与while写在同一行中, 如下所示:

#!/usr/bin/python
 
flag = 1
 
while (flag): print 'Given flag is really true!'
 
print "Good bye!"

2、 for in循环

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

语法:

for循环的语法格式如下:

for iterating_var in sequence:

  statements(s)

案例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for letter in 'Python':     # 第一个实例
   print("当前字母: %s" % letter)
 
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print ('当前水果: %s'% fruit)
 
print ("Good bye!")

通过序列索引迭代

另外一种执行循环的遍历方式是通过索引,如下实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print ('当前水果 : %s' % fruits[index])
 
print ("Good bye!")

以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。

循环使用 else 语句

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print ('%d 等于 %d * %d' % (num,i,j))
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print ('%d 是一个质数' % num)

三、循环嵌套

Python 语言允许在一个循环体里面嵌入另一个循环。

Python for 循环嵌套语法:

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

Python while 循环嵌套语法:

while expression:
   while expression:
      statement(s)
   statement(s)

你可以在循环体内嵌入其他的循环体,如在while循环中可以嵌入for循环, 反之,你可以在for循环中嵌入while循环。

实例:

以下实例使用了嵌套循环输出2~100之间的素数:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " 是素数"
   i = i + 1
 
print "Good bye!"

四、break 语句

Python break语句,就像在C语言中,打破了最小封闭for或while循环。

break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。

break语句用在while和for循环中。

如果您使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for letter in 'Python':     # 第一个实例
   if letter == 'h':
      break
   print '当前字母 :', letter
  
var = 10                    # 第二个实例
while var > 0:              
   print '当前变量值 :', var
   var = var -1
   if var == 5:   # 当变量 var 等于 5 时退出循环
      break
 
print "Good bye!"

五、continue 语句

Python continue 语句跳出本次循环,而break跳出整个循环。

continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。

continue语句用在while和for循环中。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for letter in 'Python':     # 第一个实例
   if letter == 'h':
      continue
   print '当前字母 :', letter
 
var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:
      continue
   print '当前变量值 :', var
print "Good bye!"

结果

当前字母 : P

当前字母 : y

当前字母 : t

当前字母 : o

当前字母 : n

当前变量值 : 9

当前变量值 : 8

当前变量值 : 7

当前变量值 : 6

当前变量值 : 4

当前变量值 : 3

当前变量值 : 2

当前变量值 : 1

当前变量值 : 0

Good bye!

六、pass 语句

Python pass 是空语句,是为了保持程序结构的完整性。

pass 不做任何事情,一般用做占位语句。

pass 一般用于占位置。

在 Python 中有时候会看到一个 def 函数:

def sample(n_samples):

   pass

该处的 pass 便是占据一个位置,因为如果定义一个空函数程序会报错,当你没有想好函数的内容是可以用 pass 填充,使程序可以正常运行。


相关文章
|
6天前
|
Python
python中if语句(一)
python中if语句(一)
26 0
|
6天前
|
Python
python中if语句(三)
python中if语句(三)
13 0
|
9月前
|
Python
【从零学习python 】09.Python 中的条件判断语句
【从零学习python 】09.Python 中的条件判断语句
45 0
|
11月前
|
Python
Python for...else... 语句
Python for...else... 语句
|
Python
python(7)--if语句
python(7)--if语句
64 0
python(7)--if语句
|
Python
Python中的While 语句
Python中的While 语句自制脑图
76 0
Python中的While 语句
|
Python
Python中的if 语句_2
Python中的if 语句_2自制脑图
58 0
Python中的if 语句_2
|
Python
Python中的if-else 语句
Python中的if-else 语句自制脑图 if-else 语句的相关代码,if-else 语句语法,执行流程
62 0
Python中的if-else 语句
|
存储 数据库 Python
Python - with 语句
Python - with 语句
93 0
|
数据库连接 数据库 Python
Python中的With语句
在Python中,您需要通过打开文件来访问文件。您可以使用 open()函数来实现。Open 返回一个文件对象,该文件对象具有用于获取有关已打开文件的信息和对其进行操作的方法和属性。
136 0