标签:today break 接收 lis NPU span als 条件 username
一、if判断
模拟人对某些事物的判断并作出不同的决策的能力。计算机由于要像人一样的去工作,那么它必须也要具备判断事物对错的能力,从而作出不同的响应。实际中的例子,面前走过一个妹纸,你会想好不好看,要不要超过去看看正脸等等。程序中比如ATM取款机,需要接收你输入的用户名和密码来判断你是否是合法用户等等。
语法: if 条件:
代码1
代码2
代码3
...
else:
代码1
代码2
代码3
...
if...else...表示代码成立会怎么样,else表示不成立会怎么样。
cls = ‘human‘ gender = ‘female‘ age = 18 if cls == ‘human‘and ‘gender‘ == ‘female‘ and age >16 and age < 22: print(‘上去表白‘) else: print(‘打扰了’‘)
if...elif...
if 条件1:
代码1
代码2
代码3
...
elif 条件2:
代码1
代码2
代码3
...
elif 条件3:
代码1
代码2
代码3
...
...
else:
代码1
代码2
代码3
...
if...elif...else表示if条件1成立干什么,elif条件2成立干什么,elif条件3成立干什么,elif...否则干什么。
if...elif...else
cls = ‘human‘
gender = ‘female‘
age = 28
if cls == ‘human‘ and gender == ‘female‘ and age > 16 and age < 22:
print(‘开始表白‘)
elif cls == ‘human‘ and gender == ‘female‘ and age > 22 and age < 30:
print(‘考虑下‘)
else:
print(‘阿姨好‘)
应用实例:#模拟注册登录
user_name = ‘zzj‘
user_pwd = ‘123‘
inp_name = input(‘please input your name>>>:‘)
inp_pwd = input(‘please input your password>>>:‘)
if user_name == inp_name and userpwd == inp_pwd:
print(‘登陆成功!‘)
else :
print(‘登录错误!‘)
#一周安排
print(‘‘‘必须输入其中一种:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday Sunday
‘‘‘)
today=input(‘>>: ‘)
if today == ‘Monday‘ or today == ‘Tuesday‘ or today == ‘Wednesday‘ or today == ‘Thursday‘ or today == ‘Friday‘:
print(‘上班‘)
elif today == ‘Saturday‘ or today == ‘Sunday‘:
print(‘出去浪‘)
else:
print(‘‘‘必须输入其中一种:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
‘‘‘)
if 的嵌套
cls = ‘human‘
gender = ‘female‘
age = 18
is_success = False
if cls == ‘human‘ and gender == ‘female‘ and age > 16 and age < 22:
print(‘开始表白‘)
if is_success:
print(‘那我们一起走吧...‘)
else:
print(‘我逗你玩呢‘)
else:
print(‘阿姨好‘)
二、while循环
实现ATM的输入密码重新输入的功能
user_db = ‘nick‘
pwd_db = ‘123’
while True:
inp_user = input(‘username:‘)
inp_pwd = input(‘password:‘)
if inp_user == user_db and pwd_db == inp_pwd:
print(‘login successful‘)
else:
print(‘username or password error‘)
while + break
break 的意思就是终止掉当前层的循环,执行其他代码。
#break 语句演示
while True :
print(‘1‘)
print(‘2‘)
print(‘3‘)
break
例:
user_db = ‘jason‘
pwd_db = ‘123‘
while True:
inp_user = input(‘username: ‘)
inp_pwd = input(‘password: ‘)
if inp_user == user_db and pwd_db == inp_pwd:
print(‘login successful‘)
break
else:
print(‘username or password error‘)
print(‘退出了while循环‘)
#while + else
n = 1
while n < 3:
if n == 2:
print(n)
n +=1
else:
ptint(‘else会在while没有break时才会执行else中的代码‘)
三、for 循环
1. for i in range(1,10): #range顾头不顾尾
print(i)
2.name_list = [‘jason‘,‘zzj‘,‘angela‘]
for i in range(len(name_list)):
prtint(i,name_list[i])
3.for + break 跳出本层循环
name = [‘jason‘,‘zzj‘,‘angela‘]
for i in name:
if i == ‘zzj‘:
break
print(i)
4.for + continue
name = [‘jason‘,‘zzj‘,‘angela‘]
for i in name:
if i == ‘zzj‘:
continue
print(i)
5.for循环练习题
打印九九乘法口诀表
for i in range(1,10): for j in range(1,i+1): print(‘%s*%s=%s‘%(i,j,i*j),end=‘ ‘) print()
标签:today break 接收 lis NPU span als 条件 username
原文地址:https://www.cnblogs.com/spencerzhu/p/11122876.html