1、模拟网站确保用户名是否重复的方式,无视大小写,用到函数lower()
1 #检查用户名是否重复 2 current_users=['admin','alex','lebran','kaobi','James'] 3 lower_current_users=[current_user.lower() for current_user in current_users]#列表元素变为小写 4 new_users=['Admin','alex','haden','Holliday','JAMES'] 5 for new_user in new_users: 6 if new_user.lower() in lower_current_users: 7 print('Input another username.') 8 else: 9 print('You can use it.')
2、if...and...条件测试
user="charlie" passwd="xjl1991" username=input("username:") password=input("password:") if user==username and passwd==password: print("欢迎登陆") else: print("用户名或密码错误")
3、列表:先将列表清空,再检查列表是否为空
1 list=['admin','alex','lebran','kaobi','james'] 2 list=[] #将列表清空 3 if list: 4 print('h') 5 else: 6 print('We need to find some users!')
4、if-elif语句
# elif测试每个年龄段的收费情况 age=int(input('Please input your name:')) if age < 4: price=0 elif age < 18: price=5 elif age < 65: price=10 else: price=5 print('Your admission cost is %s.'%price)#你的入场费是
5、三元运算,也叫三目运算,就是把简单的if--else--语句,合并成一句
#如果if后面的条件成立,就返回前面的值,不成立,返回后面的值 name = 'alex' if 1==1 else 'sb'
6、练习题:猜年龄游戏
age=26 counter=0 for i in range(10): print("--counter:",counter) if counter <3: guess_number=int(input("your guess number:")) if guess_number==age: print("Congretulations,you got it!") break elif guess_number>age: print("Think smaller.") else: print("Think bigger.") else: continue_confirm=input("do you want to try continue:") if continue_confirm=="y": counter=0 continue else: break counter=counter+1