条件控制
1.注释
单行注释:前边加# 快捷键:CTRL+/ 或者 CTRL+Q
多行注释:快捷键:STRL+SHIFT+Q
2.条件语句
if else
mood = False
if mood :
print('go to left')
# print('back')
else:
print('go to right')
注意python中,缩进符表示语句在if else的管理范围内,删去缩进符就会报错
一段比较规范的代码
""" 一段小程序 """
ACCOUNT = 'qiyue'
PASSWD = '123456'
print('please input account')
USER_ACCOUNT = input()
print('please input passwd')
USER_PASSWD = input()
if USER_ACCOUNT == ACCOUNT and USER_PASSWD == PASSWD:
print('success')
else:
print('fail')
(1)最上方要有模块说明
(2)常亮命名用大写
(3)赋值、比较运算符的前后各有一个空格
(4)if else的:前不要有空格
(5)if else控制的语句前方要有四个空格,并不一定是一个tab,在vscode中,一个tab正好是4个空格,所以两种写法都可以,其他ide中可能只能打4个空格来正确表示缩进
3.snippet片段


4.嵌套分支和代码块
if else可以嵌套使用
5.elif的使用
常规写法:
print('please input A')
A = input()
print('A is '+ A)
if A == 1:
print('orange')
else:
if A == 2:
print('apple')
else:
if A == 3:
print('banana')
else:
print('shopping')
使用elif
print('please input A')
A = input()
print('A is '+ A)
if A == 1:
print('orange')
elif A == 2:
print('apple')
elif A == 3:
print('banana')
else:
print('shopping')
6.注意input输入的类型
运行下面这段代码:
print('please input A')
A = input()
print('A is '+ A)
if A == 1:
print('orange')
elif A == 2:
print('apple')
elif A == 3:
print('banana')
else:
print('shopping')
终端显示结果:
please input A
2
A is 2
shopping
发现A == 2这个比较语句没生效
分析原因,应该是因为input输入的,计算机当做了str类型,和int类型的2不相等,所以应该首先进行一次类型转换
print('please input A')
A = input()
print('A is '+ A)
print(type(A))
A = int(A)
if A == 1:
print('orange')
elif A == 2:
print('apple')
elif A == 3:
print('banana')
else:
print('shopping')
终端输出结果:
please input A
3
A is 3
<class 'str'>
banana
结果正确
网友评论