蓝桥杯Python B组练习——python复习2

蓝桥杯Python B组练习——python复习2

一、简介

复习python,参考书《Python编程从入门到实践》,[美]Eric Mathes著。前一部分见专栏——蓝桥杯Python B组练习

这一部分不全,不想写了

二、字典

1.一个简单的字典

来看一个游戏,其中包含一些外星人,这些外星人的颜色和点数各不相同。下面是一个简单的字典,存储了有关特定外星人的信息:

alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])

运行结果:

green

5

2.使用字典

在Python中,字典是一系列键-值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。

在Python中,字典用放在花括号{}中的一系列键-值对表示,如下:

alien_0={'color':'green','points':5}

键值对是两个相关联的值。指定键是Python将返回与之相关联的值。键和值之间用冒号分隔,而键值对之间用逗号分隔。

1)访问键值对

print(alien_0['color'])

2)添加键值对

alien_0={'color':'green','points':5}
alien_0['x_position']=0
alien_0['y_position']=0
print(alien_0)

运行结果:

{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 0}

3)先创建一个空字典

有时候,在空字典中添加键值对是为了方便,而有时候必须这样做。

alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)

运行结果:

{'color': 'green', 'points': 5}

4)修改字典中的值

alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
alien_0['color']='yellow'
print(alien_0)

运行结果:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 5}

5)删除键值对

对于字典中不再需要的信息,可使用del语句将相应的键值对彻底删除。使用del语句时,必须指定字典名和要删除的键。

alien_0={'color':'green','points':5}
print(alien_0)

del alien_0['points']
print(alien_0)

运行结果:

{'color': 'green', 'points': 5}
{'color': 'green'}

3.遍历字典

1)遍历所有的键值对

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

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

如上所示,编写for循环,可声明两个变量,用于存储键值对中的键和值。对于这两个变量,可使用任何名称。

如:for k,v in user_0.items()

运行结果:

Key:username
Value:efermi

Key:first
Value:enrico

Key:last
Value:fermi
2)遍历字典中的所有键

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

for k in user_0.keys():
    print(k.title())

运行结果:

Username
First
Last

还可以使用keys()确定某个键是否在keys中。

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

if 'second_name' not in user_0.keys():

方法keys()并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键。

运行结果:

Please take out poll

3)按顺序遍历字典中的所有键

要以特定的顺序返回元素,一种办法是在for循环中返回的键进行排序。为此,可使用函数sorted()来获得按特定顺序排序的键列表的副本:

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

for k in sorted(user_0.keys()):
    print(k.title())

运行结果:

First
Last
Username

4)遍历字典中的所有值

如果你感兴趣的主要是字典包含的值,可使用方法values(),它返回一个值列表,而不包含任何键。

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

for v in user_0.values():
    print(v.title())

运行结果:

Efermi
Enrico
Fermi
 

这样的做法提取字典的所有值,而没有考虑是否重复。为剔除重复项,可使用集合(set)。集合类似于列表,但每一个元素都必须是独一无二的:

favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

for language in set(favorite_languages.values()):
    print(language.title())

运行结果:

C
Python
Ruby


4.嵌套

有时候,需要将一系列字典存储在列表中,或者将列表作为值存储在字典中,这称为嵌套。

1)字典列表

alien_0 ={'color':'green','points':5}
alien_1 ={'color':'yellow','points':10}
alien_2 ={'color':'red','points':15}

aliens=[alien_0,alien_1,alien_2]

for alien in aliens:
    print(alien)

运行结果:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

2)在字典中存储列表

有时候需要将列表存储在字典中,而不是将字典存储在列表中。

#存储所点披萨的信息
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("\t"+topping)

运行结果:

You ordered athick-crust pizzawith the following toppings:
    mushrooms
    extra cheese

3)在字典中存储字典

users = {
    'aeinstein':{'first':'albert',
                 'last':'einstein',
                 'location':'princeton',
                 },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
    },   
}

for username,user_info in users.items():
    print("\nUsername:"+username)
    full_name=user_info['first']+" "+user_info['last']
    location = user_info['location']

    print("\tFull name:"+full_name.title())
    print("\tLocation:"+location.title())

运行结果:

Username:aeinstein
    Full name:Albert Einstein
    Location:Princeton

Username:mcurie
    Full name:Marie Curie
    Location:Paris


三、用户输入和while循环

1.函数input()的工作原理

函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。

name=input("Please enter your name:")
print("Hello,"+name+"!")

运行结果:

Please enter your name:Eric
Hello,Eric!

1)使用int()来获取数值输入

age=input("How old are you?")
age>=18

