栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

practice4

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

practice4

书上的一些例子2

写的很烂,记录一下,方便后续自己查看

4-1 披萨
pizzas = ['beef','seafood','sausage','cheese']
for pizza in pizzas:
    print("I like "+pizza+" pizza")
print("I really love pizza!")
I like beef pizza
I like seafood pizza
I like sausage pizza
I like cheese pizza
I really love pizza!
4-2 动物
animals = ['dog','cat','rabbit']
for animal in animals:
    print("A "+animal+" would make a great pet")
print("Any of these animals would make a great pet!")
A dog would make a great pet
A cat would make a great pet
A rabbit would make a great pet
Any of these animals would make a great pet!
4-3 数到20
for number in range(1,21):
    print(number)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
4-4 一百万
million = list(range(1,1000001))
# for number in million:
    # print(number)
4-5 计算1~1000000的总和
min(million)
1
max(million)
1000000
#sum(million)
4-6 奇数
odds = list(range(1,21,2))
for odd in odds:
    print(odd)
1
3
5
7
9
11
13
15
17
19
4-7 3的倍数
values = []
for number in range(3,31,3):
    values.append(number)
for value in values:
    print(value)
3
6
9
12
15
18
21
24
27
30
cubes = []
for value in range(1,11):
    cube = value**3
    cubes.append(cube)
for number in cubes:
    print(number)
1
8
27
64
125
216
343
512
729
1000
4-9 立方解析

列表解析 将for循环和创建新元素的代码合并成一行,注意无冒号

cubes = [value**3 for value in range(1,11)]
print(cubes)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
4-10 切片

切片仍是列表,不能和字符串一起显示,注意分开写

print("The first three items in the list are: ")
print(cubes[:3])
The first three items in the list are: 
[1, 8, 27]
print("Three items from the middle of the list are:")
print(cubes[3:6])
Three items from the middle of the list are:
[64, 125, 216]
print("The last three items in the list are: ")
print(cubes[-3:])      # 用负数来取末尾的数,有时比直接数方便 
The last three items in the list are: 
[512, 729, 1000]
4-11 你的比萨和我的比萨

关于复制
这里的切片复制是深拷贝,会涉及到另开新空间
关于深拷贝与浅拷贝

my_pizzas = ['beef','seafood','sausage','cheese']
friend_pizzas = my_pizzas[:]
my_pizzas.append('chicken')
friend_pizzas.append('durian')
print("My favorite pizzas are:")
for pizza in my_pizzas:
    print(pizza.title()+" pizza")
