zoukankan      html  css  js  c++  java
  • python中的方法

    if 条件语句

    if  判断条件  :

         xxxxxxx

    else:

         xxxxxxx

    判断条件有多个时:

    if  判断条件 :

        xxxxxx

    elseif  判断条件1 :

        xxxxxx

    elseif  判断条件2 :

        xxxxxx

    else:

        xxxxxx

    python 复合布尔表达式计算采用短路规则,即如果通过前面的部分已经计算出整个表达式的值,则后面的部分不再计算。如下面的代码将正常执行不会报除零错误:

    a=0
    b=1
    if ( a > 0 ) and ( b / a > 2 ):
        print "yes"
    else :
        print "no"


    循环:python中提供了for循环和while循环两种,
    但是没有do ...while循环
    控制语句有:break,continue,pass
    while循环:1. while 判断条件 :
    执行语句

    2. while ....else 在循环条件为false时,执行else的部分。



    while 语句时还有另外两个重要的命令 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


    无限循环:可以使用 CTRL+C 来中断循环。

    while ....else
    count = 0
    while count < 5:
    print count, " is less than 5"
    count = count + 1
    else:
    print count, " is not less than 5"



    for 循环: python中的for循环可以遍历任何序列的项目,比如一个列表或一个字符串

    for letter in 'Python': #第一个实例
    print '当前字母 :', letter

    fruits = ['banana', 'apple', 'mango']
    for fruit in fruits: #第二个实例
    print '当前水果 :', fruit

              fruits = ['banana', 'apple', 'mango']
    for index in range(len(fruits)): #第三个实例
    print '当前水果 :', fruits[index]

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

    在for循环中的in :,for循环后的in跟随一个序列的话,循环每次使用的序列元素,而不是序列
    的下标
    s = 'qazxswedcvfr'
    for i in range(0,len(s),2):
        print s[i]

    在for循环中的enumerate() : 在每次循环中,可以同时得到下标和元素 实际上,enumerate(),在每次循环中返回的是包含每个元素的定值表,两个元素分别赋值 index,char for (index,char) in enumerate(s): print "index=%s ,char=%s" % (index,char)


    range()函数:
    range(1,5) #代表从1到5(不包含5)
    [1, 2, 3, 4]
    range(1,5,2) #代表从1到5,间隔2(不包含5)
    [1, 3]
    range(5) #代表从0到5(不包含5)
    [0, 1, 2, 3, 4]

    continue语句用在while和for循环中。continue语句跳出本次循环,break语句跳出整个循环。
    continue语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
    continue 语句是一个删除的效果,他的存在是为了删除满足循环条件下的某些不需要的成分。

    n = 0
    while n < 10:
        n = n + 1
        if n % 2 == 0:      # 如果n是偶数,执行continue语句
            continue        # continue语句会直接继续下一轮循环,后续的print()语句不会执行
        print(n)

    pass占位符:pass是空语句,不做任何事情,只是为了保持程序结构的完整性。
    当编写一个程序时,执行语句部分思路还没有完成,又不能空着不写内容,这时可以用pass来占位,过后再来编写代码。
    比如: def iplaypython():
    pass




















  • 相关阅读:
    小白的Python之路_day1
    Vue---tab切换时不刷新
    Vue---第十五章使用VScode编写第一个脚本
    Vue---第十四章visual studio code使用
    Vue---第十三章基础运算和v-model
    Vue---第十二章批量下载模块
    vue---第十一章全局依赖环境区分
    Vue---第十章全局变量
    Vue---第九章NPM
    hadoop-Rpc使用实例
  • 原文地址:https://www.cnblogs.com/linqiuhua/p/7696102.html
Copyright © 2011-2022 走看看