Python从入门到实践 学习记录3

1.if语句

#检查多个条件
>>>(age_0>=21)and(age_1>=21)
>>>(age_0>=21)or(age_1>=21)

#检查特定值是否在列表中
>>>requested_topping = 'mushroom'
>>>'mushrooms' in requested_toppings
True
>>>'mushroom' not in requested_toppings
False
>>>requested_topping in requested_toppings
True

#####
age=12
if age < 4:
    do something
elif age < 18:
    do something
else:
    do something # else 代码块可省略

2.字典

在Python中,字典是一系列键值对,在字典中,想存储多少个键值对都可以。

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

#添加键值对
alien_0['x_position'] = 0
alien-0['y_position'] = 25

#创建空字典
alien_0 = {}

#删除键值对
del alien_0['points']

#使用get()来访问值
point_value = alien_0.get('point','No point value assigned.')
print(point_value)

#遍历字典
for k, v in user_0.items():

#遍历字典中所有的键
for name in favorite_languages.keys():
#或者
for name in favorite_languages:

if 'erin' not in favorite_languages.keys():

#按特定顺序遍历字典中所有的键
for name in sorted(favorite_languages.keys()):

#遍历字典中所有的值
for language in favorite_languages.values():
for language in set(favorite_languages.values()):#剔除重复项

#集合
>>>languages={'python','ruby','python','c'}
>>>languages
{'ruby','python','c'}

#嵌套
#列表中存储字典
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]

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

#字典中存储字典
users = {
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton',
        },

    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
        },
    }
    

2.用户输入和while循环

#input()输入解读为字符串
message = input("Tell me something, and I will repeat it back to you:")
print(message)

#int()字符串转换为数值
age = imput("How old are you?")
age = int(age)
age > 18

Out:True

#求模
number % 2

#while循环
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."

active = True
while active:
    message = input(prompt)

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

#break,continue

#使用while循环处理列表和字典
while unconfirmed_users:  #字典
    do something

while 'cat' in pets:      #列表
    do something          

#使用用户输入来填充字典
responses = {}
polling_active = True
while polling_active:
    name = input("\nWhat is your name? ")
    response = input("\nWhich mountain would you like to climb someday?" )
    responses[name] = response
    
    do something
        polling_active = False

3.函数

#定义函数
def greet_user():
    print("Hello!")
greet_user()

#传递实参
def describe_pet(animal_type,pet_name):  #位置实参
def describe_pet(animal_type='hamster',pet_name='harry'):  #关键字实参
def describe_pet(pet_name,animal_type='dog'):  #默认值

#等效的函数调用
descride_pet('willie')
describe_pet(pet_name='willie')

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

#返回简单值
def get_formatted_name(first_name,last_name):
    full_name=f"{first_name}{last_name}"
    return full_name.title()

#让实参变成可选的
def get_formatted_name(first_name,middle_name,last_name):#同时提供 名,中间名,姓
    do something

def get_formatted_name(first_name,last_name,middle_name=''):#同时提供 名,中间名,姓
    if middle_name:
        full_name=f"{first_name} {middle_name} {last_name}" #或仅提供 名,姓
    else:
        full_name=f"{first_name} {last_name}"

#返回字典
def build_person(first_name,last_name):
    person={'first':first_name,'last':last_name}
    return person

#传递列表
def greet_users(names):
    for name in names:
        msg=f"Hello,{name.title()}!"
        print(msg)

usernames=['hannah','ty','margot']
greet_users(usernames)

#在函数中修改列表
def print_models(unprinted_designs,completed_models):
    while unprinted_designs:
        current_design=unprinted_designs.pop()
        print(f"Printing model:{current_design}")
        completed_models.append(current_design)

def show_completed_models(completed_models):
    do something……
    for completed_model in completed_models:
        print(completed_model)

#禁止函数修改列表,采用列表切片
function_name(list_name[:])

#传递任意数量的实参(封装到元组)
def make_pizza(*toppings):
    print(toppings)

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

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

#结合使用位置实参和任意数量实参
def make_pizza(size,*toppings):
    ……
make_pizza(16,'pepperoni)
make_pizza(12,'mushrooms','green peppers','extra cheese')

#使用任意数量的关键字实参
def build_profile(first,last,**user_info):
    user_info['first_name']=first
    user_info['last_name']=last
    return user_info

user_profile=build_profile('albert','einstein',
                            location='princeton',
                            field='physics')
print(user_profile)

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

#导入整个模块
import pizza  #pizza.py
pizza.function_name(……)  #使用pizza模块中的函数

from pizza import function_name  #导入pizza模块中特定的函数
funcyion_name(……)  #直接使用函数

#使用as给函数指定别名
from pizza import make_pizza as mp

#使用as给模块指定别名
import pizza as p

#导入模块中所有的函数(一般不用)
from pizza import *  #导入pizza module中所有的函数

#给形参指定默认值时,等号两边不要有空格
#函数调用中的关键字实参,等号两边也不要有空格
    

4.类

类中的函数称为方法。

#创建一个名为Dog的类
class Dog:
    """一次模拟小狗的简单尝试。"""

    def __init__(self,name,age):
        """初始化属性name和age"""
        self.name = name
        self.age = age

    def sit(self)
        """模拟小狗收到命令时蹲下。"""
        print(f"{self.name} is now sitting.")

    def roll_over(self):
        """模拟小狗收到命令时打滚。"""
        print(f"{self.name} rolled over!")

#根据类创建和访问实例
my_dog = Dog('Willie',6)
your_dog = Dog('Lucy',3)  #创建不同的实例
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()
my_dog.roll_over()

#继承(super()是一个特殊的函数,让你能够调用父类的方法)
class Car:
    """……"""

    def __init__(self,make,model,year)
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0
        ……

    ……

class ElectricCar(Car)  #继承Car类
    """电动汽车的独特之处。"""

    def __init__(self,make,model,year):
        """
        初始化父类的属性。
        再初始化电动汽车特有的属性。
        """
        super()._init_(make,model,year) #该行代码让Python调用Car类的方法_init_()
        self.battery_size = 75          #ElectricCar包含此方法中定义的所有属性

    def ……
#可重写父类的方法

#添加Battery类,将一个Battery实例作为ElectricCar类的属性
class ElectricCar(Car):
    """……"""

    def __init__(self,make,model,year)
        """
        ……
        ……
        """

        super()._init_(make,model,year)
        self.battery = Battery()

    ……


my_tesla = ElectricCar('tesla','model s',2019)
my_tesla.battery.describe_battery()  #describe_battery()是Battery类中的一个函数



5.Python标准库

模块random:i)randint(),随机返回位于两个整数之间的一个整数;ii)choice(),随机返回一个列表或元组中的一个元素。

>>>from random import randint
>>>randint(1,6)
3

>>>from random import choice
>>>players = ['charles','matina','michael','florence','eli']
>>>first_up = choice(players)
>>>first_up
'florence'

6.类编码风格

类名采用驼峰命名法,每个单词的首字母都大写,不使用下划线。

实例名和模块名都采用小写格式,并在单词之间加上下划线。

2022/7/6 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值