首页 > 编程语言 >python中的if和elif区别

python中的if和elif区别

时间:2022-09-04 17:25:22浏览次数:62  
标签:code1 elif 区别 python res number numbers

代码1:

 1 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
 2 for number in numbers:
 3     if number == 1:
 4         res='st'
 5     if number == 2:
 6         res='nd'
 7     if number == 3:                                                      
 8         res='rd'
 9     else:
10         res='th'
11     print(f"{number}{res}")

结果:

python code1.py 
1th
2th
3rd
4th
5th
6th
7th
8th
9th

代码2:

 1 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
 2 for number in numbers:
 3     if number == 1:
 4         res='st'
 5     elif number == 2:
 6         res='nd'
 7     elif number == 3:                                                    
 8         res='rd'
 9     else:
10         res='th'
11     print(f"{number}{res}")

结果:

python code1.py 
1st
2nd
3rd
4th
5th
6th
7th
8th
9th

由此可见,code1中使用if时,只有number==3时,才发生改变,1和2时被3给覆盖了。code2中,使用elif时,三种情况1 2 3时全部进行处理,根据实际情况,只需要其中一种使用if并列即可。如果也许需要多种情况均满足,使用elif并列更加合理。

总之:  =陈述语气,是设置值,也就是赋值,运算是从右到左侧

     ==疑问语气,是条件判断,判断是否相等,运算是从左到右侧

标签:code1,elif,区别,python,res,number,numbers
From: https://www.cnblogs.com/guochaoxxl/p/16655460.html

相关文章

  • cpp和c中struct用法的区别
    cpp和c中struct用法的区别c中的struct不使用typedefC语言中,定义struct的语法如下:struct[<tag>]{<member-list><member-list><member-list>.........
  • Python scrapy 爬虫 模拟登录
    模拟登录,可以解决某些网站,必须要登录才能抓取的问题。模拟登录就是要拿到网站的cookie。当爬虫程序进入网站开始抓取时数据时,爬虫的入口并不是scrapy 给定的pass,而......
  • 【Python基础】内置函数filter详解
    filter,顾名思义,就是一个过滤器。其作用是从列表(或其他序列类型)中筛选出满足条件的子列表,filter是python的内置函数,无须import即可直接使用。1filter的基础用法对于列表(或......
  • let,var,const的区别
    js中let,var,const的区别(1)块级作用域:块级作用域由{}包括,let和const具有块级作用域,var不存在块级作用域(2)变量提升:var存在变量提升,let和const不存在变量提升,即在变......
  • call、apply、bind三者的用法和区别
    call、apply、bind三者的用法和区别call非严格模式如果不传参数,或者第一个参数是null或nudefined,this都指向window严格模式第一个参数是谁,this就指向谁,包括null和unde......
  • Python中assert断言添加错误提示信息
    参考资料:https://www.cnblogs.com/meina/p/13848090.html当我们使用Python写代码的时候,可以多用assert断言语句来让代码变得更加鲁棒。但是如果单纯用assert......
  • catalina.out 和 catalina.log 的区别和用途
    目录catalina.out和catalina.log的区别和用途catalina.outcataliana.{yyyy-MM-dd}.log和localhost.{yyyy-MM-dd}.log总结catalina.out和catalina.log的区别和用途c......
  • python读取xlsx文件并转化为 json 数据
    fromopenpyxlimportload_workbookimportosfromreimportfindallimportjson#读取所有的sheet目录defread_xlsx(path="./"):lis=os.listdir(path)......
  • Mybatis的ResultMap和ResultType的区别
    在使用mybatis进行数据库连接操作时对于SQL语句返回结果的处理通常有两种方式,一种就是resultType另一种就是resultMap,下面说下我对这两者的认识和理解resultType:当使用re......
  • Python入门系列(九)pip、try except、用户输入、字符串格式
    pip包含模块所需的所有文件。检查是否安装了PIP$pip--version安装包$pipinstallpackage_name使用包importpackage_name删除包$pipuninstallcamelcase......