Python三种基本语句

184 阅读4分钟
原文链接: click.aliyun.com

Python条件语句

python的条件语句和C/C++的条件语句的判断方法是一样的

通过执行条件的true or flase来判断执行那个分支只是在书写上存在不同:

If 判断条件:

执行语句(单个语句或者语句块)

Else :

执行语句(单个语句或者语句块)

在python中通过缩进表示同一个语句块,在pyt

python程序语言中指定任何非0或者非空(null)值为true。0或者null为false。

还有条件语句的连用:

If 判断条件:

执行语句(单个语句或者语句块)

Elif:

执行语句(单个语句或者语句块)

Else:

执行语句(单个语句或者语句块)

不同于C/C++的是python中不支持switch语句,如果多个条件判断的时候我们可以利用elif进行实现,当多个条件同时判断的时候我们可以利用or或者and进行组合判断表达式,

如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。

Python while循环语句

While 判断语句:

执行条件……(单个语句或者语句块)

当判断条件可以是任何表达式,任何非零、或非空(null)的值均为 true。

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

While语句中另外两个命令continue和break来跳出循环和在C/C++使用的时候一样,continue用于跳出本次循环,break用于推出循环。

循环使用else语句

While 判断语句:

执行条件……(单个语句或者语句块)

Else :

执行条件……(单个语句或者语句块)

Python for 循环语句

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

For iterating_var in squance:

Statements(s)

实际的运行流程和C/C++没有区别只是书写上不同。

在Linux系统中运行,VS中输出应该加扣号

#!/usr/bin/python

 

for letter in 'Python':     # First Example

   print 'Current Letter :', letter

 

fruits = ['banana', 'apple',  'mango']

for fruit in fruits:        # Second Example

   print 'Current fruit :', fruit

 

print "Good bye!"

以上实例输出结果:

1

2

3

4

5

6

7

8

9

10

Current Letter : P

Current Letter : y

Current Letter : t

Current Letter : h

Current Letter : o

Current Letter : n

Current fruit : banana

Current fruit : apple

Current fruit : mango

Good bye!

通过序列索引迭代是外一种循环的遍历方式

#!/usr/bin/python

 

fruits = ['banana', 'apple',  'mango']

for index in range(len(fruits)):

   print 'Current fruit :', fruits[index]

 

print "Good bye!"

以上实例输出结果:

1

2

3

4

Current fruit : banana

Current fruit : apple

Current fruit : mango

Good bye!

len()和range()为内置函数,len()返回列表长度(元素的个数),range返回一个序列的数

循环使用else

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

如下实例:

1

2

3

4

5

6

7

8

9

10

#!/usr/bin/python

 

for num in range(10,20):  #to iterate between 10 to 20

   for i in range(2,num): #to iterate on the factors of the number

      if num%i == 0:      #to determine the first factor

         j=num/i          #to calculate the second factor

         print '%d equals %d * %d' % (num,i,j)

         break #to move to the next number, the #first FOR

   else:                  # else part of the loop

      print num, 'is a prime number'

以上实例输出结果:

1

2

3

4

5

6

7

8

9

10

10 equals 2 * 5

11 is a prime number

12 equals 2 * 6

13 is a prime number

14 equals 2 * 7

15 equals 3 * 5

16 equals 2 * 8

17 is a prime number

18 equals 2 * 9

19 is a prime number