【2020Python修炼记12】Python语法入门—流程控制(if分支结构+while/for循环结构)

一、条件

 灵魂三问:

什么是条件?什么可以当做条件?为何要用条件?

1、 条件,就是判断依据,判断前提……

2、条件的类型

# 第一大类:显式布尔值

条件可以是:比较运算符       # age = 18 # print(age > 16)  # 条件判断之后会得到一个布尔值

条件可以是:True、False     # is_beautiful=True # print(is_beautiful)

# 第二大类:隐式布尔值

所有的值都可以当成条件去用     # 其中0、None、空(空字符串、空列表、空字典),代表的布尔值为False

其余都为True

 3、为何要用条件

 条件有助于程序按照人的思想去执行指令,得出人想要的结果。也能够提高代码的效率和价值。

二、逻辑运算符:not、and、or

注意:(不是 not at all)

1、not、and、or的基本使用

# not:就是把紧跟其后的那个条件结果取反
# ps:not与紧跟其后的那个条件是一个不可分割的整体

>>> print(not 16 > 13)
False
>>> print(not True)
False
>>> print(not False)
True
>>> print(not 10)
False
>>> print(not 0)
True
>>> print(not None)
True
>>> print(not '')#'' 空值
True
>>> 

# and:逻辑与,and用来链接左右两个条件,两个条件同时为True,最终结果才为真

>>> print(True and 10 > 3)
True
>>> print(True and 10 > 3 and 10 and 0) # 条件全为真,最终结果才为True
0
>>> print( 10 > 3 and 10 and 0 and 1 > 3 and 4 == 4 and 3 != 3)  # 偷懒原则
0
>>> 

# or:逻辑或,or用来链接左右两个条件,两个条件但凡有一个为True,最终结果就为True,
#            两个条件都为False的情况下,最终结果才为False

>>> print(3 > 2 or 0)
True
>>> print(3 > 4 or False or 3 != 2 or 3 > 2 or True) # 偷懒原则
True
>>> 

三句话总结:

not 就是:真变假,假变真

and 就是:全真为真,一假即假

or 就是:一真即真,全假为假 

2、优先级  not>and>or

# ps:
# 如果单独就只是一串and连接,或者说单独就只是一串or连接,按照从左到右的顺讯依次运算即可(偷懒原则)
# 如果是混用,则需要考虑优先级了

>>> res=3>4 and not 4>3 or 1==3 and 'x' == 'x' or 3 >3
>>> print(res)
False
>>> #       False                 False              False
>>> res=(3>4 and (not 4>3)) or (1==3 and 'x' == 'x') or 3 >3
>>> print(res)
False
>>> #规范表达,尽量用and连接
>>> res=3>4 and ((not 4>3) or 1==3) and ('x' == 'x' or 3 >3)
>>> print(res)
False
>>>

三、成员运算符,身份运算符

1、成员运算符  in

>>> print("egon" in "hello egon") # 判断一个字符串是否存在于一个大字符串中
True
>>> print("e" in "hello egon") # 判断一个字符串是否存在于一个大字符串中
True
>>> print(111 in [111,222,33]) # 判断元素是否存在于列表
True
>>> # 判断key是否存在于字典
>>> print(111 in {"k1":111,'k2':222})
False
>>> print("k1" in {"k1":111,'k2':222})
True
>>> # not in
>>> print("egon" not in "hello egon") # 推荐使用
False
>>> print(not "egon" in "hello egon") # 逻辑同上,但语义不明确,不推荐
False
>>> 

2、身份运算符  is

>>> 
>>> #is # 判断的是id是否相等
>>> x=10
>>> y=23
>>> x is y
False
>>> 

四、流程控制(即控制流程-指控制程序的执行流程)

1、分支结构——if  条件判断

==什么是分支结构==

分支结构就是根据条件判断的真假去执行不同分支对应的子代码

==为什么要用分支结构==

人类某些时候需要根据条件来决定做什么事情,

所以程序中必须有相应的机制来控制计算机具备人的这种判断能力

==如何使用分支结构== 

=1、 if 的语法

完整的if语法如下图:

语法一:单独的 if

if 条件:

(四个空格)代码1

(四个空格)代码2

(四个空格)代码3

 (代码前的空格,是代码等级的区分标志) 

# print(1)
# print(2)
# print(3)
# if 条件:
#     代码1
#     代码2
#     代码3
# print(4)
# print(5)
>>> 
>>> age = 60
>>> is_beautiful = True
>>> if (age > 16 and age < 20 and is_beautiful):
        print('我喜欢,我们在一起吧')
    print('其他代码.............')
