Python新手入门【语句结构】

93 阅读1分钟

1.条件语句

  • if用法

    flag = False name = 'luren' if name == 'python':
    flag = True
    print 'welcome boss'
    else: print name

输出结果为:

luren            # 输出结果
  • elif用法

    num = 5
    if num == 3: # 判断num的值 print 'boss'
    elif num == 2: print 'user' elif num == 1: print 'worker' elif num < 0: # 值小于零时输出 print 'error' else: print 'roadman' # 条件均不成立时输出

输出结果为:

roadman        # 输出结果

2.循环语句

2.1 循环类型

  • while循环

    count = 0 while (count < 9): print('The count is:', count) count = count + 1

    print("Good bye!")

输出结果为:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
  • for循环

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

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

    print "Good bye!"

输出结果为:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

2.2 循环控制语句

控制语句描述
break在语句块执行过程中终止循环,并且跳出整个循环
continue在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环
passpass是空语句,是为了保持程序的完整性