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

本文深入讲解Python的基础语法,包括布尔变量的真假判断、if条件语句的使用、while和for循环的应用,以及断言的实践。通过实例演示了如何在列表中筛选整数和打印杨辉三角形,适合初学者掌握Python核心概念。

      今天学习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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值