如上,用户输入的是数字21,但我们请求Python提供变量age时,它返回的是‘21’——用户输入的数值的字符串表示。如果试图将输入作为数字使用,就会引发错误:

为解决这个问题,可以用函数int()

age=input("How old are you?")
age=int(age)
if age>=18:
    print("True")

运行结果:

2)求模运算符

处理数值信息时,求模运算符(%)是一个很有用的工具,它将两个数相除并返回余数:

print(4%3)
print(5%3)
print(6%3)
print(7%3)

运行结果:

1
2
0
1

2.while循环简介

1)使用while循环

使用while循环来数数,例如,下面的while循环从1数到5:

current_number=1
while current_number <=5:
    print(current_number)
    current_number+=1

运行结果:

1
2
3
4
5

2)让用户选择何时退出

prompt =  "\nTell me something,and I will repeat it back to you:"
prompt=prompt+"\nEnter 'quit' to end the program."
message=""
while message !='quit':
    message=input(prompt)
    print(message)

运行结果:

Python首次执行while语句时,需要将message的值与‘quit’进行比较,但此时用户还没有输入。如果没有可供比较的东西,Python将无法继续运行程序。为解决这个问题,我们必须给变量message指定一个初始值。虽然这个初始值只是一个空字符串,但符合要求,让Python能够执行while循环所需的比较。只需要message的值不是‘quit’,这个循环就会不断运行。

3)使用标志

在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志。充当了程序的交通信号灯。你可让程序在标志为True时继续运行,并在任何事件导致标志值为False时让程序停止运行。

prompt =  "\nTell me something,and I will repeat it back to you:"
prompt=prompt+"\nEnter 'quit' to end the program."
active = True
while active:
    message=input(prompt)

    if message == 'quit':
        active = False
    else:
        print(message)

运行结果:

4)使用break退出循环

要立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用break语句。

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"

while True:
    city=input(prompt)

    if city == 'quit':
        break
    else:
        print("I'd love to go to"+city.title()+"!")

运行结果:

注意:在任何循环中都可使用break语句。例如,可使用break语句来退出遍历列表或字典的for循环。

5)在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。

prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"

while True:
    city=input(prompt)

    if city == 'quit':
        continue
    else:
        print("I'd love to go to"+city.title()+"!")

运行结果:

如运行结果显示,陷入无限循环,无法跳出循环,我们应该避免无限循环。如果程序陷入无限循环,可按Ctrl+C,也可关闭显示程序的终端窗口。

3.使用while循环来处理列表和字典

1)在列表之间移动元素

unconfirmed_users=['alice','brian','candace']
confirmed_users=[]

while unconfirmed_users:
    current_user = unconfirmed_users.pop()

    print("Verifying user:"+ current_user.title())
    confirmed_users.append(current_user)

print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

运行结果:

2)删除包含特定值的所有列表元素

我们使用函数remove()来删除列表中的特定值,这之所以可行,是因为要删除的值在列表中值出现了一次。

假设你有一个宠物列表,其中包含多个值为’cat‘的元素。要删除所有这些元素,可不断运行一个while循环,直到列表中不再包含值’cat‘,如下所示:

pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

运行结果:

3)使用用户输入来填充字典

responses = {}

polling_active = True

while polling_active:
    name = input("\nWhat is your name?")
    response = input("Which mountain would you like to climb someday?")

    responses[name] = response

    repeat = input("Would you like to let another person respond?(yes/no)")
    if repeat == 'no':
        polling_active = False
print("\n--------Poll Result------")
for name,response in responses.items():
    print(name+"would like to climb"+response+".")

运行结果:

四、函数

1.定义函数

下面是一个打印问候语的简单函数,名为greet_user():

def greet_user():

        print("Hello!")

greet_user()

第一行的代码使用关键字def来告诉Python你要定义一个函数。这是函数定义,向Python指出了函数名。第二行函数体,第三行执行函数,打印Hello!

1)向函数传递信息

def greet_user(username):
    print("Hello!"+username.title()+"!")

greet_user('jesse')

运行结果:

Hello!Jesse!

2.传递实参

向函数传递实参的方式很多,可使用位置实参这要求实参的顺序与形参顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成

1)位置实参

def descirbe_pet(animal_type,pet_name):
    print("\nI have a "+animal_type+".")
    print("My" + animal_type+"'s name is"+pet_name.title()+".")

descirbe_pet('hamster','harry')

运行结果:

注意:位置实参的顺序很重要

2)关键字实参

关键字实参是传递函数的名称-值对。

