zoukankan      html  css  js  c++  java
  • Python学习笔记——条件控制

    Python中的条件控制方式基本和C语言类似,主要有如下几种语法:

    If条件判断

    Python的条件语句的语法是if…elseif…else,如下的一个简单的猜数字的示例演示了这一过程:

        number = 23
        guess = int(raw_input('Enter an integer : '))

        if guess == number:
            print 'Congratulations, you guessed it.'         # New block starts here
        elif guess < number:
            print 'No, it is a little higher than that'     # Another block
        else:
            print 'No, it is a little lower than that'

    从上我们也可以看到:和C不同的是,python并不是通过括号,而是通过缩进来表示语法块。(为了文章排版整齐,我文章的例子都在行首都插入了一个tab键,使用时需要去掉)

    While循环语句

    这里以一个从1加到100来简单的演示一下while循环的用法:

        total = 0;
        count = 0;
        
        whilecount < 100 :
            count = count + 1
            total = total + count
        
        print total

    for循环

    Python的for循环其实是类似c#的foreach,实现的是遍历功能:

        total = 0;
        
        for i in range(1, 101):
         total = total + i
        print total

    break & Continue语句

    break & continue用法和C语言基本类似:

        while True:
            s = raw_input('Enter something : ')
            if s == 'quit':
                break
            if len(s) < 3:
                continue
            print 'Input is of sufficient length'

     

  • 相关阅读:
    poj 1684 Lazy Math Instructor(字符串)
    STL内存配置器
    迭代器(iterators)
    类型萃取(type traits)
    hdu 2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活(多重背包+dp)
    hdoj 1114 Piggy-Bank(完全背包+dp)
    hdoj 2546 饭卡(0-1背包)
    hdoj 2620 Bone Collector(0-1背包)
    U3d开发个人总结
    Android软键盘的用法总结
  • 原文地址:https://www.cnblogs.com/TianFang/p/3191850.html
Copyright © 2011-2022 走看看