Python 各种语句:2018-07-27

2018-07-27  本文已影响6人  默写年华Antifragile

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'     # 条件均不成立时输出
# -*- 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
# -*- 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

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"

3. pass 语句

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

# -*- coding: UTF-8 -*-
for letter in 'Python':
    if letter == 'h':
        pass
        print "这是pass块"
    print "Current letter:",letter
上一篇下一篇

猜你喜欢

热点阅读