Python编程:从入门到实践 第5章

357 阅读8分钟

Python编程:从入门到实践 第5章课后习题

5-2 题有不懂的。

5-1 条件测试:编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来。你编写的代码应类似于下面这样:

car = 'subaru' 
print("Is car == 'subaru'? I predict True.") 
print(car == 'subaru') 
print("\nIs car == 'audi'? I predict False.") 
print(car == 'audi') 
  • 详细研究实际结果,直到你明白了它为何为True 或False 。
  • 创建至少10个测试,且其中结果分别为True 和False 的测试都至少有5个。

5-2 更多的条件测试:你并非只能创建10个测试。如果你想尝试做更多的比较,可再编写一些测试,并将它们加入到conditional_tests.py中。对于下面列出的各种测试,至少编写一个结果为True和False的测试。

  • 检查两个字符串相等和不等。
  • 使用函数lower() 的测试。
  • 检查两个数字相等、不等、大于、小于、大于等于和小于等于。
phone ='iPhone'
print("Is phone =='iPhone'? I predict True") #字符串完全一样
print(phone == 'iPhone')

print("Is phone =='iphone'? I predict False") #大小写不一样
print(phone == 'iphone')

print("Is phone !='iphone'? I predict True") #大小写不一样但不等于所以true
print(phone != 'iphone')

print("Is phone.lower() ='iphone'? I predict True") 
print(phone.lower() == 'iphone')

num1, num2, num3 = 10, 20, 20

if num1 > num2:
    print('num1 is greater than num2')
else:
    print('num1 is less than num2')

print('num2 greater than num3?', num2>num3)
print('num2 equals num3?', num2==num3, '\nnum2 greater or equal to num3?', num2>=num3)
  • 使用关键字and和or的测试。
num1, num2, num3 = 10, 20, 20

print(num1 >1 and num2 >30) #False
print(num1>1 or num2>30) #True

  • 测试特定的值是否包含在列表中。
  • 测试特定的值是否未包含在列表中。
num = list(range(1,11,1))
print(100 in num)
print(100 not in num)

但是之前尝试了一个这个发现有错误:

brand = 'honda'
car_brands = ['honda','toyota','vw','gm','ford']
motor_brands = ['honda', 'ducati','kawasaki','harley']


if brand in car_brands not in motor_brands:
    print(brand, 'make cars')
elif brand in motor_brands not in car_brands:
    print(brand, 'make motors')
elif brand in car_brands and motor_brands:
    print(brand, 'make both')
else:
    print(brand, 'error')

#为什么honda归到cars里面取了?

打印结果是honda make cars。为什么honda直接归入cars而不是如第一句和第三句说的那样打印make both?

5-3 外星人颜色#1:假设在游戏中刚射杀了一个外星人,请创建一个名为alien_color 的变量,并将其设置为'green' 、'yellow' 或'red' 。

  • 编写一条if 语句,检查外星人是否是绿色的;如果是,就打印一条消息,指出玩家获得了5个点。
  • 编写这个程序的两个版本,在一个版本中上述测试通过了,而在另一个版本中未通过(未通过测试时没有输出)。
alien_color = 'green'
if alien_color == 'green':
    print('5 pts')
    
if alien_color == 'yellow':
    print('5pts') #无输出

双等于号,单等于号报错。

5-4 外星人颜色#2:像练习5-3那样设置外星人的颜色,并编写一个if-else 结构。

  • 如果外星人是绿色的,就打印一条消息,指出玩家因射杀该外星人获得了5个点。
  • 如果外星人不是绿色的,就打印一条消息,指出玩家获得了10个点。
  • 编写这个程序的两个版本,在一个版本中执行if 代码块,而在另一个版本中执行else 代码块。
alien_color = 'green'
if alien_color == 'green':
    print('5 pts') 
else:
    print('10 pts')

5-5 外星人颜色#3:将练习5-4中的if-else 结构改为if-elif-else 结构。

  • 如果外星人是绿色的,就打印一条消息,指出玩家获得了5个点。
  • 如果外星人是黄色的,就打印一条消息,指出玩家获得了10个点。
  • 如果外星人是红色的,就打印一条消息,指出玩家获得了15个点。
  • 编写这个程序的三个版本,它们分别在外星人为绿色、黄色和红色时打印一条消息。
alien_color = 'green'
if alien_color == 'green':
    print('5 pts') 
elif alien_color == 'yellow':
    print('10 pts')
else:
    print('15 pts')

