Table of contents
1. Condition test
1.1 Detect multiple conditions (and / or)
keywords used
- and : both conditions are true
- or : at least one condition is met
example
age_o=20
age_1=22
print(age_o>=21 and age_1<=22,age_o>=21 or age_1<=22)
1.2 Check if a specific value is contained in a list
keywords used
- Determine if a specific value is in a column: in
- Judging that a specific value is not in the list: not in
example
color = ['green','red','blue','yellow','pink']
if 'pink' in color:
print('yes!')
if 'dark' not in color:
print('sorry!')
1.3 if statement structure
- single if statement
- if-else statement
- if-elif-else statement
Two, if statement processing list
2.1 Determine whether the list is empty
Three ways to judge:
- Directly use the conditional expression if + list, if the list is not empty, the if list expression returns true, otherwise returns false
- Check whether the list == []
- Judging by column length
list_1 = []
if list_1:
print('This is not a empty list!')
else:
print('This is a empty list!')
if list_1==[]:
print('This is a empty list!')
else:
print('This is not a empty list!')
if len(list_1)==0:
print('This is a empty list!')
else:
print('This is not a empty list!'
2.2 Exercises
the code
print('5-8')
usernames = ['root','admin','jack','peter','diane']
for username in usernames:
if username == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello Jaden, thank you for logging in again.')
print('5-9')
usernames.clear()
if usernames:
for username in usernames:
if username == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello Jaden, thank you for logging in again.')
else:
print('We need to find some users!')
print('5-10')
current_users = ['jack','peter','will','admin','diane']
new_users = ['mary','peter','will','lili','frank']
for new_user in new_users:
for current_user in current_users:
if new_user == current_user:
print(f'Dear {
new_user.title()}, you need to change a username!')
break;
else:
print(f'Dear {
new_user.title()}, this username is ready to use!')
else:
print('All the usernames are finished checked!')
print('5-11')
numbers = list(range(1,10))
for number in numbers:
if number==1:
print('first')
elif number == 2:
print('second')
elif number==3:
print('third')
else:
print(f'{
number}th')
output
Note: How to clear the list
- Use the clear method
- Let the list == [] directly
- Use the del statement: del [:], without specifying the start and end indexes, delete all elements and clear
the list