Python编程从入门到实践 动手试一试 代码合集

本教程涵盖了Python编程的基础知识,包括变量、字符串、消息输出、列表操作、循环、条件测试、字典、函数定义、类的使用等。通过一系列练习,读者将了解如何在Python中进行基本的编程操作和逻辑控制。此外,还涉及了面向对象编程的概念,如创建类和实例化对象。
摘要由CSDN通过智能技术生成

动手试一试

2-1 简单消息

a='a message'
print(a)

2-2 多条简单消息

a='a message'
print(a)
a='two messages'
print(a)

2-3 个性化消息

name='Mark'
print('Hello '+name+','+'would you like to learn some Python today?')
Hello Mark,would you like to learn some Python today?

2-4 调整名字的大小写

name='Mark Huang'
print(name.upper())
print(name.lower())
print(name.title())
MARK HUANG
mark huang
Mark Huang

2-5 名言

print('Abraham Lincoln once said , " I am a slow walker , but I never walk backwards "')
Abraham Lincoln once said , " I am a slow walker , but I never walk backwards "

2-6 名言2

famous_person='Abraham Lincoln'
message= ' "I am a slow walker , but I never walk backwards" '
print(famous_person + 'once said,' + message)
Abraham Lincolnonce said, "I am a slow walker , but I never walk backwards" 

2-7 剔除人名中的空白

name='\n\tMark Huang\t\n'
print(name)
print(name.lstrip())
print(name.rstrip())
print(name.strip())
	Mark Huang	

Mark Huang	


	Mark Huang
Mark Huang

2-8 数字8

print(6+2)
print(10-2)
print(2*2*2)
print(8/1)
8
8
8
8.0

2-9 最喜欢的数字

favorite_number=8
print('My favorite number is'+ ' '+str(favorite_number))
My favorite number is 8

2-10 添加注释

# this is a notation
print('a notation is testing.')
a notation is testing.

2-11 Python之禅

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

3-1 姓名

names=['Jack','Tom','Mark']
print(names[0])
print(names[1])
print(names[2])
Jack
Tom
Mark

3-2 问候语

names=['Jack','Tom','Mark']
print(names[0]+', Nice to meet you !')
print(names[1]+', Nice to meet you !')
print(names[2]+', Nice to meet you !')
Jack, Nice to meet you !
Tom, Nice to meet you !
Mark, Nice to meet you !

3-3 自己的列表

commutes=['Porsche','Mercedes-Benz','HongQi']
print('I would like to own a '+commutes[0]+' car')
print('I would like to own a '+commutes[1]+' car')
print('I would like to own a '+commutes[2]+' car')
I would like to own a Porsche car
I would like to own a Mercedes-Benz car
I would like to own a HongQi car

3-4 嘉宾名单

guest_list=['Tom','Mike','Mark']
print(guest_list[0]+' was invited')
print(guest_list[1]+' was invited')
print(guest_list[2]+' was invited')
Tom was invited
Mike was invited
Mark was invited

3-5 修改嘉宾列表

guest_list=['Tom','Mike','Mark']
print(guest_list[-3]+' is unable to keep the appointment')
guest_list[0]='Marry'
print(guest_list[0]+' was invited')
print(guest_list[1]+' was invited')
print(guest_list[2]+' was invited')
Tom is unable to keep the appointment
Marry was invited
Mike was invited
Mark was invited

3-6 添加嘉宾

print('The bigger table has been found')
guest_list.insert(0,'John')
guest_list.insert(2,'Alice')
guest_list.append('Tony')
print(guest_list[0]+' was invited')
print(guest_list[1]+' was invited')
print(guest_list[2]+' was invited')
print(guest_list[3]+' was invited')
print(guest_list[4]+' was invited')
print(guest_list[5]+' was invited')
The bigger table has been found
John was invited
Marry was invited
Alice was invited
Mike was invited
Mark was invited
Tony was invited

3-7 缩减名单

guest_list=['Tom','Mike','Mark']
guest_list[0]='Marry'
guest_list.insert(0,'John')
guest_list.insert(2,'Alice')
guest_list.append('Tony')
print('sorry, we have only two people able to attend this invitation')
a=guest_list.pop(0)
print(a+' can not be able to invite')
a=guest_list.pop(0)
print(a+' can not be able to invite')
a=guest_list.pop(1)
print(a+' can not be able to invite')
a=guest_list.pop(2)
print(a+' can not be able to invite')
print(guest_list[0]+' was still be invited')
print(guest_list[1]+' was still be invited')
del guest_list[0]
del guest_list[0]
print(guest_list)
sorry, we have only two people able to attend this invitation
John can not be able to invite
Marry can not be able to invite
Mike can not be able to invite
Tony can not be able to invite
Alice was still be invited
Mark was still be invited
[]

3-8 放眼世界

cities=['Beijing','Shanghai','Hangzhou','Chongqing','Zhengzhou']
print(cities)
print(sorted(cities))
print(cities)
print(sorted(cities,reverse=(True)))
print(cities)
cities.reverse()
print(cities)
cities.reverse()
print(cities)
cities.sort()
print(cities)
print(cities)
cities.sort(reverse=True)
print(cities)
['Beijing', 'Shanghai', 'Hangzhou', 'Chongqing', 'Zhengzhou']
['Beijing', 'Chongqing', 'Hangzhou', 'Shanghai', 'Zhengzhou']
['Beijing', 'Shanghai', 'Hangzhou', 'Chongqing', 'Zhengzhou']
['Zhengzhou', 'Shanghai', 'Hangzhou', 'Chongqing', 'Beijing']
['Beijing', 'Shanghai', 'Hangzhou', 'Chongqing', 'Zhengzhou']
['Zhengzhou', 'Chongqing', 'Hangzhou', 'Shanghai', 'Beijing']
['Beijing', 'Shanghai', 'Hangzhou', 'Chongqing', 'Zhengzhou']
['Beijing', 'Chongqing', 'Hangzhou', 'Shanghai', 'Zhengzhou']
['Beijing', 'Chongqing', 'Hangzhou', 'Shanghai', 'Zhengzhou']
['Zhengzhou', 'Shanghai', 'Hangzhou', 'Chongqing', 'Beijing']

