python编程从入门到实践(课本学习代码(2-6章))

本次上传的代码为2-6章的。用‘.’的标号是课本内的代码,用‘-’的标号是课后习题
2.2

message = 'hello python world!'
print(message.title())#每个单词首字母大写

message = 'hello python crash course world!'
print(message.title())

mesage = 'hello python crash course reader!'
print(mesage.title())

2.3

#字符串
name = 'toms jobs'
print(name.title())

name = 'Alan Walker'
print(name.upper())#所有字母都大写
print(name.lower())#所有字母都小写


first_name = 'alan'
last_name = 'walker'
name = first_name.title() +' '+ last_name.title()
print(name)
print('Hello!'+ name)

#使用制表符和换行符来添加空白
print('python')

print('language:\npython\nc\njava')#使用/n来进行换行

print('language:\n\tpython\n\tc\n\tjava')#使用/t来进行tab制表符

#删除空白

language = 'python '
print(language.rstrip())#去除字符串右边空白

language = ' python'
print(language.lstrip())#去除字符串左边空白

language = ' python '
print(language.strip())#去除首尾空白

2.4

#数字

age = 23
message = 'Happy ' + str(age) + 'rd Birthday!'#使用str()函数使数字成字符串表达
print(message)

print(2 + 3)
print(3 / 2)


#python 之禅
import this

3.1

#列表

bicycles = ['trek','cannondale','realine','specialized']#列表的输出
print(bicycles)

#访问列表元素
bicycles = ['trek','cannondale','realine','specialized']
print(bicycles[0].title())#索引从0开始
print(bicycles[2].title())

message = 'my favorite bicycle is ' + bicycles[3].title() +  '!'
print(message.title())

3.2

#修改列表元素

motorcycles = ['honda','yamaha','suzuki','hanlanda']
print(motorcycles)

motorcycles[1] = 'ducati'#修改列表中的元素
print(motorcycles)

print('=======================================')
#在列表中添加元素
motorcycles = ['honda','yamaha','suzuki','hanlanda']
print(motorcycles)

motorcycles.append('ducati')#将元素添加到列表的末尾
print(motorcycles)

print('======================================')
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaba')
motorcycles.append('suzuki')
print(motorcycles)
print('======================================')
#在列表中插入元素
motorcycle = ['honda','yamaha','suznki']

motorcycle.insert(0,'ducati')
print(motorcycle)

print('======================================')
#从列表中删除元素
motorcycles = ['honda','yamaha','suznki']
print(motorcycles)

del motorcycles[0]
print(motorcycles)
print('======================================')
#使用pop删除元素
motorcycles = ['honda','yamaha','suznki']
print(motorcycles)

popped_motorcycle = motorcycles.pop()#删除列表中的尾元素
print(motorcycles)
print(popped_motorcycle)#输出删除的元素

print('======================================')
#弹出列表中任何位置的元素
motorcycles = ['honda','yamaha','suznki']
print(motorcycles)

popped_motorcycle = motorcycles.pop(0)#删除列表中索引为0的元素
print(motorcycles)
print('The first motorcycle I wanna ' + popped_motorcycle + ' .')#输出删除的元素

print('======================================')
#根据值删除元素

motorcycles = ['honda','yamaha','suzuki','hanlanda']
print(motorcycles)

motorcycles.remove('hanlanda')
print(motorcycles)


print('************************************')
print('======================================')

#动手试一试
name_list = []
name_list.append('tom')
name_list.append('jobs')
name_list.append('bill')
name_list.append('jack')
name_list.append('andy')

print('I am so sorry! ' + name_list[1].title() + " don't join this party!")
print(len(name_list))
#修改名单
del name_list[1]
# print(name_list)
name_list.insert(1,'jordan')
print(name_list)
print('Because of find a big dask , so we will add costoms .')
print(len(name_list))
#添加嘉宾
name_list.insert(1,'rose')
name_list.insert(3,'lily')
name_list.append('pig')
print(name_list)
print('Dear ' + name_list[1].title() + ' , welcome to my party !')
print('Dear ' + name_list[3].title() + ' , welcome to my party !')
print('Dear ' + name_list[7].title() + ' , welcome to my party !')
print(len(name_list))
#缩减名单

