print( 'Hello' == 'Hello' )
print( 'Hello' == 'hello' )
print( 'Hello' != 'Hello' )
print( 'Hello' != 'hello' )
print( 'Hello'.lower() == 'hello' )
print( 1 == 1 )
print( 1 == 2 )
print( 1 != 1 )
print( 1 != 2 )
print( 1 > 1 )
print( 1 <= 1 )
print( 1 < 2 )
print( 1 >= 2 )
print( 1+1 < 4 and 5-1 <= 4 )
print( 1 == 1 and 1 == 2 )
print( 1 == 1 or 1 == 2 )
print( 1+1 > 4 and 5-1 != 4 )
li = [ 1, 2, 3 ]
print( 1 in li )
print( 4 in li )
print( 4 not in li )
True
False
False
True
True
True
False
False
True
False
True
True
False
True
False
True
False
True
False
True
5-6 人生的不同阶段 :设置变量 age 的值,再编写一个 if-elif-else 结构,根据 age 的值判断处于人生的哪个阶段。
f. 如果一个人的年龄超过 65 (含)岁,就打印一条消息,指出他是老年人。
ages = [ 1, 2, 4, 13, 20, 65 ]
for age in ages:
if age < 2:
print('He is a baby.')
elif age < 4:
print('He is learing to walk.')
elif age < 13:
print('He is a child.')
elif age < 20:
print('He is a teenager.')
elif age < 65:
print('He is a adult.')
else:
print('He is a old man.')
He is a baby.
He is learing to walk.
He is a child.
He is a teenager.
He is a adult.
He is a old man.
5-7 喜欢的水果 :创建一个列表,其中包含你喜欢的水果,再编写一系列独立的 if 语句,检查列表中是否包含特定的水果。
favorite_fruits = [ 'bananas', 'apples', 'pears' ]
if 'bananas' in favorite_fruits:
print('You really like bananas!')
if 'apples' in favorite_fruits:
print('You really like apples!')
if 'pears' in favorite_fruits:
print('You really like pears!')
if 'grapes' in favorite_fruits:
print('You really like grapes!')
if 'watermelons' in favorite_fruits:
print('You really like watermelons!')
You really like bananas!
You really like apples!
You really like pears!
5-8 以特殊方式跟管理员打招呼 :创建一个至少包含 5 个用户名的列表,且其中一个用户名为 'admin' 。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息。
users = [ 'admin', 'cindy', 'candy', 'dancy', 'dandy' ]
for user in users:
if user == 'admin':
print('Hello admin, would you like to see a status report?')
else:
print('Hello {}, thank you for logging in again'.format(user))
Hello admin, would you like to see a status report?
Hello cindy, thank you for logging in again
Hello candy, thank you for logging in again
Hello dancy, thank you for logging in again
Hello dandy, thank you for logging in again
5-11 序数 :序数表示位置,如 1st 和 2nd 。大多数序数都以 th 结尾,只有 1 、 2 和 3 例外。
nums = list(range(1,10))
for num in nums:
if num == 1:
print( str(num) + 'st' )
elif num == 2:
print( str(num) + 'nd' )
elif num == 3:
print( str(num) + 'rd' )
else:
print( str(num) + 'th' )
1st
2nd
3rd
4th
5th
6th
7th
8th
9th