4-1 比萨

pizzas=['New York Style','Chicago Style','California Style']
for pizza in pizzas:
 print(pizza)
 print("I want to eat "+pizza+' pizza')
print('\nI really love pizza !')   
New York Style
I want to eat New York Style pizza
Chicago Style
I want to eat Chicago Style pizza
California Style
I want to eat California Style pizza

I really love pizza !

4-2 动物

animals=['dog','cat','duck']
for animal in animals:
 print(animal)
 print("A "+animal+" would make a great pet")
print("\nAny of these animals would make a great pet !")
dog
A dog would make a great pet
cat
A cat would make a great pet
duck
A duck would make a great pet

Any of these animals would make a great pet !

4-3 数到20

for value in range(1,21):
 print(value)
dog
A dog would make a great pet
cat
A cat would make a great pet
duck
A duck would make a great pet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

4-4 一百万

millions=list(range(1,1000001))
for million in millions:
    print(million)

4-4 一百万

4-5 计算1~1000000的总和

one_million=list(range(1,1000001))
print(min(one_million))
print(max(one_million))
print(sum(one_million))
1
1000000
500000500000

4-6 奇数

odds=list(range(1,20,2))
for odd in odds:
    print(odd)
1
3
5
7
9
11
13
15
17
19

4-7 3的倍数

odds=list(range(3,31,3))
for odd in odds:
    print(odd)
3
6
9
12
15
18
21
24
27
30

4-8 立方

cubes=[]
for value in range(1,11):
    cubes.append(value**3)
print(cubes)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

4-9 立方解析

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

4-10 切片

cities=['Beijing','Shanghai','Hangzhou','Chongqing','Zhengzhou']
print("The first three items in the list are:")
print(cities[0:3])
print("\nThree items from the middle of the list are:")
print(cities[1:4])
print("\nThe last three items in the list are:")
print(cities[-3:])
The first three items in the list are:
['Beijing', 'Shanghai', 'Hangzhou']

Three items from the middle of the list are:
['Shanghai', 'Hangzhou', 'Chongqing']

The last three items in the list are:
['Hangzhou', 'Chongqing', 'Zhengzhou']

4-11 你的比萨和我的比萨

pizzas=['New York Style','Chicago Style','California Style']
friend_pizzas=pizzas[0:3]
pizzas.append("Apples Styles")
friend_pizzas.append("Cheese Stycle")
for pizza in pizzas:
    print(pizza)
print("\n")
for friend_pizza in friend_pizzas:
    print(friend_pizza)
New York Style
Chicago Style
California Style
Apples Styles

New York Style
Chicago Style
California Style
Cheese Stycle

4-12 使用多个循环

my_foods=['pizza','falafel','carrot cake','cannoli','ice cream']
for my_food in my_foods:
    print(my_food)
print('\n')
for i in range(0,5):
    print(my_foods[4-i])    
pizza
falafel
carrot cake
cannoli
ice cream


ice cream
cannoli
carrot cake
falafel
pizza

4-13 自助餐

dishes=('a','b','c','d','e')
for dish in dishes:
    print(dish)
print('\n')
dishes=('aa','bb','c','d','e')
for dish in dishes:
    print(dish)
a
b
c
d
e

aa
bb
c
d
e

5-1 条件测试

car='subaru'
print("Is car == 'subaru'? I predict True")
print(car == 'subaru')

print("\nIs car == 'audi ? I predict False'")
print(car == 'audi')
Is car == 'subaru'? I predict True
True

Is car == 'audi ? I predict False'
False

5-2 更多的条件测试

conditional_test=['AAA','aaa','bbb']
print("AAA = aaa ?")
print(conditional_test[0]==conditional_test[1]+"\n")
print("AAA的小写是否与aaa相等")
print(conditional_test[0].lower()==conditional_test[1]+"\n")

numbers=[1,2,3,4,5]
print("1 < 2 ?")
print(numbers[0]<numbers[1])
print("1 <= 2 ?")
print(numbers[0]<=numbers[1])
print("2 > 3 ?")
print(numbers[1]>numbers[2])
print("2 >= 3 ?")
print(numbers[1]>=numbers[2])
print("3 = 4 ?")
print(numbers[2] == numbers[3])
print("4 != 5 ?")
print(numbers[3] == numbers[4])
print("1 < 2 and 2 > 3 ?")
print(numbers[0] < numbers[1] and numbers[1] > numbers[2])
print("1 < 2 or 2 > 3 ?")
print(numbers[0] < numbers[1] or numbers[1] > numbers[2])
print("8 in numbers")
print(8 in numbers)
print("8 not in numbers")
print(8 not in numbers)
AAA = aaa ?
False
AAA的小写是否与aaa相等
False
1 < 2 ?
True
1 <= 2 ?
True
2 > 3 ?
False
2 >= 3 ?
False
3 = 4 ?
False
4 != 5 ?
False
1 < 2 and 2 > 3 ?
False
1 < 2 or 2 > 3 ?
True
8 in numbers
False
8 not in numbers
True

5-3 外星人颜色#1

