文章目录
前言
本文的主要内容是介绍Python中 if 语句及其使用,包括条件测试、if -else 语句、if -elif-else 语句以及使用 if 语句处理列表操作,文中附有代码以及相应的运行结果辅助理解。
一、 条件测试
每条 if 语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。Python根据条件测试的值为True还是False来决定是否执行 if 语句中的代码。如果条件测试的值为True,就执行紧跟在 if 语句后面的代码;如果值为False,Python就忽略这些代码。
1.比较字符串相等或不相等
下面是条件测试检查变量的值与特定值是否相等/不相等的例子。
fruit = 'apple' print('1.' + str(fruit == 'apple')) #判断是否相等 print('2.' + str(fruit == 'banana')) print('3.' + str(fruit != 'apple')) #判断是否不相等 print('4.' + str(fruit != 'banana'))
2.比较数字
num1 = 20 num2 = 30 print('1.' + str(num1 == num2)) print('2.' + str(num1 != num2)) print('3.' + str(num1 >= num2)) print('4.' + str(num1 <= num2))
3.检查多个条件
num1 = 20 num2 = 30 print('1.' + str(num1 >= 15 and num2 >= 15)) print('2.' + str(num1 >= 25 and num2 >= 25)) print('3.' + str(num1 >= 25 or num2 >= 25)) print('4.' + str(num1 >= 35 or num2 >= 35))
4.检查特定值是否在列表中
fruits = ['grape', 'apple', 'banana', 'orange', 'pear'] print('1.' + str('apple' in fruits)) print('2.' + str('mango' in fruits)) print('3.' + str('banana' not in fruits)) print('4.' + str('watermelon' not in fruits))
二、if 语句
弄懂了上面介绍的条件测试后,就可以开始编写if语句了。
1.简单的if语句
下面是一个简单的if语句例子。
num = 25 if num >= 20: print('The number is over '+str(num)+'.') if num < 20: print('The number is under ' + str(num) + '.')
2. if-else 语句
上面的例子写了两个if语句,其可以由一个if-else 语句代替。
num = 25 if num >= 20: print('The number is over '+str(num)+'.') else: print('The number is under ' + str(num) + '.')
输出结果与上面的例子相同。
3. if-elif-else 语句
age = 13 if age <= 3: print('The age under 3 is free.') elif age <= 12: print('The age between 3 and 12 is half price.') else: print('The age over 12 is full price.')
三、使用 if 语句处理列表
在编程中,结合使用 if 语句和列表可以高效的完成一些任务,当然,与列表配合使用的还有for循环。
1.使用 if 语句检查列表中的特殊元素
fruits = ['grapes', 'apples', 'bananas', 'oranges', 'pears'] for fruit in fruits: if fruit == 'apples': print('Sorry, we are out of apples right now.') else: print(fruit.title() + ' are available.')
2.检查列表是否为空
fruits = [] if fruits: for fruit in fruits: if fruit == 'apples': print('Sorry, we are out of apples right now.') else: print(fruit.title() + ' are available.') else: print('The list is empty.')
3.使用多个列表
fruits_available = ['grapes', 'apples', 'bananas', 'oranges', 'pears'] fruits_want = ['mangoes', 'apples', 'bananas', 'watermelons', 'pears'] for fruit in fruits_want: if fruit in fruits_available: print('We have ' + fruit +'.') else: print("Sorry, we don't have " + fruit +'.') print('Check complete!')
总结
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/200933.html原文链接:https://javaforall.net
