一、if判断
基本语法格式:
1.语法一:
if 条件:
示例:#判断一个姑娘年级大不大、美不美丽,如果符合自己的要求,就去表白。。。
sex='female' #定义性别
age=18 #定义年龄
is_pritty=True #定义是否漂亮
if age>16 and age<20 and is_pritty and sex='female': #如果年龄在16~18岁,是个女的,还挺漂亮,唉~
print('开始表白。。。') #代码运行结果:开始表白。。。
2.语法二:
if 条件:
# 条件成立时执行的子代码块
代码1
代码2
代码3
else:
# 条件不成立时执行的子代码块
代码1
代码2
代码3
示例:#还是那个案例,对一个美女,你通过判断实现要不要表白,要么表白;要么,你叫阿姨
age=18 #定义年龄 如果把年龄定义成 age=66
sex='female' #定义性别
is_pritty=True #定义是否漂亮
if age>16 and age<18 and is_pritty: #如果年龄在16~18岁,是个女的,还挺漂亮,唉~
print('表白...')
else:
print('阿姨好...') #输出的结果:表白... #输出的结果:阿姨好...
3.语法三:if的嵌套
if 条件1:
if 条件2:
代码1
代码2
代码3
示例:#既然在以上的基础上都表白了,那么肯定有人会表白成功或者失败的。因此,
age=18
sex='female'
is_pritty=True
is_success=True #是否成功
if age>16 and age<18 and is_pritty and sex='female':
print('表白....')
if is_success:
print('在一起....')
esle:
print('谈什么恋爱啊,一点意思都没有!')
else:
print('阿姨好...') #输出结果:表白....
在一起....
4.语法四:
if 条件1:
代码1
代码2
代码3
elif 条件2:
代码1
代码2
代码3
else:
代码1
代码2
代码3
示例:
score=input('>>>>>>')
score=(int)score
if score>=90:
print('优秀')
elif score>=80:
print('良好')
elif score>=70:
print('普通')
else:
print('很差')
二、while循环
基本语法格式:
语法:
while 条件:
代码1
代码2
代码3
案例:#验证用户登录
while True:
name=input('Please input you name:')
pwd=input('Please input you password:')
if name='wanglei' and pwd ='123':
print('Login success!')
else:
print('you name or password error!')
1.结束while循环的两种方式:
1.1通过修改条件为False,例如:
tag=True
while tag:
name=input('Please input you name:')
pwd=input('Please input you password:')
if name='wanglei' and pwd='123':
print('Login success!')
tag=False
else:
print('you name or password error!')
1.2通过while+break,例如:
while tag:
name=input('Please input you name:')
pwd=input('Please input you password:')
if name='wanglei' and pwd='123':
print('Login success!')
break
else:
print('you name or password error!')
2.while嵌套
案例:#在登录到账户的基础上,实现用户多0(退出),1(取款),2(转账),3(存款)的操作
tag=True
while tag:
name=input('Please input you name:')
pwd=input('Please input you password:')
if name='wnaglei' and pwd='123':
print('Login success!')
while tag:
choice=input('Please enter you choice:')
if choice == '0':
tag=False
elif choice == '1':
print('取款')
elif choice == '2':
print('转账')
elif choice == '3':
print('存款')
else:
print('你输入的指令有误,请重新输入!')
else:
print('you name or password error!')
三、for循环
for循环的强大之处在于循环取值。
案例1:#对于列表,依次取出L=[1,2,3,4,5]的值,并输出在控制台上。
L=[1,2,3,4,5]
for x in L:
print(x) #得到的结果就是1,2,3,4,5
案例2:对于字典......
dic={'name':'wanglei','age':18,'sex':'male'}
for x in dic:
print(x) #输出的结果为:name,age,sex