alien_color='yellow'
if alien_color=='green':
    print("You get 5 scores")

5-4 外星人颜色#2

alien_color='yellow'
if alien_color=='green':
    print("You get 5 scores")
else:
    print("You get 10 scores")
You get 10 scores

5-5 外星人颜色#3

alien_color='yellow'
if alien_color=='green':
    print("You get 5 scores")
elif alien_color=='green':
    print("You get 10 scores")
else:
    print("You get 15 scores")
You get 15 scores

5-6 人生的不同阶段

age=22

if age<2:
    print("He is a baby")
elif age>=2 and age<4:
    print("He is learning to walk")
elif age>=4 and age<13:
    print("He's a child")
elif age>=13 and age<20:
    print("He's a teenager")
elif age>=20 and age<65:
    print("He's an adult")
elif age>=65:
    print("He's an old man")
He's an adult

5-7 喜欢的水果

favourite_fruits=['apple','peach','watermelon','bananas','strawberry']
if 'apple' in favourite_fruits:
    print("You really like apples")
if 'peach' in favourite_fruits:
    print("You really like peaches")
if 'watermelon' in favourite_fruits:
    print("You really like watermelons")
if 'bananas' in favourite_fruits:
    print("You really like bananas")
if 'strawberry' in favourite_fruits:
    print("You really like strawberries")
You really like apples
You really like peaches
You really like watermelons
You really like bananas
You really like strawberries

5-8 以特殊的方式跟管理员打招呼

users=['admin','Tom','Mark','Jack','Eric']
for user in users:
    if user == 'admin':
        print("Hello admin, would you like to see a status report ?")
    else:
        print("Hello "+user+" ,"+" thank you for logging in again")
Hello admin, would you like to see a status report ?
Hello Tom , thank you for logging in again
Hello Mark , thank you for logging in again
Hello Jack , thank you for logging in again
Hello Eric , thank you for logging in again

5-9 处理没有用户的情况

users=['admin','Tom','Mark','Jack','Eric']
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+" ,"+" thank you for logging in again")
else:
    print("We need to find some users!")
We need to find some users!

5-10 检查用户名

current_users=['Huang','Tom','Mark','Jack','Eric']
new_users=['John','Alice','Tom','Mark','Mike']
i=0
for current_user in current_users:
    current_users[i].lower()
    i=i+1
i=0
for new_user in new_users:
    new_users[i].lower()
    i=i+1
for new_user in new_users:
    if new_user in current_users:
        print("Sorry, You need to enter a different user name.")
    else:
        print("This user name is not used.")
This user name is not used.
This user name is not used.
Sorry, You need to enter a different user name.
Sorry, You need to enter a different user name.
This user name is not 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

6-1 人

informations={"first_name":"A","last_name":"B","age":22,"city":"Beijing"}
print(informations['first_name'])
print(informations['last_name'])
print(informations['age'])
print(informations['city'])
A
B
22
Beijing

6-2 喜欢的数字

favorite_numbers={"Alice":1,"Tom":2,"Jack":3,"Mike":4,"Mark":5}
print(favorite_numbers)
{'Alice': 1, 'Tom': 2, 'Jack': 3, 'Mike': 4, 'Mark': 5}

6-3 词汇表

dictionaries={
    "application":"应用程式 应用、应用程序",
    "batch":"批次(意思是整批作业) 批处理",
    "character":"字元、字符",
    "debug":" 除错、调试",
    "enumerators":"列举元(enum 型别中的成员)枚举成员、枚举器"
             }
print("application: "+dictionaries['application']+"\n")
print("batch: "+dictionaries['batch']+"\n")
print("character: "+dictionaries['character']+"\n")
print("debug: "+dictionaries['debug']+"\n")
print("enumerators: "+dictionaries['enumerators']+"\n")
application: 应用程式 应用、应用程序

batch: 批次(意思是整批作业) 批处理

character: 字元、字符

debug:  除错、调试

enumerators: 列举元(enum 型别中的成员)枚举成员、枚举器

6-4 词汇表2

dictionaries={
    "application":"应用程式 应用、应用程序",
    "batch":"批次(意思是整批作业) 批处理",
    "character":"字元、字符",
    "debug":" 除错、调试",
    "enumerators":"列举元(enum 型别中的成员)枚举成员、枚举器"
             }
for key,value in dictionaries.items():
    print(key.title()+": "+value)
Application: 应用程式 应用、应用程序
Batch: 批次(意思是整批作业) 批处理
Character: 字元、字符
Debug:  除错、调试
Enumerators: 列举元(enum 型别中的成员)枚举成员、枚举器

6-5 河流

rivers={
    "HuangHe River":"China",
    "ChangJiang River":"China",
    "nile":"egypt",
       }
for key,value in rivers.items():
    print("The "+key+" runs through "+value.title())
print("\n")
for key in rivers.keys():
    print(key)
print("\n")
for key in set((rivers.values())):
    print(key.title())
The HuangHe River runs through China
The ChangJiang River runs through China
The nile runs through Egypt

HuangHe River
ChangJiang River
nile

Egypt
China

6-6 调查

favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
people=['jen','sarah','edward','phil','mark']
for person in people:
    if person in favorite_languages.keys():
        print(person.title()+", Thank you for taking the poll.")
    else:
        print(person.title()+", We want to invite you to take the poll")
Jen, Thank you for taking the poll.
Sarah, Thank you for taking the poll.
Edward, Thank you for taking the poll.
Phil, Thank you for taking the poll.
Mark, We want to invite you to take the poll

6-7 人

