else在python中是一个关键字(区分大小写),在带if语句的条件语句中使用–当带if语句的条件为false时,则执行else块。因此,如果给定的测试条件为False ,则else关键字用于定义要执行的块。
else关键字的语法
if test_condition: statement(s)-true else: statement(s)-false
在这里,如果test_condition为True,则 statement(s)-true将被执行,如果test_condition为False,则 statement(s)-false将被执行。
示例
Input: str1 = "nhooo" str2 = "DUGGU" # 条件 if str1==str2: print("Both strings are equal") else: print("Both strings are not equal") Output: Both strings are not equal
示例1:检查给定数字是否等于0。
# python代码演示示例 # 如果,否则关键字 # 检查给定数字是否等于0 # 数 num = 10 if num==0: print(num, " is equal to 0") else: print(num, " is not equal to 0")
输出结果
10 is not equal to 0
示例2:输入两个字符串,检查它们是否相等。
# python代码演示示例 # 如果,否则关键字 # 输入两个字符串,检查是否 # 他们是否相等 # 输入 str1 = input("Enter a string: ") str2 = input("Enter another string: ") # 比较字符串 if str1==str2: print("Both input strings are equal") else: print("Both input strings are not equal")
输出结果
First run: Enter a string: nhooo.com Enter another string: Duggu.org Both input strings are not equal Second run: Enter a string: nhooo Enter another string: nhooo Both input strings are equal