.Net程序员之Python基础教程学习----判断条件与循环[Fourth Day]

      今天学习Python的判断条件与循环操作。

   一. 布尔变量:

     在学习判断条件之前必须的了解bool变量,在Python中bool变量与C语言比较类似,与.net差别比较大,其中下面集中情况需要记住。

     False, '', 0, (), [],{},None 为空,而True,12,'hello',[1] 这些普遍都为真. 其实可以简单理解为,无即是false,有既是true

    

>>> bool(True)
True
>>> bool(0)
False
>>> bool(1)
True
>>> bool('')
False
>>> bool('123')
True
>>> bool([])
False

    二. IF  的使用.

    

     Note: if后面用:号隔开,相当于C#和C语言的{} 对于包含的代码段用间隔号隔开。比如第三行 print '未成年人是if(age<18)的子方法,那么就要在前面空出几个空格.

age = 18
if(age<18):
    print '未成年人'
elif(age<50):
    print '成年人'
else:
    print '老年人'

输出:'成年人'

    

age = 20
if(age<50):
    if(age>18):
        print '成年人'

  三. While的使用:        

x = 1
while x<=100:
    print x
    x+=1

        四. For 用法:

  

names = ['Frank','Loch','Vincent','Cain']
for name in names:
    print name

        五.断言的使用: 断言主要用于测试的时候。如果断言不通过将会报错.
            

>>> age = 10
>>> assert age<20
>>> assert age<9   # 第一个断言通过了。第二个断言没有通过,所以报错了。
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    assert age<9
AssertionError

        六. 综合运用。
            1. 下面有一个列表取出列表中的数字:

    

myList = ['Frank','Bob',123,456,789]
for val in myList:
    if(type(val) is int):   #type获取一个值得类型.
        print val
输出结果是:
123
456
789

            2. 打印出杨辉三角形: 10层的杨辉三角形,先声明一个二维数组,由于不能像C语言或者C++使用for(int index;index<10;index++),我选择了使用while的双层循环

    

rowIndex = 1
columnIndex = 0
myList = [[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0,0,0]]
print myList
print(myList[9][9])
while rowIndex < 10:
    while columnIndex <= rowIndex:
       if(rowIndex==1):
           myList[1][0]=1
           myList[1][1]=1
       else:
           if(columnIndex==rowIndex):
               myList[rowIndex][columnIndex]=1
           else:
               myList[rowIndex][columnIndex]=myList[rowIndex-1][columnIndex-1]+myList[rowIndex-1][columnIndex]
       columnIndex+=1
    columnIndex=0
    rowIndex+=1

line = ''
for row in myList:
    for val in row:
        if(val!= 0):
           line = line + str(val)+' '
    print line
    line=''

运行结果:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

    


    

  

  

    

    

原文地址:https://www.cnblogs.com/FourLeafCloverZc/p/4254331.html