person_0={"first_name":"A","last_name":"B","age":22,"city":"Beijing"}
person_1={"first_name":"C","last_name":"D","age":21,"city":"Shanghai"}
person_2={"first_name":"E","last_name":"F","age":22,"city":"Zhengzhou"}
people=[person_0,person_1,person_2]
for persons in people:
    print(persons)
{'first_name': 'A', 'last_name': 'B', 'age': 22, 'city': 'Beijing'}
{'first_name': 'C', 'last_name': 'D', 'age': 21, 'city': 'Shanghai'}
{'first_name': 'E', 'last_name': 'F', 'age': 22, 'city': 'Zhengzhou'}

6-8 宠物

A={
    'type':'cat',
    "owner":'Tom',
}
B={
    'type':'dog',
    "owner":'Mike',
}
pets=[A,B]
for pet in pets:
    print(pet)
{'type': 'cat', 'owner': 'Tom'}
{'type': 'dog', 'owner': 'Mike'}

6-9 喜欢的地方

favorite_places={
    'Tom':'Beijing,Shanghai,Tianjin',
    'Mike':'Beijing,Shanghai,Hangzhou',
    'Mark':'Beijing,Shanghai,Zhengzhou'
                }
for key,value in favorite_places.items():
    print(key+"'s favorite place "+value)
Tom's favorite place Beijing,Shanghai,Tianjin
Mike's favorite place Beijing,Shanghai,Hangzhou
Mark's favorite place Beijing,Shanghai,Zhengzhou

6-10 喜欢的数字

favorite_numbers={"Alice":'1,2',"Tom":'2,3',"Jack":'3,4',"Mike":'4,5',"Mark":'5,6'}
for key,value in favorite_numbers.items():
    print(key+"'s favorite numbers are "+value)
Alice's favorite numbers are 1,2
Tom's favorite numbers are 2,3
Jack's favorite numbers are 3,4
Mike's favorite numbers are 4,5
Mark's favorite numbers are 5,6

6-11 城市

cities={
    'Beijing':{
        'nation':'China',
        'population':'3kw',
        'modernation':'good'
    },
    'Zhengzhou':{
        'nation':'China',
        'population':'1kw',
        'modernation':'good'
    },
    'Shanghai':{
        'nation':'China',
        'population':'3kw',
        'modernation':'good'
    }
}
for city_name,city_info in cities.items():
    print(city_name+"'s nation is "+city_info['nation'])
    print("She has "+city_info['population']+' population')
    print("she's modernation is "+city_info['modernation'])
    print("\n")
Beijing's nation is China
She has 3kw population
she's modernation is good

Zhengzhou's nation is China
She has 1kw population
she's modernation is good

Shanghai's nation is China
She has 3kw population
she's modernation is good

7-1 汽车租赁

ask=input("what kind of cars do you want ?")
print("Let me see if I can find you a Subaru.")
what kind of cars do you want ?bmw
Let me see if I can find you a Subaru.

7-2 餐馆订位

eat=input("How many people having a meal ?")
eat=int(eat)
if eat>8:
    print("There is no vacant table at present.")
else:
    print("There is a table at present.")
How many people having a meal ?10
There is no vacant table at present.

7-3 10的整数倍

number=input("Please input a number:")
number=int(number)
if number%10==0:
    print("This number is an integral multiple of 10.")
else:
    print("This number is not an integral multiple of 10")
Please input a number:100
This number is an integral multiple of 10

7-4 比萨配料

condition=True
while condition:
    topping=input("Please tell me a topping in your pizza:")
    if topping=='quit':
        break
    print(topping.title()+" will be taken in your pizza.")
Please tell me a topping in your pizza:extra cheese
Extra Cheese will be taken in your pizza.
Please tell me a topping in your pizza:harm
Harm will be taken in your pizza.
Please tell me a topping in your pizza:quit

7-5 电影票

condition=True
while condition:
    age=input("Please tell me your age:")
    if age=='quit':
        break
    age=int(age)
    if age<3:
         print("We are free for you.\n")
    elif age>=3 and age<12:
        print("Your ticket's price is $10\n")
    else:
        print("Your ticket's price is $15\n")
Please tell me your age:2
We are free for you.

Please tell me your age:8
Your ticket's price is $10

Please tell me your age:22
Your ticket's price is $15

Please tell me your age:quit

7-6 三个出口

active=True
while active:
    age=input("Please tell me your age:")
    if age=='quit':
        break
    age=int(age)
    if age<3:
         print("We are free for you.\n")
    elif age>=3 and age<12:
        print("Your ticket's price is $10\n")
    else:
        print("Your ticket's price is $15\n")

7-7 无限循环

i=0
while True:
    print(i)
    i+=1

7-7 无限循环

7-8 熟食店

sandwich_orders=['apple sandwich','ham sandwich','cheese sandwich']
finished_sandwiches=[]
while sandwich_orders:
    sandwich_order=sandwich_orders.pop()
    print("I made your "+sandwich_order)
    finished_sandwiches.append(sandwich_order)
print(finished_sandwiches)
I made your cheese sandwich
I made your ham sandwich
I made your apple sandwich
['cheese sandwich', 'ham sandwich', 'apple sandwich']

7-9 五香烟熏牛肉(pastrami)卖完了

sandwich_orders=['pastrami','apple sandwich','ham sandwich','pastrami','cheese sandwich','pastrami']
print("The pastrami have been sold")
active=True
while active:
    if 'pastrami' in sandwich_orders:
        sandwich_orders.remove("pastrami")
    else:
        active=False
print(sandwich_orders)
The pastrami have been sold
['apple sandwich', 'ham sandwich', 'cheese sandwich']

7-10 梦想的度假胜地

places=[]
polling_active=True
while polling_active:
    question="If you could visit one place in the world, where would you go ?"
    place=input(question)
    if place =='no':
        break
    places.append(place)