>>> 
>>> # if 后面的条件为真,才会执行其后的子代码
>>> age=30
>>> is_nice=True
>>> if age==30 and is_nice:
        print('yes')
        print('no')

    
yes
no   

>>> age=40
>>> is_nice=True
>>> if age>30 and is_nice:
        print('no')
        print('yes')

    
no
yes

>>> age=20
>>> is_nice=True
>>> if age<30 and is_nice:
        print('yes')

    
yes

>>>##有个报错 SyntaxError
>>> if age>30 and is_nice:
        print('no')
    print('yes')
    
SyntaxError: unindent does not match any outer indentation level
#查资料得知(在python中,tab和空格是分开的,在一个文件里混用tab和空格会报错) 出现这个错误时,是换行后,敲了四个空格(英文状态),再输入print('yes'),随后便报错。 解决方法——使用的是Python3.8 解释器,空格和tab不一样吗?
可参考下方解决方法的链接:
https://blog.csdn.net/liuyumoye/article/details/81610311
>>>

语法二:if-else

if(条件):

(四个空格)代码1

else:

(四个空格)代码2 

if 条件:
    代码1
    代码2
    代码3
else:
    代码1
    代码2
    代码3

>>> 
>>> age=18
>>> if age>30:
    print('no')
else:
    print('yes')

    
yes
>>> 
>>>  age = 60
>>>  is_beautiful = True
>>>  star = '水平座'

>>>  if age > 16 and age < 20 and is_beautiful and star == '水平座':
     print('我喜欢,我们在一起吧。。。')
else:
     print('阿姨好,我逗你玩呢,深藏功与名')

print('其他代码.............')####????

语法三:if---elif--else

 ——elif(条件)——上一条件不满足时,才会继续执行 elif(条件),else的命令

语法3-1: if-elif
if 条件1:
    代码1
    代码2
    代码3
elif 条件2:
    代码1
    代码2
    代码3
elif 条件3:
    代码1
    代码2
    代码3
'''
# score=73
# if score >= 90:
#     print('优秀')
# elif score >= 80 and score < 90:
#     print('良好')
# elif score >= 70 and score < 80:
#     print('普通')

# 改进
# score = input('请输入您的成绩:') # score="18"
# score=int(score)
#
# if score >= 90:
#     print('优秀')
# elif score >= 80:
#     print('良好')
# elif score >= 70:
#     print('普通')

>>> 
>>> s=74
>>> if s>=90:
    print('A')
elif s>=80 and s<90:
    print('B')
elif s>=70 and s<80:
    print('C')

    
C
>>> 
>>> s=input('please input your score:')
please input your score:99
>>> s=int(s) #因为在Pyhon解释器中,会将 input()所获得的内容全部当为 字符串类型,字符串类型是不能进行大小比较的。
        因此 需要将输入的分数 强制转换为整型
>>> if s>=90: print('A') elif s>=80 and s<90: print('B') elif s>=70 and s<80: print('C') A >>>

语法3-2:if-elif-else
if 条件1:
    代码1
    代码2
    代码3
elif 条件2:
    代码1
    代码2
    代码3
elif 条件3:
    代码1
    代码2
    代码3
...
else:
    代码1
    代码2
    代码3
'''
# score = input('请输入您的成绩:') # score="18"
# score=int(score)
#
# if score >= 90:
#     print('优秀')
# elif score >= 80:
#     print('良好')
# elif score >= 70:
#     print('普通')
# else:
#     print('很差,小垃圾')
#
# print('=====>')

语法四:if 嵌套if

age = 17
is_beautiful = True
star = '水平座'

if 16 < age < 20 and is_beautiful and star == '水平座':
    print('开始表白。。。。。')
    is_successful = True
    if is_successful:
        print('两个从此过上幸福的生活。。。')
else:
    print('阿姨好')

print('其他代码.............')

循环结构——循环结构就是重复执行某段代码块

2、while 循环——条件循环

 =1=while循环 

while 条件:
     代码1     
     代码2     
     代码3
while的运行步骤:
步骤1:如果条件为真,那么依次执行:代码1、代码2、代码3、......
步骤2:执行完毕后再次判断条件,
如果条件为True则再次执行:代码1、代码2、代码3、......,
如果条件为False,则循环终止
>>> 
>>> count=0
>>> while count<5:
    print(count)
    count+=1

    
0
1
2
3
4
>>> 

=2=死循环和效率问题

>>> count=0
>>> while count < 5: # 5 < 5
           print(count) # 会一直输出 0

