Pyhton语句

一、if条件语句

1.python 并不支持 switch 语句

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

2.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

二、循环语句

1.while循环语句

  • while 判断条件: 执行语句……
#!/usr/bin/python
count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

2.for循环语句

  • for iterating_var in sequence: statements(s)
#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

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

for i in range(10):
    print (i)

猜你喜欢

转载自www.cnblogs.com/narjaja/p/9441297.html
今日推荐