print(places)
If you could visit one place in the world, where would you go ?beijing
If you could visit one place in the world, where would you go ?zhengzhou
If you could visit one place in the world, where would you go ?shanghai
If you could visit one place in the world, where would you go ?no
['beijing', 'zhengzhou', 'shanghai']

8-1 消息

def display_message():
    print("I am learning function.")
display_message()
I am learning function.

8-2 喜欢的图书

def favorite_book(book_name):
    print("One of my favorite books is "+book_name)
favorite_book("Alice in Wonderland")
One of my favorite books is Alice in Wonderland

8-3 T恤

def make_shirt(size,slogan):
    print("This shirt is "+size+" size"+" and printed '"+slogan+" '")
make_shirt("L","Just do it")
make_shirt(size="L",slogan="Just do it")
This shirt is L size and printed 'Just do it '
This shirt is L size and printed 'Just do it '

8-4 大号T恤

def make_shirt(size='L',slogan="I love python"):
    print("This shirt is "+size+" size"+" and printed '"+slogan+" '")
make_shirt()
make_shirt('M')
make_shirt("L","Just do it")
This shirt is L size and printed 'I love python '
This shirt is M size and printed 'I love python '
This shirt is L size and printed 'Just do it '

8-5 城市

def describe_city(city,nation="China"):
    print(city+" is in "+nation)
describe_city('Beijing')
describe_city('Zhengzhou')
describe_city('London',nation='British')
Beijing is in China
Zhengzhou is in China
London is in British

8-6 城市名

def city_country(city,nation):
    result='"'+city+','+nation+'"'
    return result
print(city_country('Beijing','China'))
print(city_country('Seoul','Korea'))
print(city_country('Tokyo','Japan'))
"Beijing,China"
"Seoul,Korea"
"Tokyo,Japan"

8-7 专辑

def make_album(singer,name,song_number=''):
    describe_album={'Singer':singer,'Album_Name':name}
    return describe_album
describe=make_album('Westlife','face to face')
print(describe)
describe=make_album('Taylor Swift','fearless')
print(describe)
describe=make_album('The Beatles','Please Please Me')
print(describe)
{'Singer': 'Westlife', 'Album_Name': 'face to face'}
{'Singer': 'Taylor Swift', 'Album_Name': 'fearless'}
{'Singer': 'The Beatles', 'Album_Name': 'Please Please Me'}

8-8 用户的专辑

def make_album(singer,name,song_number=''):
    describe_album={'Singer':singer,'Album_Name':name}
    return describe_album
while True:
    singer=input("Please input a singer: ")
    if singer=='q':
        break
    name=input("Input this singer's album: ")
    if name=='q':
        break
    describe=make_album(singer,name)
    print(describe)
    print("\n")
Please input a singer: The Beatles
Input this singer's album: Please Please Me
{'Singer': 'The Beatles', 'Album_Name': 'Please Please Me'}

Please input a singer: Taylor Swift
Input this singer's album: fearless
{'Singer': 'Taylor Swift', 'Album_Name': 'fearless'}

Please input a singer: q

8-9 魔术师

def show_magicians(names):
    for name in names:
        print(name)
magicians=['Tom','Mike','Mark']
show_magicians(magicians)
Tom
Mike
Mark

8-10 了不起的魔术师

def make_great(magicians):
    i=0
    for magician in magicians:
        magicians[i]="the Great "+magician
        i+=1
def show_magicians(names):
    for name in names:
        print(name)
magicians=['Tom','Mike','Mark']
make_great(magicians)
show_magicians(magicians)
the Great Tom
the Great Mike
the Great Mark

8-11 不变的魔术师

def make_great(magics):
    i=0
    for magic in magics:
        magics[i]="the Great "+magic
        i+=1
    return magics
def show_magicians(names):
    for name in names:
        print(name)
magicians=['Tom','Mike','Mark']
magicians_revise=make_great(magicians[:])
show_magicians(magicians)
show_magicians(magicians_revise)
Tom
Mike
Mark
the Great Tom
the Great Mike
the Great Mark

8-12 三明治

def make_sandwich(*toppings):
    """打印顾客点的所有配料"""
    print("\nMaking a sandwich with the following toppings:")
    for topping in toppings:
        print("-"+topping)
make_sandwich('mushrooms')
make_sandwich('extra cheese','ham')
Making a sandwich with the following toppings:
-mushrooms

Making a sandwich with the following toppings:
-extra cheese
-ham

8-13 用户简介

def build_profile(first,last,**user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile={}
    profile['first_name']=first
    profile['last_name']=last
    for key,value in user_info.items():
        profile[key]=value
    return profile
user_profile=build_profile('Mark','Huang',
                            location='China',
                            field='civil of engineering',
                           gender='male'
                          )
print(user_profile)
{'first_name': 'Mark', 'last_name': 'Huang', 'location': 'China', 'field': 'civil of engineering', 'gender': 'male'}

8-14 汽车

def make_car(car_name,car_type,**info):
    car_info={}
    car_info['car_name']=car_name
    car_info['car_type']=car_type
    for key,value in info.items():
        car_info[key]=value
    return car_info
car=make_car('subaru','outback',color='blue',tow_package=True)
print(car)
{'car_name': 'subaru', 'car_type': 'outback', 'color': 'blue', 'tow_package': True}

9-1餐馆

class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
    
    def describe_restaurant(self):
        print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)
        
    def open_restaurant(self):
        print("The restaurant is open")

restaurant=Restaurant("豫香苑","HeNan Stewed noodles and Hulatang")

