Python data analysis combat 5.2-condition judgment: if statement [python]

[Course 5.2] Conditional judgment: if statement

A Python conditional statement is a block of code that is determined by the execution result (True or False) of one or more statements.

if judgment condition:
execute statement ...
else:
execute statement ...

** Beginning with the concept of indentation

1. Basic judgment statement

age = 12
if age < 18:
    print('18岁以下不宜观看')
# if语句后面必须有 : 
# 自动缩进
# if语句写完后,要退回原有缩进继续写
# Python代码的缩进规则:具有相同缩进的代码被视为代码块

2. Input function input ()

score = input('请输入成绩:')
print('该学生成绩为:' + score)
print(type(score))
# 注意:input()返回结果都为字符串,如果需要变为数字则用到int()/float()
----------------------------------------------------------------------
请输入成绩:60
该学生成绩为:60
<class 'str'>

3. Two conditions to judge: if-else

flag = False
name = 'luren'
if name == 'python':          # 判断变量否为'python'
    flag = True               # 条件成立时设置标志为真
    print( 'welcome boss')    # 并输出欢迎信息
else:
    print(name)               # 条件不成立时输出变量名称

4. Judgment of multiple conditions: if-elif -...- else

num = 2    
if num == 3:            # 判断num的值
    print('boss')       
elif num == 2:
    print('user')
elif num == 1:
    print('worker')
elif num < 0:           # 值小于零时输出
    print('error')
else:
    print('roadman')    # 条件均不成立时输出

5. Single statement multiple condition judgment: or and

num = 5
if num >= 0 and num <= 10:    
    print( 'hello')
# 判断值是否在0~10之间
# 输出结果: hello
 
num = 10
if num < 0 or num > 10:    
    print( 'hello')
else:
    print( 'undefine')
# 判断值是否在小于0或大于10
# 输出结果: undefine
 
num = 8
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
    print( 'hello')
else:
    print( 'undefine')
# 判断值是否在0~5或者10~15之间
# 输出结果: undefine

Small homework
① Write a simple judgment sentence code: enter a certain score, if the score is greater than or equal to 60 points, then return to pass, less than 60 points, then return to fail
② Write a code to guess the number of small games: enter a number Judgment on guessing the right number, guessing the wrong number, and inputting errors

Published 36 original articles · praised 17 · visits 6274

Guess you like

Origin blog.csdn.net/qq_39248307/article/details/105476803