print('I am so sorry! ' + ' cause a lot problem , we eat dinner with two custom !')

del_name = name_list.pop(1)
print('GO out !' + del_name.title() + '.')
print(name_list)

del_name = name_list.pop(2)
print('GO out !' + del_name.title() + '.')
print(name_list)

del_name = name_list.pop(1)
print('GO out !' + del_name.title() + '.')
print(name_list)

del_name = name_list.pop(2)
print('GO out !' + del_name.title() + '.')

del_name = name_list.pop(2)
print('GO out !' + del_name.title() + '.')

del_name = name_list.pop(2)
print('GO out !' + del_name.title() + '.')

print(name_list)
print(len(name_list))
print('Celebrate ' + name_list[0].title() + ' successful !')
print('Celebrate ' + name_list[1].title() + ' successful !')

del name_list[0]
del name_list[0]
print(name_list)
print(len(name_list))

3.3

#组织列表

#使用sort()对列表进行永久性排序

cars = ['bmw','audi','toyota','auto']
cars.sort()#按照字母顺序进行排序
print(cars)

print('=============================')
cars = ['bmw','audi','toyota','auto']
cars.sort(reverse=True)#按照字母反向顺序进行排序
print(cars)

print('=============================')

#使用sorted()对列表进行临时排序
cars = ['bmw','audi','toyota','auto']
print('Here is the original list:')
print(cars)

print('Here is the sorted list:')
print(sorted(cars))

print('Here is the original list again:')
print(cars)

#倒着打印列表
print('=============================')
cars = ['bmw','audi','toyota','auto']
print(cars)

cars.reverse()
print(cars)

#打印列表长度
print('=============================')
cars = ['bmw','audi','toyota','auto']
print(len(cars))

4.1

#遍历整个列表

magicians = ['alice','david','carolian']
for magician in magicians:
    print(magician.title())
    print(magician.title() + ', that was a great trick!'+'\n')#循环一次还一行
print("Thank you , everyone.That was a great magic show!")

4.3

#创建数值列表

for value in range(1,10):
    print(value)#生成1-9的数值


#使用range()创建数值列表

numbers = list(range(1,10))
print(numbers)

#指定步长输出
even_numbers = list(range(1,10,2))#输出步长为2的数值列表
print(even_numbers)

squares = []
for value in range(1,11):
    square = value**2
    squares.append(square)
    #squares.append(value**2)
print(squares)

print('===================================')
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))#最小值
print(max(digits))#最大值
print(sum(digits))#和

#列表解析
squares = [value**2 for value in range(1,11)]#用for循环为前面的式子提供值
print(squares)

#动手试一试
for i in range(1,21):
    print(i)

#4-5
import time
start = time.clock()
value = [i for i in range(1,1000000)]
print(value)
print(min(value))
print(max(value))
print(sum(value))
end = time.clock()
time = end - start
print('Running time:'+ str(time))

#4-6
import time
start = time.clock()
value = [i for i in range(1,1000000,2)]
print(value)
print(min(value))
print(max(value))
print(sum(value))
end = time.clock()
time = end - start
print('Running time:'+ str(time))

#4-7
value = [i for i in range(3,31,3)]
print(value)

#4-8,4-9
value = [i**3 for i in range(1,11)]
print(value)


4.5

#元组

#定义元组

dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])#打印元组中的值

#元组中的值是不可以修改的
#dimensions[0] = 230



#遍历元组中的所有值
for dimension in dimensions:
    print(dimension)


#虽然无法修改元组中的值,但可以给存储元组的变量赋值
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)


dimensions = (400,100)
print("Modified dimensions:")
for dimension in dimensions:
    print(dimension)

4-4

#使用列表中的一部分元素
#切片

players = ['charles','martina','michael','florence','eli']
print(players[0:3])#打印列表的前三个,索引为0,1,2的值

print(players[1:4])#打印列表中索引为1,2,3的值

#如果没有指定第一个索引值,将从列表的的开头开始
print(players[:4])

#如果没有指定尾索引,将遍历到列表的末尾
print(players[2:])

#输出特定的列表尾值
print(players[-3:])#从倒数第三个值开始输出