print(restaurant.restaurant_name)
print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
豫香苑
HeNan Stewed noodles and Hulatang
Our restaurant is 豫香苑 ,we sold HeNan Stewed noodles and Hulatang
The restaurant is open

9-2 三家餐馆

class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
    
    def describe_restaurant(self):
        print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)
        
    def open_restaurant(self):
        print("The restaurant is open")

restaurant1=Restaurant("豫香苑","HeNan Stewed noodles and Hulatang")
restaurant2=Restaurant("聚丰园","HeNan Stewed noodles")
restaurant3=Restaurant("方中山","Hulatang")
restaurant1.describe_restaurant()
restaurant2.describe_restaurant()
restaurant3.describe_restaurant()
Our restaurant is 豫香苑 ,we sold HeNan Stewed noodles and Hulatang
Our restaurant is 聚丰园 ,we sold HeNan Stewed noodles
Our restaurant is 方中山 ,we sold Hulatang

9-3 用户

class User():
    def __init__(self,first_name,last_name):
        self.first_name=first_name
        self.last_name=last_name
    
    def describe_user(self):
        print("This user's name is "+self.first_name+" "+self.last_name)
    
    def greet_user(self):
        print(self.first_name+" "+self.last_name+" Welcome you !")
        
user1=User('Eloise','Dimucci')
user1.describe_user()
user2=User('Penelope','Liones')
user2.describe_user()
user3=User('Evelyn','Alovis')
user3.describe_user()
This user's name is Eloise Dimucci
This user's name is Penelope Liones
This user's name is Evelyn Alovis

9-4 就餐人数

class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
        self.number_served=0
    
    def describe_restaurant(self):
        print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)
        
    def open_restaurant(self):
        print("The restaurant is open")
    
    def increment_number_served(self,imp_number):
        self.impossible_number=imp_number
        print("This restaurant can accommodate "+str(self.impossible_number)+" people every day")

restaurant=Restaurant("豫香苑","HeNan Stewed noodles and Hulatang")

