python中的分支和循环:for 循环,while循环,三元操作符,断言,assert关键字,rang()函数总结

1.python中的条件语句

例:score=int(input('请输入一个分数'))       
if 100>=score>=90:                                   
    print('A')                                                       
elif 90>score>=80:
    print('B')                                                                
elif 80>score>=60:                                               
    print('C')                                                  
elif 60>score>=0:                                             
    print('D')                                                                
else:                                                                     
    print('输入错误')                                              
中直接使用elif不需要else if了      

三元操作符:small=x if x<y else y语法:x if 条件 else y

二元操作符:

x,y=4,5

if x<y:

  small=x

else:

   small=y

意思与上面三元操符意思相等                     

2.python中的断言

assert这个关键字即为断言,当关键字后面的条件为假时,程序自动崩溃并抛出AssertionError的异常。

>>> assert 3==4
Traceback (most recent call last):
  File "<pyshell#57>", line 1, in <module>
    assert 3==4
AssertionError

作用:可以用assert关键字在程序中置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert就有用

3

while循环

while 条件:

    循环体(条件为真)

for循环

语法:for  目标  in  表达式:

                 循环体

其中len(str)可以算出str的字符数量

4        rang()

语法:rang([start,]   stop   [,step=1])

      这个BIF有三个参数,其中用中括号括起来的是可选的,step=1表示第三个参数的默认值为1,意思是以1为单位步进

       该BIF表示生成一个从start参数值开始到stop参数的值结束的数字序列,其中,当括号内只有stop时,默认初始值是0

原文地址:https://www.cnblogs.com/chmusk/p/12465899.html