python 示例
Python else关键字 (Python else keyword)
else is a keyword (case-sensitive) in python, it is used in the conditional statement with if statement – when given condition with if statement if False, else block executes. Thus, else keyword is used to define a block to be executed if the given test condition is False.
else是python中的一个关键字(区分大小写),在带if语句的条件语句中使用–当带if语句的条件为false时,则执行else块。 因此,如果给定的测试条件为False,则else关键字用于定义要执行的块。
Syntax of else keyword
else关键字的语法
if test_condition:
statement(s)-true
else:
statement(s)-false
Here, if test_condition is True, then statement(s)-true will be executed, if the test_condition is False, then statement(s)-false will be executed.
在这里,如果test_condition为True,则声明(S)-true将被执行,如果test_condition为False,那么声明(S)-false将被执行。
Example:
例:
Input:
str1 = "IncludeHelp"
str2 = "DUGGU"
# condition
if str1==str2:
print("Both strings are equal")
else:
print("Both strings are not equal")
Output:
Both strings are not equal
if,else关键字的Python示例 (Python examples of if, else keywords)
Example 1: Check whether a given number is equal to 0 or not.
示例1:检查给定数字是否等于0。
# python code to demonstrate example of
# if, else keywords
# Check whether a given number is equal to 0 or not
# number
num = 10
if num==0:
print(num, " is equal to 0")
else:
print(num, " is not equal to 0")
Output
输出量
10 is not equal to 0
Example 2: Input two strings check whether they are equal or not.
示例2:输入两个字符串,检查它们是否相等。
# python code to demonstrate example of
# if, else keywords
# Input two strings check whether
# they are equal or not
# input
str1 = input("Enter a string: ")
str2 = input("Enter another string: ")
# comparing strings
if str1==str2:
print("Both input strings are equal")
else:
print("Both input strings are not equal")
Output
输出量
First run:
Enter a string: IncludeHelp.com
Enter another string: Duggu.org
Both input strings are not equal
Second run:
Enter a string: IncludeHelp
Enter another string: IncludeHelp
Both input strings are equal
翻译自: https://www.includehelp.com/python/else-keyword-with-example.aspx
python 示例