# while True:
#     name=input('your name >>>> ')
#     print(name)

# 纯计算无io的死讯会导致致命的效率问题
# while True:
#     1+1

# while 1:
#     print('xxxx')
#如何退出 --
如果你是在程序中让其自动退出,则可以使用:exit() quit() exit() 执行到此命令时,程序终止。
如果是程序陷入死循环,想强制结束,则按ctrl + c。 //这个特别关键

=3=循环的应用

# 下面的栗子,存在两个问题:

# 1、重复代码
# 2、输对了,应该不用再重复

>>> username = 'cc'
>>> password = '123'
>>> while True:
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')
    if inp_name  == username and inp_pwd == password:
        print('登录成功')
    else:
        print('账号名或密码错误')

        
请输入您的账号:'cc'
请输入您的密码:123
账号名或密码错误
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
请输入您的账号:'c'
请输入您的密码:'123'
账号名或密码错误
请输入您的账号:'ccc'
请输入您的密码:'123'
账号名或密码错误
请输入您的账号:'dd'
请输入您的密码:'123'
账号名或密码错误
请输入您的账号:'dd'
请输入您的密码:'12'
账号名或密码错误
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
请输入您的账号:

=4=退出循环的两种方式

=方式一:将条件改成 false

 

>>> 
>>> tag=True
>>> while tag:
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')
    if inp_name  == username and inp_pwd == password:
        print('登录成功')
        tag = False # 登录成功后,就会执行该代码,之后的代码还会运行,下次循环判断条件时才生效——还会再做一次循环判断,然后退出循环
    else:
        print('账号名或密码错误')

        
请输入您的账号:'dd'
请输入您的密码:'123'
账号名或密码错误
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
>>> 

=方式二:while+break,只要运行到break,就会立刻终止本层循环

>>> while True:
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')
    if inp_name  == username and inp_pwd == password:
        print('登录成功')
        break # 立刻终止本层循环
    else:
        print('账号名或密码错误')

        
请输入您的账号:'cc'
请输入您的密码:'1234'
账号名或密码错误
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
>>> 

=7=while 循环嵌套

# 每一层都必须配一个break
while True:
    while True:
        while True:
            break
        break
    break
>>> # break的方式
>>> username = 'cc'
>>> password = '123'
>>> while True: inp_name=input('请输入您的账号:') inp_pwd=input('请输入您的密码:') if inp_name == username and inp_pwd == password: print('登录成功') while True: cmd=input('input message:') if cmd =='q': break print('命令{x}正在运行'.format(x=cmd)) break #立刻终止本层循环 else: print('账号名或密码错误') 请输入您的账号:'dd' 请输入您的密码:'123' 账号名或密码错误 请输入您的账号:'cc' 请输入您的密码:'123' 登录成功 input message:'v' 命令v正在运行 input message:'q' >>>
>>> #改变条件的方式
>>> tag=True
>>> while tag:
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')
    if inp_name  == username and inp_pwd == password:
        print('登录成功')
        while tag:
            cmd=input('input message:')
            if cmd =='q':
                tag=False
            else:
                print('命令{x}正在运行'.format(x=cmd))
    else:
        print('账号名或密码错误')

        
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
input message:'v'
命令v正在运行
input message:'q'
>>> 

=8=while+continue

 结束本次循环,直接进入下一次

 强调:在continue之后添加同级代码毫无意义,因为永远无法运行

>>> username = 'cc'
>>> password = '123'
>>> count=0 >>> while count < 6: if count==4: count+=1 continue count+=1 print(count) count+=1 0 1 2 3 5 >>> count=0 >>> while count < 6: if count==4: count+=1 continue #count+=1 根本没有执行 print(count) count+=1 0 1 2 3 5 >>>

=9=while+else

>>> username = 'cc'
>>> password = '123'
>>> count=0
>>> while count < 6:
    if count==4:
        count+=1
        continue
    print(count)
    count+=1
else:
    print('else包含的代码会在while循环结束后,并且while循环是在没有被break打断的情况下正常结束的,才会运行')

    
0
1
2
3
5
else包含的代码会在while循环结束后,并且while循环是在没有被break打断的情况下正常结束的,才会运行
>>> count=0 >>> while count < 6: if count==4: break print(count) count+=1 else: print('else包含的代码,在while循环结束后,并且while循环是在被break打断的情况下正常结束的,才不会运行') 0 1 2 3 >>>

应用案例:

版本一:

