03 Conditional statement

Reprinted from Datawhale open source learning library

https://github.com/datawhalechina/team-learning-program/tree/master/PythonLanguage

Conditional statements

1. if statement

if expression:
    expr_true_suite
  • if the statement expr_true_suiteblock of code only if the conditional expression expressionis true if implemented, otherwise we will continue to execute the statement immediately behind the code block.
  • Single statement if expressionthe conditional expression by Boolean operators and, orand notto achieve multiple conditional.

【example】

if 2 > 1 and not 2 > 3:
    print('Correct Judgement!')

# Correct Judgement!

2. if-else statement

if expression:
    expr_true_suite
else:
    expr_false_suite
  • Python provides the else used with if. If the result of the conditional expression of the if statement is false, the program will execute the code after the else statement.

【example】

temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
    print("你太了解小姐姐的心思了!")
    print("哼,猜对也没有奖励!")
else:
    print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")

ifSentences support nesting, which means that one ifsentence is embedded in another ifsentence to form a different level of selection structure. Python uses indentation instead of curly braces to mark code block boundaries, so pay special attention to elsethe hanging problem.

【example】

hi = 6
if hi > 2:
    if hi > 7:
        print('好棒!好棒!')
else:
    print('切~')

【example】

temp = input("不妨猜一下小哥哥现在心里想的是那个数字:")
guess = int(temp)
if guess > 8:
    print("大了,大了")
else:
    if guess == 8:
        print("你这么懂小哥哥的心思吗?")
        print("哼,猜对也没有奖励!")
    else:
        print("小了,小了")
print("游戏结束,不玩儿啦!")

3. if-elif-else statement

if expression1:
    expr1_true_suite
elif expression2:
    expr2_true_suite
    .
    .
elif expressionN:
    exprN_true_suite
else:
    expr_false_suite
  • The elif statement is the else if, used to check whether multiple expressions are true, and execute the code in a specific code block when it is true.

【example】

temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
    print('A')
elif 90 > source >= 80:
    print('B')
elif 80 > source >= 60:
    print('C')
elif 60 > source >= 0:
    print('D')
else:
    print('输入错误!')

4. assert keywords

  • assertWe call this keyword "assertion". When the condition behind this keyword is False, the program automatically crashes and throws AssertionErroran exception.

【example】

my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0

# AssertionError
  • During unit testing, it can be used to place checkpoints in the program. Only the condition is True can the program work normally.

【example】

assert 3 > 7

# AssertionError

Guess you like

Origin blog.csdn.net/Han_Panda/article/details/113091983