第五章 if语句【Python从入门到实践】

cars=['bmw','audi','toyoto','subarn']
for car in cars:
    if car=='bmw':
        print(car.upper())
    else:
        print(car.title())

# ==含义:条件测试,检查是否等于,而不是赋值

car='bmw'
a=car=='bmw'
print(a)
b=car=='bmw'
print(b)
c=car=='Bmw'   #区分大小写
print(c)

#当不想区分大小写时:都转换成小写
'''
 lower()方法
语法格式 : str.lower()
作用:将字符串中的大写字母转换为小写字母
演示代码:>>> str1 = "Hello World!"
>>> str1.lower()
'hello world! 
'''

car='Audi'
d=car.lower()=='audi'
print(d)
print(car)   #原来的car没有变

#if不等于
requested_topping='mushroom'

if requested_topping != 'anchvoies':
    print('Hold the anchvoies!')

#对数字的判断
age=18
g=age==18
print(g)

answer=15
if answer !=42:
    print('That is not correct answer.Please try again!')

#对数字判断的特有符号
age=18
h=age==19
i=age<19
j=age>21
k=age>=18
l=age<=19
print(h,i,j,k,l)

#且and、或or
age_0=22
age_1=18
print(age_0>=21 and age_1>=21)
print(age_0>=21 or age_1>=21)

# in:判断是否存在于列表中
a=[0,1,2,3]
print(1 in a)
print(10 in a)

a=[2,4,6,8]
if 1 not in a:
    print("NO,I cannot find this")

#if——else:
#例子1:投票
age=19
if age>=18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry,You are too young to vote!")
    print("Please register to vote as soon as you turn 18!")

#例子2:门票的判断
age=12
if age<=4:
    print("You admision cost is $0" )
elif age<8:
    print("You admision cost is $5")
else:
    print("You admision cost is $10")

print("\n简化版")
age=12
if age<=4:
    price = 0
elif age<8:
    price = 5
else:
    price = 10
#字符串于数字不是用一个类型:将数字转换成字符串
print("You admision cost is $"+str(price) +".")

#多个elif:如果上一个为真,之后elif不会执行,elif=else if
print("\n多个elif:")
age=60
if age<=4:
    price = 0
elif age<8:
    price = 5
elif age < 65:
    price = 10
else:
    price = 20
print("You admision cost is $"+str(price) +".")

#省略else
print("\n都用elif,不用else的情况:")
age=60
if age <= 4:
    price = 0
elif age < 8:
    price = 5
elif age < 65:
    price = 10
elif age >= 65:
    price = 5
print("You admision cost is $"+str(price) +".")