#遍历切片
print("Here are the first there playerd on my team:")
for player in players[:3]:
    print(player.title())


#列表的复制
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]#把列表中的所有值复制到另一个列表

my_foods.append('cannoli')
friend_foods.append('ice cream')
#friend_foods = my_foods这里是将后面的列表赋给前面的列表,打印的两个值相同

print("My favorite foods are:")
print(my_foods)
print("My friends favorite foods are:")
print(friend_foods)


5.1

#一个简单的实例

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

5.2

#赋值与相等运算符
car = 'bmw'#赋值
if car =='bmw':#相等
    print('Ture')
else:
    print('Flase')

#赋值与相等运算符要考虑大小写
car = 'Bmw'
if car =='bmw':
    print('Ture')
else:
    print('Flase')


#数值的比较
age = 12
if age != 34:
    print('Please try again!')


#使用and和or来进行多个条件的检查

age_0 = 18
age_1 = 78
if age_0 <= 20 and age_1 >= 70:
    print('Ture')
else:
    print('Flase')


#检查特定值是否在列表中
cars = ['audi','bmw','toyota','subaru']
if 'bmw' in cars:
    print('Ture')
else:
    print('Flase')

#检查特定值是否不在列表中
cars = ['audi','bmw','toyota','subaru']
car = 'auto'
if car not in cars:
    print('Sorry!,please go out')
    cars.append(car)
    print(cars)



#布尔表达式的运用
game_activity = True
can_edit = False



#5-1

5.4

#使用if语句处理列表

bags = ['mushrooms','green peppers','extra cheese']
for bag in bags:
    print('Adding '+ bag + '.')
print('\nFinshed your pizza!')

print('=========================')
print()
######
bags = ['mushrooms','green peppers','extra cheese']
for bag in bags:
    if bag == 'mushrooms':
        print("Sorry! We are out of mashrooms right now.")
    else:
        print('Adding '+ bag + '.')
print('\nFinshed your pizza!')


print('============================')
print()
#确定列表不是空
bags = []
if bags:
    for bag in bags:
        print('Adding ' + bag + '.')
        print('\nFinshed your pizza!')
else:
    print('Are you sure want a plain pizza.')


print('============================')
print()
#5-8
name_list = ['tom','lily','jack','bob','admin']
for name in name_list:
    print('Wlecome '+ name +'.')
    if name == 'admin':
        print('Hello admin,would you like ti see a status report!')
    else:
        print('Hello Eric,think you for logging again!')



print('============================')
print()
#5-10
users = ['tom','lily','jack','bob','admin']
new_users = ['a','b','c','tom','bob']
for user in users:
    for user1 in new_users:
        if user1 == user:
            print('This name ready user!')
        else:
            print('PASS')

print('============================')
print()
#5-11
numbers = [1,2,3,4,5,6,7,8,9]
for number in numbers:
    if number == 1:
        print('%dst'%number)
    elif number == 2:
        print('%dnd'%number)
    elif number == 3:
        print('%drd'%number)
    else:
        print('%dth'%number)

5-3

#if 语句
age = 23
if age >=20:
    print('Victory')


#if-elif-else语句
age =int(input('Please input age: '))
if age<= 4 and age>=0:
    print('You admision cost is $0.')
elif age >4 and age <= 18:
    print('You admision cost is $5.')
elif age>18 and age <200:
    print('You admision cost is $10.')
else:
    print('You are evil.')

#输入三个数,然后从小到大输出
value = []
for i in range(4):
    x = int(input('输入:\n'))
    value.append(x)
value.sort()
print(value)

#输出9*9乘法表
for i in range(1,10):
    print()
    for j in range(1,i+1):
        m = i * j
        print('%d*%d=%d'%(i,j,m)),

#暂停一秒钟输出
import time
myD = {1: 'a', 2: 'b'}
for key, value in dict.items(myD):
    print (key, value)
    time.sleep(1) # 暂停 1 秒


#古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
f1 = 1
f2 = 1
for i in range(1,22):
    print ('%12ld %12ld' % (f1,f2),)
    if (i % 3) == 0:
        print ('')
    f1 = f1 + f2
    f2 = f1 + f2

#5-3
alien_color = ['green','red','yellow']
if 'green' in alien_color:
    print('You have 5 point.')
