首页 > 编程语言 > 详细

【Python基础知识】(四)比较运算符、逻辑运算符和if语句

时间:2020-07-09 18:32:29      阅读:65      评论:0      收藏:0      [点我收藏+]

比较运算符

1、检查是否相等

  相等运算符(==):用来判断二者是否“相等”,注意与赋值运算符(=)区分

car = audi
‘‘‘在Python中判断是否相等时区分大小写‘‘‘
car == Audi    ‘‘‘False‘‘‘
car.title() == Audi    ‘‘‘True‘‘‘

 

2、检查是否不相等

  (1)比较数字:小于(<)、小于等于(<=)、大于(>)、大于等于(>=)

age = 19

age < 21    ‘‘‘True‘‘‘
age <= 21    ‘‘‘True‘‘‘
age > 19    ‘‘‘False‘‘‘
age >= 19    ‘‘‘True‘‘‘

  (2)条件判断:不等于(!=)

requested_topping = mushrooms

if requested_topping != anchovies:
    print( "Hold the anchovies!" )

 

逻辑运算符

  使用逻辑运算符andor可一次检查多个条件,形成更复杂的判断式。

age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21    ‘‘‘False‘‘‘
age_0 >= 21 or age_1 >= 21    ‘‘‘True‘‘‘
age_1 = 22
age_0 >= 21 and age_1 >= 21    ‘‘‘True‘‘‘

 

if语句

  上述程序中的判断语句,均可作为if语句的条件测试。若测试值为真,Python将会执行if语句所包含的代码,若为假则不会执行。

 

1、简单的if语句

age = 19
if age >= 18:
    print( "You are old enough to vote!" )

 

2、if-else语句

age = 17
if age >= 18:
    print( "You are old enough to vote!" )
    print( "Have you registered to vote yet?" )
else:
    print( "Sorry, you are too young to vote." )
    print( "Please register to vote as soon as you turn 18!" ) 

输出为:

Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

  和for语句相同,当测试值为真时,Python会执行所有紧跟在if语句之后且缩进的代码

 

3、if-elif-else结构(elif意为else if)

age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5

print( "Your admission cost is " + str(price) + " dollars." )

 

使用if语句处理列表

1、判断列表是否为空

  当把列表名用作if语句的条件表达式时,Python将在列表至少包含一个元素时返回True,在列表为空时返回False。

requested_toppings = []
if requested_toppings:
    print( "not empty" )
else:
    print( "empty" )
‘‘‘列表为空,故打印empty‘‘‘

 

2、判断元素是否在列表中

  使用in表示包含于列表,not in表示不包含于列表。

available_toppings = [ mushrooms, olives, green peppers, 
                                pepperoni, pineapple, extra cheese ]
requested_toppings = [ mushrooms, french fries, extra cheese ]

for requested_topping in requested_toppings:
    if requested_topping not in available_toppings:
        print( "Sorry, we don‘t have " + requested_topping + "." )
    else:
        print( "Adding " + requested_topping + "." )

print( "\nFinished making your pizza!" )

输出为:

Adding mushrooms.
Sorry, we dont have french fries.
Adding extra cheese.

Finished making your pizza!

 

参考书籍:《Python编程:从入门到实践》

2020-07-09

 

【Python基础知识】(四)比较运算符、逻辑运算符和if语句

原文:https://www.cnblogs.com/carl39/p/13275061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!