>>> username = 'cc'
>>> password = '123'
>>> count=0
>>> tag=True
>>> while tag:
    if count == 3:
        print('输错三次退出')
        break
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')
    
    if inp_name  == username and inp_pwd == password:
        print('登录成功')
        while tag:
            cmd=input('input message:')
            if cmd =='q':
                tag=False
            else:
                print('命令{x}正在运行'.format(x=cmd))
    else:
        print('账号名或密码错误')
        count+=1

        
请输入您的账号:'ccc'
请输入您的密码:'123'
账号名或密码错误
请输入您的账号:'123'
请输入您的密码:'ff'
账号名或密码错误
请输入您的账号:'22'
请输入您的密码:'222'
账号名或密码错误
输错三次退出

>>> count=0
>>> tag=True
>>> while tag:
    if count == 3:
        print('输错三次退出')
        break
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')

    if inp_name  == username and inp_pwd == password:
        print('登录成功')
        while tag:
            cmd=input('input message:')
            if cmd =='q':
                tag=False
            else:
                print('命令{x}正在运行'.format(x=cmd))
    else:
        print('账号名或密码错误')
        count+=1

        
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
input message:'c'
命令c正在运行
input message:'q'
>>> 

版本二:(优化版)

test 1

>>> username = 'cc' >>> password = '123' >>> count=0 >>> while count < 3: inp_name=input('请输入您的账号:') inp_pwd=input('请输入您的密码:') if inp_name == username and inp_pwd == password: print('登录成功') while True: cmd=input("输入命令>: ") if cmd == 'q': break # 只是退出 子循环 else: print('命令{x}正在运行'.format(x=cmd)) break #整个程序结束,退出所有while循环 else: print('账号名或密码错误') count+=1 else: print('输错3次,退出')

# 第三个else包含的代码,会在while循环结束后,并且while循环是在没有被break打断的情况下正常结束的,才会运行
前面两个else,则是对应两个 if。
请输入您的账号:
'123' 请输入您的密码:'cc' 账号名或密码错误 请输入您的账号:'1234' 请输入您的密码:'234' 账号名或密码错误 请输入您的账号:'cc' 请输入您的密码:'12344' 账号名或密码错误 输错3次,退出

test 2

>>> count=0
>>> while count < 3:
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')

    if inp_name  == username and inp_pwd == password:
        print('登录成功')
        while True:
            cmd=input("输入命令>: ")
            if cmd == 'q': 
                break
            else:
                print('命令{x}正在运行'.format(x=cmd))
        break      # 整个程序结束,退出所有while循环
    else:
        print('账号名或密码错误')
        count+=1
else:
    print('输错3次,退出')

    
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
输入命令>: 'v'
命令v正在运行
输入命令>: 'q'
>>> 

