How to use if statement in Python?

In Python, the if statement is used to execute different code blocks based on a condition. The basic syntax for the if statement is as follows:

if 条件:
    # 条件为真时执行的代码块
else:
    # 条件为假时执行的代码块

Here is a simple example to determine if a number inputted by the user is positive.

num = int(input("请输入一个数字:"))

if num > 0:
    print("输入的数字是正数")
else:
    print("输入的数字不是正数")

In the example above, first call the input() function to get the number input from the user, then use the int() function to convert the input string to an integer. Next, use an if statement to check if the number is greater than 0. If it is, print “The input number is positive”, otherwise print “The input number is not positive”.

In addition to using the “if” statement, you can also use the “elif” keyword to add multiple condition checks. For example, the following example determines the grade based on the user’s input score.

score = int(input("请输入你的成绩:"))

if score >= 90:
    print("你的等级是A")
elif score >= 80:
    print("你的等级是B")
elif score >= 70:
    print("你的等级是C")
elif score >= 60:
    print("你的等级是D")
else:
    print("你的等级是E")

In the example above, different grades are printed based on different score ranges. If the score is greater than or equal to 90, it will print an “A” grade; if the score is between 80 and 89, it will print a “B” grade, and so on. If the score is outside of any range, it will print an “E” grade.

bannerAds