print(restaurant.restaurant_name)
print(restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()
print(str(restaurant.number_served)+" people have dined in this restaurant")
restaurant.number_served=88
print(str(restaurant.number_served)+" people have dined in this restaurant")
restaurant.increment_number_served(100)
豫香苑
HeNan Stewed noodles and Hulatang
Our restaurant is 豫香苑 ,we sold HeNan Stewed noodles and Hulatang
The restaurant is open
0 people have dined in this restaurant
88 people have dined in this restaurant
This restaurant can accommodate 100 people every day

9-5 尝试登陆次数

class User():
    def __init__(self,first_name,last_name):
        self.first_name=first_name
        self.last_name=last_name
        self.login_attempts=0
    
    def describe_user(self):
        print("This user's name is "+self.first_name+" "+self.last_name)
    
    def greet_user(self):
        print(self.first_name+" "+self.last_name+" Welcome you !")
        
    def increment_login_attempts(self):
        self.login_attempts+=1
    
    def reset_login_attempts(self):
        self.login_attempts=0
my_user=User("A","B")
my_user.increment_login_attempts()
print(my_user.login_attempts)
my_user.increment_login_attempts()
print(my_user.login_attempts)
my_user.increment_login_attempts()
print(my_user.login_attempts)
my_user.reset_login_attempts()
print(my_user.login_attempts)
1
2
3
0

9-6 冰淇淋小店

class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
    
    def describe_restaurant(self):
        print("Our restaurant is "+self.restaurant_name+" ,we sold "+self.cuisine_type)
        
    def open_restaurant(self):
        print("The restaurant is open")
class IceCreamStand(Restaurant):
    def __init__(self,restaurant_name,cuisine_type):
        super().__init__(restaurant_name,cuisine_type)
        self.flavors=['popsicle','frozen yogurt','gelato']
    def show(self):
        print(self.flavors)
icecream=IceCreamStand('ICECREAM','snack')
icecream.show()
['popsicle', 'frozen yogurt', 'gelato']

9-7 管理员

class User():
    def __init__(self,first_name,last_name):
        self.first_name=first_name
        self.last_name=last_name
    
    def describe_user(self):
        print("This user's name is "+self.first_name+" "+self.last_name)
    
    def greet_user(self):
        print(self.first_name+" "+self.last_name+" Welcome you !")
class Admin(User):
    def __init__(self,first_name,last_name):
        super().__init__(first_name,last_name)
        self.privileges=['can add post','can delete post','can ban user']
    def show_privileges(self):
        print(self.privileges)
admin_user=Admin('Eloise','Dimucci')
admin_user.show_privileges()
['can add post', 'can delete post', 'can ban user']

9-8 权限

class Privileges():
    def __init__(self,privileges=['can add post','can delete post','can ban user']):
        self.privileges=privileges

        
    def show_privileges(self):
        print(self.privileges)

class User():
    def __init__(self,first_name,last_name):
        self.first_name=first_name
        self.last_name=last_name
    
    def describe_user(self):
        print("This user's name is "+self.first_name+" "+self.last_name)
    
    def greet_user(self):
        print(self.first_name+" "+self.last_name+" Welcome you !")
        
class Admin(User):
    def __init__(self,first_name,last_name):
        super().__init__(first_name,last_name)
        self.PRIVILEGES=Privileges()

admin_user=Admin('Eloise','Dimucci')
admin_user.PRIVILEGES.show_privileges()
['can add post', 'can delete post', 'can ban user']

9-9 电瓶升级

class Car():
    def  __init__(self,make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=0
        
    def get_descriptive_name(self):
        long_name=str(self.year)+' '+self.make+' '+self.model
        return long_name.title()
    
    def read_odometer(self):
        print("This car has "+str(self.odometer_reading)+" miles on it.")
        
    def update_odometer(self,mileage):
        if mileage>=self.odometer_reading:
            self.odometer_reading=mileage
        else:
            print("You can't roll back an odometer!")
    def increment_odometer(self,miles):
        self.odometer_reading+=miles

class  Battery():
    """一次模拟电动汽车电瓶的简单尝试"""
    
    def __init__(self,battery_size=70):
        """初始化电瓶的属性"""
        self.battery_size=battery_size
    
    def describe_battery(self):
        """打印一条描述电瓶容量的消息"""
        print("This car has a "+str(self.battery_size)+"-kwh battery.")
        
    def get_range(self):
        """打印一条消息,指出电瓶的续航里程"""
        if self.battery_size==70:
            range=240
        elif self.battery_size==85:
            range=270
        message="This car can go approximately "+str(range)
        message+=" miles on a full charge"
        print(message)
    
    def upgrade_battery(self):
        if self.battery_size !=85:
            self.battery_size=85
        
class ElectricCar(Car):
    '''电动汽车的独特之处'''
    
    def __init__(self,make,model,year):
        '''初始化父类的属性,再初始化电动汽车特有的属性'''
        super().__init__(make,model,year)
        self.battery=Battery()

my_tesla=ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
my_tesla.battery.upgrade_battery()
my_tesla.battery.get_range()
2016 Tesla Model S
This car has a 70-kwh battery.
This car can go approximately 240 miles on a full charge
This car can go approximately 270 miles on a full charge

10-1 Python学习笔记

filename_path=r'C:\Users\JianFei\Desktop\learning_python.txt'

with open(filename_path) as file_object:
    contents=file_object.read()
    print(contents)
print("\n")    
with open(filename_path) as file_object:
    for line in file_object:
        print(line.rstrip())
print("\n")    
with open(filename_path) as file_object:
    lines=file_object.readlines()
for line in lines:
    print(line)
In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.


In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.

In Python you can store as much information as you want.

In Python you can connect pieces of information.

In Python you can model real-world situations.

10-2 C语言学习笔记

filename_path=r'C:\Users\JianFei\Desktop\learning_python.txt'

with open(filename_path) as file_object:
    lines=file_object.readlines()
for line in lines:
    line=line.replace("Python","C")
    print(line)
In C you can store as much information as you want.

In C you can connect pieces of information.

In C you can model real-world situations.

10-3 访客

filename='guest.txt'
with open(filename,'w') as file_object:
    file_object.write(input("Please input your name:"))

在这里插入图片描述

10-4 访客名单

filename='guest_book.txt'
guest_name=''
with open(filename,'w') as file_object:
    while True:
        guest_name=input("Please input your name:")
        if guest_name=='n':
            break
        else:
            file_object.write(guest_name+"\n")
            greeting="Welcome "+guest_name+" !"
            print(greeting)
            file_object.write(greeting+"\n")

在这里插入图片描述

10-5 关于编程的调查

filename='reasons.txt'
reason=''
with open(filename,'w') as file_object:
    while True:
        reason=input("Please input a reason why you like programning ?")
        if reason=='stop':
            break
        else:
            file_object.write(reason+"\n")

在这里插入图片描述

10-6 加法运算

print("Give me two numbers: and I'll add them.")

first_number=input("\nFirst number:")
try:
    first_number=int(first_number)
except ValueError:
    print("You're entering text, Please enter a number.")
else:
    second_number=input("Second number:")
    try:
        second_number=int(second_number)
    except ValueError:
        print("You're entering text, Please enter a number.")
    else:
        print(first_number+second_number)
Give me two numbers: and I'll add them.

First number:8
Second number:a
You're entering text, Please enter a number.

10-7 加法计算器

print("Give me two numbers: and I'll add them.")
print("Enter 'q' to quit.")
while True:
    first_number=input("\nFirst number:")
    if first_number=='q':
        break
    try:
        first_number=int(first_number)
    except ValueError:
        print("You're entering text, Please enter a number.")
    else:
        second_number=input("Second number:")
        if second_number=='q':
            break
        try:
            second_number=int(second_number)
        except ValueError:
            print("You're entering text, Please enter a number.")
        else:
            print(first_number+second_number)
Give me two numbers: and I'll add them.
Enter 'q' to quit.

First number:8
Second number:8
16

First number:q

10-8 猫和狗

def print_name(filename):
    try:
        with open(filename)as f_obj:
            contents=f_obj.read()
    except FileNotFoundError:
        msg="Sorry, the file "+filename+" does not exist."
        print(msg)
    else:
        print(contents)
filenames=['cats.txt','dogs.txt']
for filename in filenames:
    print_name(filename)
a
b
c
Sorry, the file dogs.txt does not exist.

10-9 沉默的猫和狗

def print_name(filename):
    try:
        with open(filename)as f_obj:
            contents=f_obj.read()
    except:
        pass
    else:
        print(contents)
filenames=['cats.txt','dogs.txt']
for filename in filenames:
    print_name(filename)
a
b
c

10-10 常见单词

filename='War against Germany and Italy.txt'

try:
    with open(filename,encoding='UTF-8') as f_obj:
        contents=f_obj.read()
except FileNotFoundError:
    msg="Sorry the file "+filename+" does not exist."
    print(msg)
else:
    words=contents.split()
    num=words.count('the')
    print("'the' appears "+str(num)+" times")
'the' appears 26 times

10-11 喜欢的数字

import json
filename="favorurite_number.json"
fav_number=input("Please input your favorite number.")
with open(filename,'w') as f_obj:
    json.dump(fav_number,f_obj)
Please input your favorite number.8
import json
filename="favorurite_number.json"
with open(filename) as f_obj:
    fav_number=json.load(f_obj)
    print("I know your favourite number!It's "+fav_number)
I know your favourite number!It's 8

10-12 记住喜欢的数字

import json
filename='favourite_number.json'
try:
    with open(filename)as f_obj:
        fav_number=json.load(f_obj)
except:
    fav_number=input("Please input your favorite number.")
    with open(filename,'w') as f_obj:
        json.dump(fav_number,f_obj)
        print("Your favourite number has been recorded !It's "+fav_number)
else:
    print("I know your favourite number!It's "+fav_number)
Please input your favorite number.8
Your favourite number has been recorded !It's 8

10-13 验证用户

import json

def get_stored_username():
    """如果存储了用户名,就获取它"""
    filename='username.json'
    try:
        with open(filename)as f_obj:
            username=json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username
    
def get_user_username():
    """提示用户输入用户名"""
    username=input("What is your name?")
    filename='username.json'
    with open(filename,'w') as f_obj:
        json.dump(username,f_obj)
    return username

def greet_user():
    """问候用户,并指出其名字"""
    username=get_stored_username()
    if username:
        print("Welcomg back, "+username+"!")
    else:
        username=get_new_username()
        print("We'll remember you when you come back, "+username+"!")

greet_user()
Welcomg back, Eric!
### 回答1: 《Python编程入门实践》是一本非常适合初学者的Python编程教材,编写了涵盖了Python语言的基础知识和实践应用的内容。配套代码是书中提供的用于实践的示例代码,用于辅助读者理解和实践书中的知识。 这本书的配套代码由作者根据每个章节的内容编写而成,整体结构与书中章节一一对应。每个章节的代码示例都是从简单到复杂的演进过程,读者可以通过逐步实践和理解这些代码,掌握Python的各种基础和实践技巧。 配套代码中的示例覆盖了众多Python的主题,包括但不限于变量、数据类型、条件语句、循环语句、函数、类与对象、异常处理、文件操作等。通过编写和运行这些代码示例,读者能够提升对Python语言的理解和掌握,并能够逐步将所学知识应用到实际项目中。 配套代码通常以.py文件的形式提供,读者可以通过Python的解释器执行这些文件,观察代码运行结果,以加深对代码的理解。同时,配套代码中也包含了一些示例程序的示意图或结果截图,帮助读者更加直观地理解代码的作用和效果。 总之,《Python编程入门实践》配套代码的存在是为了帮助读者更好地理解和实践书中的知识,并通过编写和运行代码来提升Python编程能力。读者可以按照书中的章节顺序逐步学习和实践,同时也可以自由选择感兴趣的章节进行阅读和实践。 ### 回答2: 《Python编程入门实践》是一本以Python编程为主题的教材,旨在通过实践帮助初学者掌握Python编程的基础知识和实践技巧。配套代码是书中提供的与各章节内容相对应的示例代码,用于帮助读者理解和实践书中所介绍的概念和技术。 配套代码通常包括了书中所有示例程序的源代码文件,以及配套的数据文件和其他必要的资源文件。这些代码文件可以用于在本地环境中运行和调试,并通过实际的编码练习来巩固和实践所学的知识。 使用配套代码可以提供以下好处: 1. 实践编程技巧:通过自己实际动手编写和运行代码,加深对Python编程语言和相关工具的理解和熟悉程度。 2. 加深理解:通过观察和分析书中示例代码的各个部分,以及运行代码的结果,可以更好地理解和掌握Python编程的原理和应用。 3. 自我验证:通过与书中示例代码进行对比,可以验证自己的编码是否正确,从而及时纠正和改进自己的编程技能。 在使用配套代码时,建议读者: 1. 逐章阅读:按照书中的章节顺序,先阅读理解章节内容,再运行和分析对应的代码示例,这样可以更好地跟上整个学习进度。 2. 分步实践:不要一开始就把整个代码文件全部复制并运行,而是要逐步实践每个示例的代码,理解每个代码块的功能和作用。 3. 自主思考:在实践时可以尝试修改和扩展代码,观察不同的运行结果,从而提升对Python编程的理解和创造力。 总之,《Python编程入门实践》配套代码是学习此书的重要辅助资料,可以帮助读者更好地理解和掌握Python编程的基础知识和实践技巧。通过实际动手编码,读者可以加深对书中所介绍内容的理解,并通过自主思考和实践,进一步提升编程能力。 ### 回答3: 《Python编程入门实践》是一本非常受欢迎的Python编程学习教材,对于入门学习Python的学习者来说是一本很好的选择。这本书配套的代码可以帮助读者巩固课本上的知识,通过实践来加深对Python编程的理解和运用。 配套代码包括了书中各章节的实例代码和练习代码,以及一些扩展案例。通过使用这些代码,读者可以实时地运行并观察代码的输出结果,从而更好地理解Python编程的概念和语法。 对于初学者来说,通过运行代码并观察输出结果可以帮助加深对Python语法和逻辑的理解。通过自己动手修改代码并实验不同的情况,可以帮助读者思考问题并找到解决问题的方法。这种实践的学习方式可以提高编程能力,并培养解决问题的能力。 此外,配套代码还可以帮助读者快速查找和复习书中的内容。由于代码是按照书中章节的顺序组织的,读者可以直接找到自己所在的章节,方便地运行代码并进行实践。 总之,《Python编程入门实践》配套代码是一份宝贵的资源,可以帮助读者更好地学习和实践Python编程。读者可以通过将代码和课本内容结合起来,从而更好地理解和掌握Python编程的知识,并能够熟练地运用到实际项目中。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值