print("nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
    print(pizza.title()+" pizza")
My favorite pizzas are:
Beef pizza
Seafood pizza
Sausage pizza
Cheese pizza
Chicken pizza

My friend's favorite pizzas are:
Beef pizza
Seafood pizza
Sausage pizza
Cheese pizza
Durian pizza
4-12 使用多个循环
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[-2:]
print("My favorite foods are:")
for food in my_foods:
    print(food)
print("nMy friend's favorite pizzas are:")
for food in friend_foods:
    print(food)
My favorite foods are:
pizza
falafel
carrot cake

My friend's favorite pizzas are:
falafel
carrot cake
4-13 自助餐
foods = ('niunai','youtiao','baozi','mian','doujiang')
for food in foods:
    print(food)
niunai
youtiao
baozi
mian
doujiang
food[0]='mantou' #不可修改
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
----> 1 food[0]='mantou' #不可修改


TypeError: 'str' object does not support item assignment
foods = ('mantou','youtiao','baozi','zhou','doujiang')
for food in foods:
    print(food)
mantou
youtiao
baozi
zhou
doujiang
5-1 条件测试
number = 8
print("Is number == 8 ? I predict True.")
print(number == 8)
Is number == 8 ? I predict True.
True
print("nIs number == 6 ? I predict False.")
print(number == 6)
Is number == 6 ? I predict False.
False
number = 5
print("Is number == 2 ? I predict True.")
print(number == 2)
Is number == 2 ? I predict True.
False
print("Is number > 3 ? I predict True.")
print(number > 3)
Is number > 3 ? I predict True.
True
print("Is number < 8 ? I predict True.")
print(number < 8)
Is number < 8 ? I predict True.
True
print("Is number > 6 ? I predict True.")
print(number > 6)
Is number > 6 ? I predict True.
False
print("Is number < 4 ? I predict True.")
print(number < 4)
Is number < 4 ? I predict True.
False
print("Is number == 4 ? I predict True.")
print(number == 4)
Is number == 4 ? I predict True.
False
print("Is number == 5 ? I predict True.")
print(number == 5)
Is number == 5 ? I predict True.
True
color = "blue"
print("Is color == 'blue' ? I predict True.")
print(color == 'blue')
Is color == 'blue' ? I predict True.
True
5-2 更多的测试条件

检查两个字符串相等和不等

color = 'blue'
print("Is color == 'blue' ? I predict True.")
print(color == 'blue')
Is color == 'blue' ? I predict True.
True
print("Is color == 'red' ? I predict False.")
print(color == 'red')
Is color == 'red' ? I predict False.
False

使用函数lower()的测试

color = 'Blue'
color.lower() == 'blue'
True

检查两个数字大小关系

a = 5
b = 3
a == b
False
a !=b
True
a > b
True
a < b
False
a >= b
True
a <= b
False

使用关键字and和or的测试

a > 6 and b > 1
False
a > 1 and b > 1
True
a > 6 or b > 1
True

测试特定的值是否包含在列表中

colors = ['blue','red','green']
color = 'red'
if color not in colors:
    print(color.title()+" is not in the list.")
else:
    print(color.title()+" is in the list!")
Red is in the list!

测试特定的值是否未包含在列表中

colors = ['blue','red','green']
color = 'black'
if color not in colors:
    print(color.title()+" is not in the list.")
else:
    print(color.title()+" is in the list!")
Black is not in the list.
5-3 外星人颜色1
alien_color = 'red'
if alien_color == 'green':
    print("you get 5 points.")
    
alien_color = 'green'
if alien_color == 'green':
    print("you get 5 points.")
you get 5 points.
5-4 外星人颜色2
alien_color = 'red'
if alien_color == 'green':
    print("you get 5 points.")
else:
    print("you get 10 points.")
you get 10 points.
alien_color = 'green'
if alien_color == 'green':
    print("you get 5 points.")
else:
    print("you get 10 points.")
you get 5 points.
5-5 外星人颜色3
alien_color = 'red'
if alien_color == 'green':
    print("you get 5 points.")
elif alien_color == 'yellow':
    print("you get 10 points.")
else:
    print("you get 15 points.")
you get 15 points.
alien_color = 'green'
if alien_color == 'green':
    print("you get 5 points.")
elif alien_color == 'yellow':
    print("you get 10 points.")
else:
    print("you get 15 points.")
you get 5 points.
alien_color = 'yellow'
if alien_color == 'green':
    print("you get 5 points.")
elif alien_color == 'yellow':
    print("you get 10 points.")
else:
    print("you get 15 points.")
you get 10 points.
5-6 人生的不同阶段
age = 18
if age < 2:
    print("He is a baby.")
elif age < 4:
    print("He is learning to walk.")
elif age < 13:
    print("He is a child.")
elif age < 20:
    print("He is a teenager.")
elif age < 65:
    print("He is an adult.")
else:
    print("He is an old man.")
He is a teenager.
5-7 喜欢的水果
favorite_fruits = ['banana','pomegrante','peach']
if 'apple' in favorite_fruits:
    print("You really like apple")
if 'pear' in favorite_fruits:
    print("You really like pear")
if 'banana' in favorite_fruits:
    print("You really like banana")
if 'pomegrante' in favorite_fruits:
    print("You really like pomegrante")
if 'peach' in favorite_fruits:
    print("You really like peach")
You really like banana
You really like pomegrante
You really like peach
5-8 以特殊方式跟管理员打招呼
users = ['ami','eric','alice','admin','john']
for user in users:
    if user == 'admin':
        print("Hello admin,would you like to see a status report?")
    else:
        print("Hello "+user.title()+", thank you for logging in again")
Hello Ami, thank you for logging in again
Hello Eric, thank you for logging in again
Hello Alice, thank you for logging in again
Hello admin,would you like to see a status report?
Hello John, thank you for logging in again
5-9 处理没有用户的情形
users = []
if users:
    for user in users:
        if user == 'admin':
            print("Hello admin,would you like to see a status report?")
        else:
            print("Hello "+user.title()+", thank you for logging in again")
else:
    print("We need to find some users!")
We need to find some users!
5-10 检查用户名

好像还存在当前用户列表中大小写的问题,是要考虑全部存成小写?还是取出后变成小写,复制到另一个列表?或者有其他方法?

current_users = ['ami','eric','alice','mask','john']
new_users = ['zhangsan','Alice','tony','eric','tom']
for new_user in new_users:
    new_user = new_user.lower()
    if new_user not in current_users:
        print("This name isn't used.")
    else:
        print("This name has been used. You need other.")
This name isn't used.
This name has been used. You need other.
This name isn't used.
This name has been used. You need other.
This name isn't used.
5-11 序数
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")
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/308178.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号