Python成长记五(流程控制语句if,if-else,elif)

流程控制语句:
一、python编码规范及特点:
1.末尾没有分号,也不要用分号将两条命令放在同一行
2.缩进区分代码块,用4个空格来缩进代码
3.行长度每行建议不超过80个字符,如果一个文本字符串在一行放不下, 可以使用圆括号来实现隐式行连接,如:
x = ('这是一个非常长非常长非常长非常长 '
     '非常长非常长非常长非常长非常长非常长的字符串')
4.括号:除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号
5.空行:顶级定义之间空两行, 比如函数或者类定义. 方法定义, 类定义与第一个方法之间, 都应该空一行

二.条件控制语句( if else)
注释:
(1)单行注释用 #
(2)多行注释用 ''' 注释内容 '''

流程控制语句基本语法:
a =False
if a:
    print('a的值为True')
else:
    print('a的值为False')
注意:a的值可以是一个表达式
如:
  (1)     a = 1
b = 2
if a > b:
    print('值为True')
else:
    print('值为False')
结果:值为False
  (2)
                a = 1
b = 2
c = 2
if a or b +1 == c:
    print('值为True')
else:
    print('值为False')
结果:值为True
(3)为空值得情况
d = []
if d:
    print('值为True')
else:
    print('值为False')
结果:值为False
(4)模仿用户登录
    account = 'jason'
password = '123456'

print('please input account')
user_account = input()

print('please input password')
user_password = input()

if account == user_account and password == user_password:
               print('success')
else:
             print('fail')
      (5)嵌套使用
         结构:
            if condition:
               if condition:
                    pass
               else:
                pass
            else:
                if condition:
                pass
            else:
            pass
        
二、条件控制语句elif的优点
 
 比较语句:
   1.输出想要的字母(繁琐的表达方式)
                a = input()

a = int(a)

if a == 1:
    print('a')
else:
    if a ==2:
        print('b')
    else:
        if a == 3:
            print('c')
        else:
            print('d')
    2.使用elif语句(简洁的表达方式,减少嵌套的级别)
        a = input()
a = int(a)
if a == 1:
    print('a')
elif a == 2:
    print('b')
elif a == 3:
    print('c')
else:
    print('d')

小提示:代码规范检测工具(Pylint),比如检测常量定义,文档注释等
注意:python没有真真意义上的常量
小技巧:snippet 片段 (作用快速构建代码片段,提高开发效率)

为什么python语言中没有switch开关语句?

官方解释:


地址:https://docs.python.org/2/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python

解决方案:
   1.多个elif代替switch
   2.字典的方式代替switch

总结:
---> if可以单独使用,else需要配对使用
---> pass 空语句/占位语句

猜你喜欢

转载自blog.csdn.net/q_jimmy/article/details/80459532