一、if 判断
语法一:if判断
sex = 'female' age = 32 is_beautiful = True if sex == 'female' and age == 18 and is_beautiful: print('Begin your love words:') print('another code1') print('another code2')
if判断使用注意事项:if条件紧跟着一个冒号:+回车,pycharm会自动进入到下一行并缩进4个空格,开始进入运行一组代码块。在这里注意中英文输入法对代码“括号、冒号、逗号”这些字符的影响,谨记一定要用英文输入法输入,不然容易出现报错。
语法二:if+else判断
sex = 'female' age = 18 is_beautiful = True if sex == 'female' and 16 < age <24 and is_beautiful: print('Begin your love words.') else: print('Say nothing...')
语法三:if+else 的嵌套
sex = 'female' age = 18 is_beautiful = True is_success = True if sex == 'female' and 16 < age <24 and is_beautiful: print('Begin your love words.') if is_success: print('HaHaHa') else: print('I hate love,go away!') else: print('Say nothing...')
tip:①and 多个条件并过长时,可用‘\+回车’来多行显示,这里不影响语法。
②快捷操作,TAB键 可以进行快捷缩进,比如选中多行一起快捷缩进,要回退的话,按shift+tab组合键。
语法四:if+elif+else
# 输入成绩判断优秀、很好、一般、很差 score = input('Please input your score:') score = int(score) if score >= 90: print('优秀') elif score >= 80: print('很好') elif score >= 70: print('一般') else: print('很差')
小练习:
name = input('请输入您的用户名:') pwd = input('请输入您的密码:') if name == 'sgt' and pwd == '123': print('登陆成功') else: print('用户名或密码错误')