test 3_去掉第二个break(作用-# 整个程序结束,退出所有while循环

>>> count=0
>>> while count < 3:
    inp_name=input('请输入您的账号:')
    inp_pwd=input('请输入您的密码:')

    if inp_name  == username and inp_pwd == password:
        print('登录成功')
        while True:
            cmd=input("输入命令>: ")
            if cmd == 'q': 
                break
            else:
                print('命令{x}正在运行'.format(x=cmd))
        # break
    else:
        print('账号名或密码错误')
        count+=1
else:
    print('输错3次,退出')

    
请输入您的账号:'cc'
请输入您的密码:'123'
登录成功
输入命令>: 'ww'
命令ww正在运行
输入命令>: 'q'
请输入您的账号:'cc'
请输入您的密码:'1234'
账号名或密码错误
请输入您的账号:'1223'
请输入您的密码:'eee'
账号名或密码错误
请输入您的账号:'123'
请输入您的密码:'ee'
账号名或密码错误
输错3次,退出

test 4
再来试一遍,可以总结出,如果不给外循环加一个break,
就算是输入正确,也会继续执行内循环,知道输错三次才会结束整个程序。

>>> count=0 >>> while count < 3: inp_name=input('请输入您的账号:') inp_pwd=input('请输入您的密码:') if inp_name == username and inp_pwd == password: print('登录成功') while True: cmd=input("输入命令>: ") if cmd == 'q': break else: print('命令{x}正在运行'.format(x=cmd)) # break # 整个程序结束,退出所有while循环 else: print('账号名或密码错误') count+=1 else: print('输错3次,退出') 请输入您的账号:'cc' 请输入您的密码:'123' 登录成功 输入命令>: 'q' 请输入您的账号:'cc' 请输入您的密码:'123' 登录成功 输入命令>: 'w' 命令w正在运行 输入命令>: 'q' 请输入您的账号: Traceback (most recent call last): File "<pyshell#138>", line 2, in <module> inp_name=input('请输入您的账号:') File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing >>>

 

3、for循环——取值循环

==1==什么是for循环

 循环就是重复做某件事,for循环是python提供第二种循环机制

==2==为什么要有for循环

 理论上for循环能做的事情,while循环都可以做
 之所以要有for循环,是因为for循环在循环取值(遍历取值)比while循环更简洁

==3==如何使用for循环

=基本语法=

语法:
for 变量名 in 可迭代对象: # 可迭代对象可以是:列表、字典、字符串、元组、集合
    代码1
    代码2
    代码3
    ...

= 案例 一= 循环取值

【简单版】 for

>>> 
>>> l=['cat','love','mili']
>>> for x in l:
    print(x)

    
cat
love
mili
>>> 

【复杂版】 while

>>> l=['cat','love','mili']
>>> i=0
>>> while i<3:
    print(l[i])
    i+=1

    
cat
love
mili
>>> 

= 案例二=字典循环取值

【简单版】 

>>> dic={'k1':111,'k2':2222,'k3':333}
>>> for k in dic:
    print(k,dic[k])

    
k1 111
k2 2222
k3 333
>>> 

【复杂版】while循环可以遍历字典,不过太麻烦……(此处省略若干字)

=案例三=字符串循环取值

【简单版】 

>>> 
>>> info='cat love mili'
>>> for x in info:
    print(x)

    
c
a
t
 
l
o
v
e
 
m
i
l
i
>>> 

【复杂版】

 while循环也可以循环取值,不过太麻烦……(此处省略若干字)

==4== for循环控制循环次数 range()

 =案例一= 

>>> # python 3.8版本中:
>>> range(10)
range(0, 10)
>>> range(0,10)
range(0, 10)
>>> range(1,9)
range(1, 9)
>>> 
>>> #python 2 与python 3 会有不同形式的输出:
>>> 

 =案例二= for+break、 for+else——同while循环一样

>>> username='cc'
>>> usercode='123'
>>> for i in range(3):
    name1=input('please input your name:')
    code1=input('please input your code:')
    if name1==username and code1==usercode:
        print('登陆成功')
        while True:
            cmd=input('请输入指令:')
            if cmd=='q':#不要掉了冒号噢
                break
            else:
                print('命令{x}正在执行'.format(x=cmd))
        break
    else:
        print('账号名或密码错误')
else:
    print('输错账号密码次数过多')

    
please input your name:cc
please input your code:123
登陆成功
请输入指令:1
命令1正在执行
请输入指令:'q'
命令'q'正在执行
请输入指令:q
>>> for i in range(3):
    name1=input('please input your name:')
    code1=input('please input your code:')
    if name1==username and code1==usercode:
        print('登陆成功')
        while True:
            cmd=input('请输入指令:')
            if cmd=='q':#不要掉了冒号噢
                break
            else:
                print('命令{x}正在执行'.format(x=cmd))
        break
    else:
        print('账号名或密码错误')
else:
    print('输错账号密码次数过多')

    
please input your name:22
please input your code:22
账号名或密码错误
please input your name:22
please input your code:22
账号名或密码错误
please input your name:22
please input your code:22
账号名或密码错误
输错账号密码次数过多
>>> 

=案例三= range()补充  

# 1、for搭配range,可以按照索引取值,但是麻烦,所以不推荐
# l=['aaa','bbb','ccc'] # len(l)
# for i in range(len(l)):
#     print(i,l[i])
#
# for x in l:
#     print(l)

# 2、range()在python3里得到的是一只"会下蛋的老母鸡"

==5== for+continue 

# for i in range(6):  # 0 1 2 3 4 5
#     if i == 4:
#         continue
#     print(i)

==6== for循环嵌套——:外层循环循环一次,内层循环需要完整的循环完毕 

# for i in range(3):
#     print('外层循环-->', i)
#     for j in range(5):
#         print('内层-->', j)

# 补充:终止for循环只有break一种方案

==7==补充关于print()的知识  

print('hello %s' % 'egon')
# 1、print之逗号的使用
print('hello','world','egon')

# 2、换行符
print('hello
')
print('world')

# 3、print值end参数的使用
print('hello
',end='')
print('word')
print('hello',end='*')
print('world',end='*')

4、比较while循环和for循环的异同

==相同之处==

 都是循环,for循环可以干的事,while循环也可以干 

==不同之处==

while循环称之为 条件循环,循环次数取决于条件何时变为假
for循环称之为 "取值循环",循环次数取决in后包含的值的个数

原文地址:https://www.cnblogs.com/bigorangecc/p/12425586.html