#检查元素
requested_toppings=['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    print("Adding " +  requested_topping  + ".")
print("\nFinished making your pizza!")

#for + if 没有青椒了
requested_toppings=['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
    if requested_topping =='green peppers':
        print("Sorry,we are out of  have green peppers right now!" )
    else:
        print("Adding " +requested_topping+ ".")
print("\nFinished making your pizza!")

#没点额外的配料,当列表为空时,判断值默认为false
requested_toppings=[]
if requested_toppings :  #当列表不为空时
    for requested_topping in requested_toppings:
        if requested_topping =='green peppers':
            print("Sorry,we are out of  have green peppers right now!" )
        else:
            print("Adding " +requested_topping+ ".")
    print("\nFinished making your pizza!")
else:
    print("\nAre you sure you want a plain pizza!")

#多个列表
available_toppings=['mushrooms','green peppers','olives','pepper','extra cheese']
requested_toppings=['mushrooms','french','extra cheese']
for requested_topping in requested_toppings:
        if requested_topping in available_toppings:
            print("Adding " + requested_topping + ".")
        else:
            print("Sorry,we are out of  have "+requested_topping+ "." )
print("\nFinished making your pizza!")


# 5-1 条件测试 :编写条件测试;将其预测和实际结果都打印。
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')

fruit='apple'
print("Is fruit== 'banana'? I predict False.")
print(fruit == 'subaru')
print("\nIs fruit == 'orange'? I predict False.")
print(fruit == 'audi')
print("\nIs fruit == 'apple'? I predict True.")
print(fruit== 'apple')

# 5-2 更多的条件测试:可再编写一些测试,并将它们加入到 conditional_tests.py中。
# 对各种测试,至少编写一个结果为True和False的测试。 检查两个字符串相等和不等,使用函数lower() 的测试。
# 检查两个数字相等、不等、大于、小于、大于等于和小于等于,使用关键字and 和or 的测试。
# 测试特定的值是否包含在列表中。

string_1='Freya Qin'
string_2='freya qin'
string_3='Freya Qin'

#检查两个字符串相等和不等
print("\nstring_1==string_2:")
print(string_1==string_2)
print("\nstring_1==string_3:")
print(string_1==string_3)

print("\nstring_1.lower()==string_2.lower():")
print(string_1.lower()==string_2.lower())
print("\nstring_1.lower()==string_3.lower():")
print(string_1.lower()==string_3.lower())

#检查2个数字
age_kim=32
age_Tom=20
print("\nage_kim==age_Tom:")
print(age_kim == age_Tom)
print("\nage_kim!=age_Tom:")
print(age_kim != age_Tom)
print("\nage_kim > age_Tom:")
print(age_kim > age_Tom)
print("\nage_kim > age_Tom:")
print(age_kim < age_Tom)

print("and 和or 的测试:")
print(age_kim == age_Tom and age_kim != age_Tom)  #假 and 真--->假
print(age_kim == age_Tom or age_kim != age_Tom)   #假  or 真--->真


# 测试特定的值是否包含在列表中。
aL66=[1,2,3,4]
#不允许使用小写的L,命名规则,在有些编译器中小写的L和1是分不开的
print('Is 1 in aL66?')
print(1 in aL66)
print('Is 5 in aL66?')
print(5 in aL66)

#5-3 外星人颜色#1:刚射杀一外星人,创建alien_color变量,将其设置为'green'、'yellow'或'red'
# 编写一条if语句,检查外星人是否是绿色的;如果是,打印一条消息,指出玩家获得了5个点。
# 编写这个程序的两个版本,在一个版本中上述测试通过了,而 在另一个版本中未通过(未通过测试时没有输出)。
#版本1
alien_color='green'
if(alien_color=='green'):
    print("Player won 5 points!")
#版本2
alien_color='yellow'
if(alien_color=='green'):
    print("Player won 5 points!")

#5-4 外星人颜色#2:像练习5-3那样设置外星人的颜色,
# 编写if-else 结构:如果外星人是绿色的,打印玩家因射杀该外星人获得了5个点。如果不是绿色的,打印玩家获得了10 个点。
# 编写这个程序的两个版本,在一个版本中执行if代码块,而在另一个版本中执行else 代码块。
alien_color='yellow'
print("版本1,执行else语句:")
if(alien_color=='green'):
    print("Player won 5 points!")
else:
    print("Player won 10 points!")

print("版本2,执行if语句:")
if(alien_color !='green'):
    print("Player won 10 points!")
else:
    print("Player won 5 points!")

# 5-5 外星人颜色#3 :将5-4中的if-else结构改为if-elif-else 结构。
# 如果是绿色,指出玩家获得了5个点。如果是黄色,指出玩家获得了10个 点。如果外星人是红色的,指出玩家获得了15个 点。
# 编写这个程序的三个版本,它们分别在外星人为绿色、黄色和 红色时打印一条消息。
alien_color='yellow'
print("版本1,外星人为黄色:")
if alien_color=='green':
    print("Player won 5 points!")
elif alien_color=='yellow':
    print("Player won 10 points!")
else:
    print("Player won 15 points!")

alien_color='green'
print("版本1,外星人为绿色:")
if alien_color=='green':
    print("Player won 5 points!")
elif alien_color=='yellow':
    print("Player won 10 points!")
else:
    print("Player won 15 points!")

alien_color='yellow'
print("版本2,外星人为黄色:")
if alien_color=='green':
    print("Player won 5 points!")
elif alien_color=='yellow':
    print("Player won 10 points!")
else:
    print("Player won 15 points!")

alien_color='red'
print("版本3,外星人为红色:")
if alien_color=='green':
    print("Player won 5 points!")
elif alien_color=='yellow':
    print("Player won 10 points!")
else:
    print("Player won 15 points!")


#5-6 人生的不同阶段:设置变量age的值,编写f-elif- else 结构,根据age的值判断处于人生的哪个阶段。
# 如果一个人的年龄小于2岁,他是婴儿。如果一个人的年龄为2(含)~4岁,他正蹒跚学步。
# 如果一个人的年龄为4(含)~13岁,他是儿童。 如果一个人的年龄为13(含)~20岁,他是青少年。
# 如果一个人的年龄为20(含)~65岁,他是成年人。 如果一个人的年龄超过65(含)岁,他是老年人。
age=23
if age<2:
    print("他是婴儿" )
elif age<4:
    print("他正蹒跚学步")
elif age<13:
    print("他是儿童")
elif age<20:
    print("他是青少年")
elif age<65:
    print("他是成年人")
else:
    print("他是老年人")

#5-7 喜欢的水果:创建一个列表,其中包含你喜欢的水果,
# 再编写一系列独立的if语句,检查列表中是否包含特定的水果。将该列表命名为favorite_fruits ,并在其中包含三种水果。
# 编写5条if 语句,每条都检查某种水果是否包含在列表中,如 果包含在列表中,就打印一条消息,如“You really like bananas!”。
fruits=['Apples', 'peaches', 'bananas', 'oranges']
favorite_fruits=['Apples', 'bananas', 'oranges']

fruit='oranges'
if fruit in fruits:
    print("包含这种水果" )
else:
    print("不包含这种水果")

for fruit in fruits:
    if fruit in favorite_fruits:
        print("You really like "+fruit+" !")
    else:
        print("You are not really like "+fruit+" !")

#5-8 以特殊方式跟管理员打招呼 :创建包含5个用户名的列表,且其中一个用户名为'admin'
#在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息。
#如果用户名为'admin' ,就打印一条特殊的问候消息。 否则,打印一条普通的问候消息。
user_names = ['Kim', 'Tom', 'Amy', 'Freya', 'admin']
for user_name in user_names:
    if user_name == 'admin':
        print("Hello admin, would you like to see a status report?")
    else:
        print("Hello " + user_name + ", thank you for logging in again," + '!')

#5-9 处理没有用户的情形 :在为5-8中,添加一条if语句,检查用户名列表是否为空。
#如果为空,就打印消息“We need to find some users!”。删除列表中的所有用户名,确定将打印正确的消息。
user_names = []
if user_names:
    for user_name in user_names:
        if user_name == 'admin':
            print("Hello admin, would you like to see a status report?")
        else:
             print("Hello " + user_name + ", thank you for logging in again" + '!')
else:
    print("We need to find some users!")

#5-10 检查用户名:模拟网站确保每位用户的用户名都独一无二的方式。
#创建一个至少包含5个用户名的列表current_users 。 再创建一个包含5个用户名的列表,将其命名为new_users ,并确保其中有一两个用户名也包含在列表current_users 中。
#遍历列表new_users ,对于其中的每个用户名,都检查它是否已被使用。
# 被使用,打印需要输入别的用户名;否则,打印用户名未被使用。 确保比较时不区分大小写;换句话说,如果用户名'John' 已被使用,应拒绝用户名'JOHN'。

#写法1:指建立current_userss_lower列表,存储相应的小写名字。将new_users在for循环时候,单个的取了出来,再在if中使用.lower() 将各个变量转换成小写
print("#写法1:")
current_users=['Kim', 'Tom', 'Amy', 'Freya', 'admin']
new_users= ['Kim', 'Tom','Henry','jone','Crystal']
current_users_lower=[]

#转换成小写原始名单全部
for current_user in current_users:
    name_lower=current_user.lower()
    current_users_lower.append(name_lower)
print(current_users_lower)

#检查新旧名单是否重复
for new_users in new_users:
    if new_users.lower() in current_users_lower:
        print("Please put another name!")
    else:
        print("This name is not use!")

#写法2:分别建立new_userss_lower、current_userss_lower列表,存储相应的小写名字。用新的2个列表进行比较
print("写法2:")
current_users=['Kim', 'Tom', 'Amy', 'Freya', 'admin']
new_users= ['Kim', 'Tom','Henry','jone','Crystal']
current_users_lower=[]
new_users_lower=[]

#转换成小写原始名单全部
for current_user in current_users:
    name_lower=current_user.lower()
    current_users_lower.append(name_lower)
print(current_users_lower)

for new_user in new_users:
    name_lower=new_user.lower()
    new_users_lower.append(name_lower)
print(new_users_lower)

#检查新旧名单是否重复
for new_users_low in new_users_lower:
    if new_users_low in current_users_lower:
        print("Please put another name!")
    else:
        print("This name is not use!")

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

print("写法2:")
numbers=range(1,10)
for number in numbers:
    if number==1:
        print(number.__str__()+"st")
    elif number==2:
        print(number.__str__()+"nd")
    elif number==3:
        print(number.__str__()+"rd")
    else:
        print(number.__str__()+"th")
BMW
Audi
Toyoto
Subarn
True
True
False
True
Audi
Hold the anchvoies!
True
That is not correct answer.Please try again!
False True False True True
False
True
True
False
NO,I cannot find this
You are old enough to vote!
Have you registered to vote yet?
You admision cost is $10

简化版
You admision cost is $10.

多个elif:
You admision cost is $10.

都用elif,不用else的情况:
You admision cost is $10.
Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza!
Adding mushrooms.
Sorry,we are out of  have green peppers right now!
Adding extra cheese.

Finished making your pizza!

Are you sure you want a plain pizza!
Adding mushrooms.
Sorry,we are out of  have french.
Adding extra cheese.

Finished making your pizza!
Is car == 'subaru'? I predict True.
True

Is car == 'audi'? I predict False.
False
Is fruit== 'banana'? I predict False.
False

Is fruit == 'orange'? I predict False.
False

Is fruit == 'apple'? I predict True.
True

string_1==string_2:
False

string_1==string_3:
True

string_1.lower()==string_2.lower():
True

string_1.lower()==string_3.lower():
True

age_kim==age_Tom:
False

age_kim!=age_Tom:
True

age_kim > age_Tom:
True

age_kim > age_Tom:
False
and 和or 的测试:
False
True
Is 1 in aL66?
True
Is 5 in aL66?
False
Player won 5 points!
版本1,执行else语句:
Player won 10 points!
版本2,执行if语句:
Player won 10 points!
版本1,外星人为黄色:
Player won 10 points!
版本1,外星人为绿色:
Player won 5 points!
版本2,外星人为黄色:
Player won 10 points!
版本3,外星人为红色:
Player won 15 points!
他是成年人
包含这种水果
You really like Apples !
You are not really like peaches !
You really like bananas !
You really like oranges !
Hello Kim, thank you for logging in again,!
Hello Tom, thank you for logging in again,!
Hello Amy, thank you for logging in again,!
Hello Freya, thank you for logging in again,!
Hello admin, would you like to see a status report?
We need to find some users!
#写法1:
['kim', 'tom', 'amy', 'freya', 'admin']
Please put another name!
Please put another name!
This name is not use!
This name is not use!
This name is not use!
写法2:
['kim', 'tom', 'amy', 'freya', 'admin']
['kim', 'tom', 'henry', 'jone', 'crystal']
Please put another name!
Please put another name!
This name is not use!
This name is not use!
This name is not use!
写法1:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
写法2:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值