Python-5.2-if语句-练习

检查列表是否有元素apple
#练习1
#练习1
a = ['apple','banbna']
b = 'apple'
if b in a:
    print("I like " + b + '.')
else:
    print("None")

I like apple.

遍历变量a中列表的元素
  • 如果元素为apple则以首字母大写打印出,其余全部大写
#练习2
a = ['apple','banana','pear']
for b in a :
    if b == 'apple':
        print(b.title())
    else :
        print(b.upper())

Apple
BANANA
PEAR

遍历元素
  • 检查有哪些元素在列表中
#练习3
alien_colors = ['green','yellow','red']
for alien_color in alien_colors:
    print(alien_color.title() + " in it" + '.')

Green in it.
Yellow in it.
Red in it.

序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1,2和3例外。
  • (1)在一个列表中存储数字1-9
  • (2)遍历这个列表
  • (3)在循环中使用一个if-elif-else结构,以打印每个数字对应的序数。输出内容应为1st、2nd、3rd、4th、5th、6th、7th、8th和9th,但每一序数都一行
#练习4
numbers = [number**1 for number in range(1,10)]
for number in numbers:
    if number == 1:
        print('1st')
    elif number == 2 :
        print('2nd')
    elif number == 3 :
        print(str(number)+"rd")
    else :
        print(str(number)+"th")

1st
2nd
3rd
4th
5th
6th
7th
8th
9th

遍历列表new_users
  • 对于其中的每个用户名,都检查它是否已被使用
#练习5
current_users = ['admin','nike','jake','jack','uni']
new_users = ['jack','Nike','apple','dog','flower']
for new_user in new_users:
    if new_user in current_users:
        print(new_user + " in")
    else :
        print(new_user + " out")
确保比较时不区分大小写
  • 如果用户名’John‘已被使用,应拒绝用户名’JOHN‘
#练习6
users = ['jack','jOb','apple']
new_users = ['jack','Job','bbPple']
for user in users:
    user = user.lower()
    for new_user in new_users :
        new_user = new_user.lower()
        if new_user in user :
            print(new_user + " was used")

jack was used
job was used

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值