5-6 人生的不同阶段:设置变量age 的值,再编写一个if-elif-else 结构,根据age 的值判断处于人生的哪个阶段。

  • 如果一个人的年龄小于2岁,就打印一条消息,指出他是婴儿。
  • 如果一个人的年龄为2(含)~4岁,就打印一条消息,指出他正蹒跚学步。
  • 如果一个人的年龄为4(含)~13岁,就打印一条消息,指出他是儿童。
  • 如果一个人的年龄为13(含)~20岁,就打印一条消息,指出他是青少年。
  • 如果一个人的年龄为20(含)~65岁,就打印一条消息,指出他是成年人。
  • 如果一个人的年龄超过65(含)岁,就打印一条消息,指出他是老年人。
age= 2

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!”。
my_fruits = ['peach','apple','kiwi','mango']
favorite_fruits = ['banana','pineapple','peach']

for favorite_fruit in favorite_fruits:
    if favorite_fruit in my_fruits:
        print('I love', favorite_fruit+'.')
    else:
        print("I don't like", favorite_fruit+'.' )

5-8 以特殊方式跟管理员打招呼:创建一个至少包含5个用户名的列表,且其中一个用户名为'admin' 。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息。

  • 如果用户名为'admin',就打印一条特殊的问候消息,如“Hello admin, would you like to see a status report?”。
  • 否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
ids = ['zhao','admin','qian','sun','li']

for id in ids:
    if id == 'admin':
        print('Hello admin, would you like to see a status report?')
    else:
        print('Hello', id+', thank you for logging again.')

5-9 处理没有用户的情形:在为完成练习5-8编写的程序中,添加一条if 语句,检查用户名列表是否为空。

  • 如果为空,就打印消息“We need to find some users!”。
  • 删除列表中的所有用户名,确定将打印正确的消息。
ids = []

if ids:
    for id in ids: #Python将在列表至少包含一个元素时返回True ,并在列表为空时返回False
        if id == 'admin':
            print('Hello admin, would you like to see a status report?')
        else:
            print('Hello', id+', thank you for logging again.')
else:
    print('user required.')

5-10 检查用户名:按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。

  • 创建一个至少包含5个用户名的列表,并将其命名为current_users。
  • 再创建一个包含5个用户名的列表,将其命名为new_users,并确保其中有一两个用户名也包含在列表current_users中。
  • 遍历列表new_users,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。
  • 确保比较时不区分大消息;换句话说,如果用户名'John'已被使用,应拒绝用户名'JOHN'。
current_users = ['zhao','Qian','SUN','lI','zhou']
new_users = ['wu','Zheng','Zhao','qIAN','SUN','ZHOU']

current_users_lowers = [x.lower() for x in current_users]
new_users_lowers = [x.lower() for x in new_users]

for new_users_lower in new_users_lowers:
    if new_users_lower in current_users_lowers:
        print(new_users_lower.title(), 'new user name required')
    elif new_users_lower not in current_users_lowers:
        print(new_users_lower.title(),'bingo')

这是简单粗暴的办法。在百度上看到别人用了一个略优雅的办法:

current_users = ['zhao','Qian','SUN','lI','zhou']
new_users = ['wu','Zheng','Zhao','qIAN','SUN','ZHOU']

for new_user in new_users:
    avi = True
    for current_user in current_users:
        if new_user.lower() == current_user.lower():
            avi = False
    if avi == True:
        print(new_user.title(), 'available')
    elif avi == False:
        print(new_user.title(), 'new name required')

5-11 序数:序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。

  • 在一个列表中存储数字1~9。
  • 遍历这个列表。
  • 在循环中使用一个if-elif-else 结构,以打印每个数字对应的序数。输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每个序数都独占一行。
numbers = list(range(1,10,1))

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')

这个代码number后面要跟==,如果是一个=,报错。同时打印的时候要str(),string不能直接加数字,否则报错,但不是+而是,则可以,但逗号会给空格。

如果不想打印的时候加str(),则要先将list变成string。

numbers = str(list(range(1,10,1)))
则输出:
Out[41]: '[1, 2, 3, 4, 5, 6, 7, 8, 9]'

这是一个含逗号、空格、方括号的27个元素的string,不对。

numbers = list(str(range(1,10,1)))
则输出:
Out[44]: ['r', 'a', 'n', 'g', 'e', '(', '1', ',', ' ', '1', '0', ')']

也不对。

需要:

numbers = [str(i) for i in list(range(1,10,1))]

for number in numbers:
    if number == '1':
        print(number + 'st')
    elif number =='2':
        print(number + 'nd')
    elif number =='3':
        print(number + 'rd')
    else:
        print(number + 'th')