else:
    print('NO!')

6.1

#字典
alien = {'color':'green','points':'5'}
print(alien['color'])
print(alien['points'])

6.2

#字典的使用
#访问字典中的值
alien = {'color':'red',
         'points':'10'}
point = alien['points']
print(alien['color'])
print('You just earned '+ str(point)+" point.")

print()
print('====================================')
#添加键-值对
alien = {'color':'red',
         'points':'10'}
print(alien)
alien['x_position'] = 0
alien['y_position'] =25
print(alien)

#创建空字典
alien={}
alien['color'] = 'green'
alien['points'] = 100
alien['x_position'] = 0
alien['y_position'] =25
print(alien)


#修改字典中的值
alien_0 = {'color':'yellow'}
print('The alien is '+alien_0['color']+'.')

alien_0['color'] = 'red'#改变了值
print('The alien is now '+alien_0['color']+'.')

print()
print('====================================')

alien = {'x_p':0,'y_p':23,'speed':'medium'}
print("Original x_p:"+str(alien['x_p']))

alien['speed'] = input('speed:')
#向右移动
#根据速度移动
if alien['speed'] == 'slow':
    x_i = 1
elif alien['speed'] == 'medium':
    x_i = 2
elif alien['speed'] == 'fast':
    x_i = 3

alien['x_p'] = alien['x_p'] + x_i
print("New x_p:"+str(alien['x_p']))


#删除键-值对(永远删除)

alien = {'color':'red',
         'points':'10'}
print(alien)

del alien['points']
print(alien)


#6-1
messages = {'first_name':'li','last_name':'ming','age':23,'city':'kunming'}
print('Name:'+messages['first_name'].title()+messages['last_name'].title()+' age:'+str(messages['age'])+' City:'+messages['city'].title())

#6-2
numbers = {'tom':23,'jack':34,'bob':21,'jobs':54,'worker':65}
print(numbers)



6.3

#遍历字典

user = {'username':'efermi',
        'first':'enrico',
        'last':'fermi'}

for key,value in user.items():
    print("\nKey: "+key.title())
    print("Value: "+value.title())

#遍历字典中的所有键

languages = {'jen':'python',
             'sarch':'c',
             'edward':'ruby',
             'phli':'python'}

print()
friends = ['jen','phli']
for name in languages.keys():
    print(name.title())
    if name in friends:
        print(" Hi "+name.title()+", I see you favorite language is "+languages[name].title()+'!')

print()
#遍历所有值
for language in languages.values():
    print(language.title())


#运用set()来剔除重复项
languages = {'jen':'python',
             'sarch':'c',
             'edward':'ruby',
             'phli':'python'}

print('The following languages have been mentioned:')
for language in set(languages.values()):#踢出了重复项python
    print(language.title())

6.4

#嵌套(将一系列的字典储存在列表中,或将一系列的列表储存在字典中)
alien_0 = {'color':'green','points':2}
alien_1 = {'color':'yellow','points':4}
alien_2 = {'color':'red','points':5}

aliens = [alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)



#简单小实例

print('=================================')
print()
#创建一个用于存储外星人的列表
aliens = []

#创建30个外星人
for alien_number in range(30):
    new_alien0 = {'color':'green','points':45,'speed':'slow'}
    new_alien1 = {'color':'red','points':21,'speed':'fast'}
    aliens.append(new_alien0)
    aliens.append(new_alien1)

#显示前5个外星人
for alien in aliens[:5]:
    print(alien)
print('..........')

#显示创建了多少个外星人
print('Total number of aliens: '+str(len(aliens)))




print()
print('=================================================')
#在字典中储存列表
pizza = {'crust':'thick',
         'toppings':['mushrooms','extra cheese']}

print('You ordered a '+pizza['crust']+'-crust pizza '+'with the following toppings.')
for topping in pizza['toppings']:
    print(topping)



print()
print('=================================================')

languages = {'jen':['python','ruby'],
             'sarah':['c'],
             'edward':['ruby','go'],
             'phli':['python','haskell']}
for name ,language in languages.items():
    print('\n'+name.title()+"'s favorite language are:")
    for lang in language:
        print('\t'+lang.title())

感谢阅览!!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值