def descirbe_pet(animal_type,pet_name):
    print("\nI have a "+animal_type+".")
    print("My" + animal_type+"'s name is"+pet_name.title()+".")

descirbe_pet(animal_type='hamster',pet_name='harry')

运行结果:

3)默认值

编写函数时,可给每个形参指定默认值。

def descirbe_pet(pet_name,animal_type='dog'):
    print("\nI have a "+animal_type+".")
    print("My" + animal_type+"'s name is"+pet_name.title()+".")

descirbe_pet(pet_name='harry')

运行结果:

注意:使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的形参。

这让Python依然能够正确地解读位置实参。

3.返回值

函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。

1)返回简单值

def get_formatted_name(first_name,last_name):
    full_name=first_name+' '+last_name
    return full_name.title()

musician = get_formatted_name('jimi','hendrix')
print(musician)

    运行结果:

Jimi Hendrix

2)让实参变成可选的

并非所有人都有中间名,为让中间名变成可选的,可采用如下:

def get_formatted_name(first_name,last_name,middle_name=''):
    full_name=first_name+' '+middle_name+' '+last_name
    return full_name.title()

musician = get_formatted_name('jimi','hendrix')
print(musician)

musician = get_formatted_name('john','hooker','lee')
print(musician)

    给实参middle_name指定一个默认值——空字符串,并在用户没有提供中间名时不使用这个实参。为让get_formatted_name()在没有提供中间名时依然可以运行,可给实参middle_name指定一个默认——空字符串,并将其移到形参列表末尾。

运行结果:

3)返回字典

def build_person(first_name,last_name):
    person = {'first':first_name,'last':last_name}
    return person

musician = build_person('jimi','hendrix')
print(musician)

运行结果:

{'first': 'jimi', 'last': 'hendrix'}

4)结合使用函数和while循环

def get_formatted_name(first_name,last_name):
    full_name = first_name+' '+last_name
    return full_name.title()

while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")

    f_name = input("First name: ")
    if f_name == 'q':
        break

    l_name = input("Last name:")
    if l_name == 'q':
        break
    formatted_name = get_formatted_name(f_name,l_name)
    print("\nHello,"+ formatted_name+"!")

运行结果:

4.传递列表

假设有一个用户列表,我们要问候其中的每位用户。下面示例将一个名字列表传递给一个名为greet_users()的函数,这个函数问候列表中的每个人:

def greet_uers(names):
    for name in names:
        msg = "Hello, "+name.title()+"!"
        print(msg)
usernames=['hannah','ty','margot']
greet_uers(usernames)

运行结果:

5.传递任意数量的实参

函数只有一个形参*toppings,不管调用语句提供了多少实参,这个形参都将它们统统收入囊中:


def make_pizza(*toppings):
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

运行结果:

('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

1)结合使用位置实参和任意数量实参

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后

def make_pizza(size,*toppings):
    print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")
    for topping in toppings:
        print("- "+topping)

make_pizza(16,'pepperoni')
make_pizza(20,'mushrooms','green peppers','extra cheese')

运行结果:

2)使用任意数量的关键字实参

有时候,需要接受任意数量的实参,但预先不知道传递给函数的是什么样的信息。

在下面的实例中,函数build_profile()接受名和姓,同时还接受任意数量的关键字实参:

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('albert','einstein',location='princeton',field='physics')

print(user_profile)

运行结果:

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

6.将函数存储在模块中

五、类

1.创建和使用类

使用类几乎可以模拟任何东西。

 1)创建Dog类

class Dog():
    def __init__(self,name,age):
        self.name=name
        self.age=age
        
    def sit(self):
        print(self.name.title()+"is now sitting.")
    def roll_over(self):
        print(self.name.title()+"rolled over!")

类中的函数称为方法;前面学的有关函数的一切都适用于方法,就目前而言,唯一重要的差别是调用方法的方式。__init__()是一个特殊的方法,每当你根据Dog类创建新实列时,Python都会自动运行它。在这个方法的名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生的名称冲突。__init__()中包含了三个形参:self、name和age。在这个方法的定义中,形参self必不可少,还必须位于其他形参前面。

2)根据类创建实例

1.访问属性

my_dog.name

class Dog():
    def __init__(self,name,age):
        self.name=name
        self.age=age

    def sit(self):
        print(self.name.title()+"is now sitting.")
    def roll_over(self):
        print(self.name.title()+"rolled over!")

my_dog = Dog('willie',6)

print("My dog's name is"+my_dog.name.title()+'.')
print("My dog is"+str(my_dog.age)+"years old.")

运行结果:

My dog's name isWillie.
My dog is6years old.

2.调用方法

my_dog.sit()

  • 20
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值