Python 各种语句:2018-07-27

1. If...elif...else条件语句

# -*- coding: UTF-8 -*-
 
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'     # 条件均不成立时输出
  • Python 不支持switch语句,所以多个条件的判断只能用elif来实现
# -*- coding: UTF-8 -*-
 
# 例3:if语句多个条件
 
num = 9
if num >= 0 and num <= 10:    # 判断值是否在0~10之间
    print 'hello'
# 输出结果: hello
 
num = 10
if num < 0 or num > 10:    # 判断值是否在小于0或大于10
    print 'hello'
else:
    print 'undefine'
# 输出结果: undefine
 
num = 8
# 判断值是否在0~5或者10~15之间
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
    print 'hello'
else:
    print 'undefine'
# 输出结果: undefine
  • 也可以在同一行的位置上使用if条件判断语句:
# -*- coding: UTF-8 -*-
 
var = 100 
 
if ( var  == 100 ) : print "变量 var 的值为100" 

2. while 循环语句

# -*- coding: UTF-8 -*-
numbers = [1,2,3,4,5,6,7,8,9]
odd=[]
even=[]
while len(numbers)>0:
    number = numbers.pop()
    if (number%2==0):
        even.append(number)
    else:
        odd.append(number)
print odd
print even


i = 1
while i<10:
    i+=1
    if i%2==0:
        continue
    print i #输出奇数 3,5,7,9
else:
    print "i >= 10" #else可以和while连用
i = 1
while 1:
    print i
    i += 1
    if i>10:
        break
  • continue break的用法同C++
  • while可以与else连用
  • 类似 if 语句的语法,如果你的 while 循环体中只有一条语句,你可以将该语句与while写在同一行中

3. Python for循环

  1. for循环的格式如下:

for iterating_var in sequence:
statements(s)

示例:

# -*- coding: UTF-8 -*-
for letter in 'Python':
    print "Current letter:",letter

fruits = ['banana','apple','orange']
for fruit in fruits:
    print "Current fruit:",fruit
for index in range(len(fruits)):
    print "Current fruit:",fruits[index]

  1. for循环使用 else 语句
for num in range(10,20):
    for i in range (2,num):
        if num%i==0:
            j=num/i
            print '%d = %d * %d'%(num,i,j)
            break
    else:
        print num,"is a prime number"
  • for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行

3. pass 语句

pass是空语句,是为了保持程序结构的完整性,不做任何事情,一般做占位语句。

# -*- coding: UTF-8 -*-
for letter in 'Python':
    if letter == 'h':
        pass
        print "这是pass块"
    print "Current letter:",letter
原文地址:https://www.cnblogs.com/qiulinzhang/p/9513602.html