python-我的入门心得

前言:
去年年底我才算是真正的入门了python,之前的内容可以说是九牛一毛的小功夫了。至今,接近一年的时间,将之前学习的一些小方法和小的模仿练习供大家参考。

建议:
1、计算机语言是一种实现我们某一种计算或展示目的的工具,重在使用,可以简单入门先了解语法,深入学习,建议根据自己的方向和目的逐步推进。
2、前期可先使用Pycharm规范自己的编写习惯,之后转为更为灵活的Visual Studio(插件很香)

参考书籍

Eric Matthes - 《Python Crash Course》_ A Hands-On, Project-Based Introduction to Programming-No Starch Press (2019)

在这里插入图片描述

获取方法:
夸克网盘:https://pan.quark.cn/s/1eb1a06a24cc

百度网盘:
链接:https://pan.baidu.com/s/1qAu56DrN7JJ8OM1vl8NGXw?pwd=sswi
提取码:sswi

书籍配套网站:https://nostarch.com/pythoncrashcourse2e/

如果从事数据处理的内容,对前十章进行基本了解即可。

代码练习

建议在一周之内练习完成,之后就直接上手一些任务和工作(已经按照之前的学习进度分节)

第一节 字符串和数字

    # This is a sample Python script.

    # Press Shift+F10 to execute it or replace it with your code.
    # Press Double Shift to search everywhere for classes, files,
    # #tool windows, actions, and settings.

    #  第二章
    #  第一部分:有关字符串
    # 随时更新,但因为每次都输出了,所以有两行,而不是一行
    message = "Hello Python interpreter!"
    print(message)

    message = "Hello Python Crash Course world!"
    print(message)

    # title的功能就是让他变成标题的形式  upper 大写  lower 小写
    name = "ADa lovelace"
    print(name.title())
    print(name.upper())
    print(name.lower())

    # 名+姓   f 字符串组合
    first_name = "ada"
    last_name = "lovelace"
    full_name = f"{first_name} {last_name}"
    print(full_name)
    message = f"hello,{full_name.title()}!"
    print(message)

    # \t  start the next line with a tab   \n  move to a new line
    print("\tPython")
    print("\n\tPython")

    # 将字符串中多余的空格删除,只留下字符
    # #rstrip(删除右边的空白)  lstrip(删除左边的空白) strip(删除所有的空白)
    favorite_language = '   python   '
    print(favorite_language)
    favorite_language = favorite_language.rstrip()
    print(favorite_language)

    # 在单引号中间尽量不要出现撇号’ 以免认为该句结束,导致语法错误
    message = "One of Python's strengths is its diverse community."
    print(message)

    # 小作业   注意在组合时要求是话用双引号,就需要用转义符 \"
    writer = "Albert Einstein"
    lian_ci = "once said"
    sentence = "\"A person who never made a \nmistake never tried anything new\"."
    sentence_kuo = "sentence"
    writer_sentence = f"{writer} {lian_ci} {sentence}"
    print(writer_sentence)

    #  第二部分:有关数字
    # 加减乘除:其中乘方使用**  数字太长了可以使用下划线进行分割(易读)
    a = 1+1
    b = 2/9
    c = 3**2
    d = 2**2.0
    message = "My favorite number is:"
    universe_age = 14_000_000_000
    print(universe_age)
    print(f"{message} {c}")

    # 多重赋值
    x, y, z = 0, 0, 0

    # 常数,也就是matlab中的全局变量  是在程序中永远不变的,python中直接全部大写就可以搞定
    # 元组是不可变的数据类型
    MAX_CONNECTTIONS = 500

    # 2022-11-29日 学习到第67页 comment   Fighting!
    # the zens of python
    # import this 用来看有哪些信条

第二节 列表和循环

    #  第三章 List
    # 列表由[] 以及, 组成  0为第一个,-1为最后一个
    bicycles = ['trek', 'cannandale', 'redline', 'specialized']
    print(bicycles[0].title())
    print(bicycles[-1].upper())
    message = f"My first bicycle was a {bicycles[0].title()}"
    print(message)

    # 改变列表中的元素  改变——定位
    # #尾部添加——append  任意位置插入——insert  删除某一位置元素——del
    # 其中[0:2] 指的是删除0、1两个位置的元素,2表示截止位置
    motocycles = ['honda', 'yamaha', 'suzuki']
    print(motocycles)
    motocycles[-1] = 'ducati'
    print(motocycles)
    motocycles.append('ducati')
    print(motocycles)
    motocycles.insert(0, 'ducati')
    print(motocycles)
    del motocycles[0:2]
    print(motocycles)

    # pop 将list里面的最后一个值删掉,并存储删掉的值
    popped_motocycle = motocycles.pop()
    print(motocycles)
    print(popped_motocycle)
    first_owned = motocycles[0]
    print(f"The first motorcycle Iowned was {first_owned}")

    # remove 将一个已经知道信息但不知道位置的量删除
    motocycles = ['honda', 'yamaha', 'suzuki', 'ducati']
    motocycles.remove('honda')
    print(motocycles)

    # 重新组织list  .sort(reverse=True/False) 按照首字母进行排序(改变了回不去)
    # #sorted() 改变了可以回去   .reverse 将原顺序颠倒
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    cars.sort(reverse=False)  # True
    print(cars)

    print("\nHere is the sorted list:")
    print(sorted(cars))

    print("\nHere is the original list again:")
    print(cars)

    cars.reverse()
    print(cars)

    # list的长度  len
    aa = len(cars)

    #  第四章  循环
    magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
        print(magician)

    magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
        print(f"{magician.title()}, that was a great trick!")
        print(f"I can't wait to see your next trick, {magician.title()}.\n")
    print("Thank you, everyone. That was a great magic show!")

    #  range(0,5) = range(5)  输出均为0,1,2,3,4
    for value in range(0, 5):
        print(value)

    # 使用list建立数字列表
    # (0,11,2) 0 初始 11 截止(不包含) 2 间隔  有点类似于matlab中的linspace
    numbers = list(range(0, 11, 2))
    print(numbers)

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

    squares = [value**2 for value in range(1, 11)]
    print(squares)

    # 计算最小值min 最大值max 求和sum
    digits = list(range(1, 11))
    a_min = min(digits)
    a_max = max(digits)
    a_sum = sum(digits)
    print(a_min, a_max, a_sum)

    # slice 输出指定范围  :就表示要么前面所有,要么后面所有  在循环中用也很便捷
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[0:3])
    print(players[:4])
    print(players[-3:])

    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print("Here are the first three players on my team:")
    for player in players[:3]:
        print(player.title())


    # 2022-11-30日 学习到第101页 Copying a List  Fighting!

第三节 元组、if判断、字典

    # 将一个列表的值copy到另一个list中
    # 如果players后面加入[:] 则favorite_players 和 players就会分开处理;直接赋值,会一同变化
    # 强调了slice 切片的重要性
    favorite_players = players[:]
    players.append('qpp')
    favorite_players.append('dpp')

    # tuple  永恒不变的(immutable)list   使用圆括号(parentheses)定义,而不是方括号
    # tuple 和 大写字母定义的常数有什么区别?
    dimensions = (200, 50)
    print(dimensions[0])
    print(dimensions[1])

    for dimension in dimensions:
        print(dimension)

    # 构造元组时,如果没有在单个数字后面加, 则输出不是一个元组类型,而是一个int或float
    my_t = (2.3, )

    # 第五章 if条件判断   if else 后面都要加:  没有end结尾  等于 == 不等于 !=  数字同理
    cars = ['bmw', 'audi', 'toyota', 'subaru']

    for car in cars:
        if car == 'bmw':
            print(car.upper())
        else:
            print(car.title())

    car = 'Bmw'
    # car.lower() == 'bmw'  既不改变又可用于判断

    requested_topping = 'mushrooms'
    if requested_topping != 'anchovies':
        print("Hold the anchovies!")
    # 再次强调:for if else 结尾都是需要加:的

    # 判断中出现“和” “或” 的时候使用“and” “or” 相当于matlab中的“&&” “||”
    # 大于等于 >=   小于等于 <=   存在多个判断时,可以采用()分割,但不是必须
    age_0 = 18
    age_1 = 20
    if (age_0 >= 17) and (age_1 <= 22):
        print("Wow! That is right!")
    else:
        print("That is really sad!")

    # 判断list中的value是否存在   是否在  in  是否不在  not in
    abc = ['a', 'b', 'c']
    # 'a' in abc
    # >>>True
    banned_users = ['andrew', 'carolina', 'david']
    user = 'marie'
    if user not in banned_users:
        print(f"{user.title()}, you can post a response if you wish.")

    # 布尔表达式(Boolean Expressions)  这个东西怎么用?

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

    # 对于有多种判断的使用:if - elif - else    可以使用多个elif  并且最后的else并不是必须的
    # 在if-elif-else中,满足一个即可输出,但有时候一个事情满足多种条件,需要多个输出的时候,就会
    # 将不会继续使用这个chain,而是转为if-if-if实现
    age = 12
    if age < 4:
        price = 0
    elif age < 18:
        price = 25
    else:
        price = 40
    print(f"Your admission cost is ${price}.")

    requested_toppings = []
    if requested_toppings:  # 判断结果为True  即1
        # Python returns True if the list contains at least one item;
        # an empty list evaluates to False
        for requested_topping in requested_toppings:
            print(f"Adding {requested_topping}.")
        print("\nFinished making your pizza!")
    else:
        print("Are you sure you want a plain pizza?")

    restaurant_fills = ['mushrooms', 'olives', 'green peppers',
                        'pepperoni', 'pineapple', 'extra cheese']
    guest_quests = ['pepperoni', 'red peppers', 'olives']
    for guest_quest in guest_quests:
        if guest_quest in restaurant_fills:
            print(f"Adding {guest_quest}")
        else:
            print(f"Sorry, we don't have {guest_quest}")

    print("\n Finished making your pizza!")

    # 第六章 字典dictionary {key1: value1, key2: value2, key3...}
    alien_0 = {'color': 'green', 'point': 5}
    print(alien_0['color'])
    print(alien_0['point'])

    # 给字典添加key和对应的value
    alien_0['x_position'] = 0
    alien_0['y_position'] = 25

    # 建立一个空的字典,并填充
    alien_a = {}
    alien_a['number'] = 1
    alien_a['name'] = 'superalien'
    print(alien_a)
    alien_a['number'] = 2

    # 小游戏,对外星人的位置进行改变
    alien_3 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
    print(f"Original position: {alien_3['x_position']}")
    if alien_3['speed'] == 'slow':
        x_increment = 1
    elif alien_3['speed'] == 'medium':
        x_increment = 2
    else:
        x_increment = 3
    alien_3['x_position'] = alien_3['x_position'] + x_increment
    print(f"New position: {alien_3['x_position']}")
    certain = alien_3.get('speed')

    # 删除dict中的某个key 使用del
    # 此为永久删除:Be aware that the deleted key-value pair is removed permanently.
    del alien_3['y_position']

    alien_0 = {'color': 'green', 'speed': 'slow'}
    point_value = alien_0.get('speed', 'No point value assigned.')
    print(point_value)

    # 小练习  .keys 得到key  同样对于.values     name['key1'] = name. get('key1')
    bf_information = {
        'f_name': 'Hai',
        'l_name': 'Wang',
        'gender': 'male',
        'age': 22,
        'city': 'Nanjin'
        }

    f_name = bf_information['f_name']
    l_name = bf_information.get('l_name')

    # .items 可以同时得到 keys 和 values
    for key, value in bf_information.items():
        print(f"\nKey: {key}")
        print(f"\nValue: {value}")

    # sorted 会将索引量进行首字母排序
    # set 会将重复量删除
    for qian_value in sorted(bf_information.keys()):
        print(f"OK! I know {qian_value.title()} is really important!")

    if 'age' not in bf_information.keys():
        print("Please add the age to your best friend!")
    else:
        print(f"Wow! You friends is {bf_information.get('age')} years old.")

    # 与dict相近的set  内部时不存在键值对的
    # 输出五顺序,而且也不重复            暂时不知道他有什么用处
    languages = {'python', 'ruby', 'python', 'c'}
    print(languages)

    # 嵌套 nesting
    # 将字典嵌套在列表中  [{},{},{}] dicts in list  (A List of Dictionaries)
    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)

    # Make an empty list for storing aliens.
    aliens = []
    # Make 30 green aliens.
    for alien_number in range(30):
        new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
        aliens.append(new_alien)
    # Show the first 5 aliens.
    for alien in aliens[:5]:
        if alien['color'] == 'green':
            alien['color'] = 'red'
            alien['points'] = 10
            alien['speed'] = 'medium'
        print(alien)
    print("...")
    # Show how many aliens have been created.
    print(f"Total number of aliens: {len(aliens)}")

    # 2022-12-1日 学习到第145页 A List of Dictionaries  Fighting!

第四节 while判断

    # 将列表嵌套在字典中  {[],[],[]} list in dicts   (A List in a Dictionaries)
    pizza = {
        'crust': 'thick',
        'toppings': ['mushrooms', 'extra cheese']
    }
    print(f"You ordered a {pizza['crust']}-crust pizza "
        "with the following toppings:")

    for topping in pizza['toppings']:
        print("\t"+topping)

    # 将字典嵌套在字典中 A Dictionary in a Dictionary
    users = {
        'aeinstein': {
            'first': 'albert',
            'last': 'einstein',
            'location': 'princeton',
            },
        'mcurie': {
            'first': 'marie',
            'last': 'curie',
            'location': 'paris',
            },
        }
    for username, user_info in users.items():
        print(f"\nUsername: {username}")
        full_name = f"{user_info['first']} {user_info['last']}"
        location = user_info['location']
        print(f"\tFull name: {full_name.title()}")
        print(f"\tLocation: {location.title()}")

    # 第七章 while loop (while循环语句的使用)
    # input的用法  prompt(提示用户输入)   最好是在冒号后面加入space
    name = input("Please enter your name: ")
    print(f"\nHello, {name}!")

    # build a multi-line string +=   语句过长,分行更清晰
    prompt = "If you tell us who you are, we can personalize the messages you see."
    prompt += "\nWhat is your first name? "
    name = input(prompt)
    print(f"\nHello, {name}!")

    # 对于用户输入数字,但input结果为str类型,使用int转换
    age = input("Hello! Hou old wre you?")
    age = int(age)

    # 求余数运算 The Modulo Operator(%)
    a_m = 45 % 4

    in_sen = "Please give me you favorite number,I will tell you if it is an odd. "
    number_input = input(in_sen)
    number_input = int(number_input)

    if number_input % 2 != 0:
        print(f"Congratulations! {number_input} is an odd.")
    else:
        print(f"Wow! {number_input} is an even.")

    # while 循环
    sum_curn = 0
    current_number = 1
    while current_number <= 5:
        print(current_number)
        sum_curn += current_number
        current_number += 1
    print(sum_curn)

    prompt2 = "\nTell me something, and I will repeat it back to you:"
    prompt2 += "\nEnter 'quit' to end the program"
    message = ""  # 以供python进行第一次判断
    while message != 'quit':
        message = input(prompt2)
        print(message)

    # flag 的神奇用法
    active = True
    while active:
        message = input(prompt2)

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

    # 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(f"I'd love to go to {city.title()}!")

    # continue 的用法
    current_number = 0
    while current_number < 10:
        current_number += 1
        if current_number % 2 == 0:
            continue
            # continue statement tells Python to ignore the rest of
            # the loop and return to the beginning
        print(current_number)

    # 错误的 infinity
    # x = 1
    # while x <= 5:
    #       print(x)

    # Using a while Loop with Lists and Dictionaries #
    # A [for loop] is effective for looping through a list, but you shouldn’t modify
    # a list inside a [for loop] because Python will have trouble keeping track of
    # the items in the list. To modify a list as you work through it,
    # use a [while loop].Using [while loops] with lists and dictionaries allows you
    # to collect, store,and organize lots of input to examine and report on later.

    # Start with users that need to be verified,
    # and an empty list to hold confirmed users.
    unconfirmed_users = ['alice', 'brian', 'candace']
    confirmed_users = []
    # Verify each user until there are no more unconfirmed users.
    # Move each verified user into the list of confirmed users.
    while unconfirmed_users:
        current_user = unconfirmed_users.pop()

        print(f"Verifying user: {current_user.title()}")
        confirmed_users.append(current_user)
    # Display all confirmed users.
    print("\nThe following users have been confirmed:")
    for confirmed_user in confirmed_users:
        print(confirmed_user.title())

    # 使用remove将list中某一指定的字符删完
    men = ['Huo Jianhua', 'Chi Changxu', 'Liu Dehua', 'Hu Ge', 'Huo Jianhua']
    print(men)

    while 'Huo Jianhua' in men:
        men.remove('Huo Jianhua')
    print(men)

    # 使用用户输入填充字典内容
    Hearting_Challenge = {}

    Challenge_active = True
    while Challenge_active:
        name = input("\nHello! Welcome to this Challenge~ What's your name")
        hearting_girl = input("\nWho is your favorite girl?")

        Hearting_Challenge[name] = hearting_girl

        repeat = input("Would you like to let another person respond?(yes/no)")
        if repeat == 'no':
            Challenge_active = False
    print(f"\nIt's time to tell you {len(Hearting_Challenge)} truth(es) <@^_^@>")
    for name, hearting_girl in Hearting_Challenge.items():
        print(f"Dear {name}, your favorite girl is {hearting_girl}.")

    # python 中的 function 定义  形参:argument  实参:parameter  在函数定义时,没有明显差别
    def greet_user(username):
        # describes what the function does
        """Display a simple greeting."""
        print(f"Hello, {username.title()}!")

    # 位置参数
    def describe_gender(name, gender): # Attention:需要字符型输入
        """describe the gender of someone"""
        print(f"{name} is my good friend,")
        if gender == 'girl':
            sub_gender = 'she'
        else:
            sub_gender = 'he'
        print(f"{sub_gender} is a {gender}.")
    # 在调用的过程中,使用关键字参数(Keyword Arguments)可以不用担心顺序问题
    # describe_gender(gender = 'boy', name = 'Mile')
    # >>>Mile is my good friend,
    # he is a boy.

    # 可以在函数定义中设置默认输入值
    # 例如:def describe_gender2(name, gender = 'girl'): # Attention:需要字符型输入
    # 此时可以只输入字符型的name,默认性别为女孩儿;当输入为两个是,则用输入值(可以指定)

    # 比如:有这样的一个函数
    # def describe_pet(pet_name, animal_type='dog'):
    # 可以使用以下方法进行调用
    # describe_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')

    # 当有多个输入时,可以将某些定为选择性输入 (选择性输入,同matlab一般放在最后面
    # matlab可以用nargin判读输入个数来执行)
    def get_formatted_name(first_name, last_name, middle_name=''):
        """Return a full name, neatly formatted."""
        if middle_name:
            # Python interprets non-empty strings as True
            full_name = f"{first_name} {middle_name} {last_name}"
        else:
            full_name = f"{first_name} {last_name}"
        return full_name.title()

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

    # 函数最后值返回至字典
    def build_person(first_name, last_name, age=None):
        """Return a dictionary of information about a person."""
        person = {'first': first_name, 'last': last_name}
        if age:
            person['age'] = age
        return person

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

    # 在循环中调用函数(同matlab的思路)
    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(f"\nHello, {formatted_name}!")

    def print_models(unprinted_designs, completed_models):
        """
        Simulate printing each design, until none are left.
        Move each design to completed_models after printing.
        """
        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):
        """Show all the models that were printed."""
        print("\nThe following models have been printed:")
        for completed_model in completed_models:
            print(completed_model)

    unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
    completed_models = []
    # 这里如果使用 print_models(unprinted_designs[:], completed_models) 则保留原状态
    print_models(unprinted_designs, completed_models)
    show_completed_models(completed_models)

    # 厉害了! def中还可以Passing an Arbitrary Number of Arguments  传递任意数量的参量
    # 此时输入任意个toppings是以tuple存储的   如果有其他想要规定的输入,需要放在前面
    # 单星号 * 输入一个
    def make_pizza(*toppings):
        """Summarize the pizza we are about to make."""
        print("\nMaking a pizza with the following toppings:")
        for topping in toppings:
            print(f"- {topping}")
    make_pizza('pepperoni')
    make_pizza('mushrooms', 'green peppers', 'extra cheese')

    # 双星号 ** 输入多个(字典)
    def build_profile(first, last, **user_info):
        """Build a dictionary containing everything we know about a user."""
        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)

    # 关于import的使用
    # 第一种:首先,新建了一个pizza.py的函数module  函数封装名字.函数名()
    # module_name.function_name()
    import pizza
    pizza.make_pizza(16, 'pepperoni')
    pizza.make_pizza(12, 'pepperoni', 'onion')

    # 第二种:调用模块中的某一个函数或者某几个函数
    # from module_name import function_name
    # from module_name import function_0, function_1, function_2
    from pizza import make_pizza
    # 这个时候就可以不用dot . 了,看着更方便一些
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

    # 第三种:如果名字重复了,可以给调用的函数起个别名
    # Using as to Give a Function an Alias
    from pizza import make_pizza as mp
    mp(16, 'onion')

    # 第四种:上面方法给函数起名,同样也可以给模块起名字
    # Using as to Give a Module an Alias
    # 这个方法的好处在于:知道那个模块,同时知道重用了哪个模块
    import pizza as p
    p.make_pizza(16, 'pepperoni')
    p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

    # 第五种:调用某种模块里面所有的函数
    # Importing All Functions in a Module
    from pizza import *
    make_pizza(16, 'pepperoni')
    make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

    # Attention:
    # 1、如果你为一个参数指定了默认值,等于号的两边不应该使用空格:
    # 2、在一个模块里面写很多函数时,函数之间需要空两行
    # 3、在调用时,应该将调用放在主程序最前面(除非前面还有其他文字解释)

    # 2022-12-2日 学习到第195页 classes  Fighting!

第五节 类

    # 创建类
    class Dog:
        """A simple attempt to model a dog."""
        def __init__(self, name, age):
            """Initialize name and age attributes."""
            self.name = name
            self.age = age
        def sit(self):
            """Simulate a dog sitting in response to a command."""
            print(f"{self.name} is now sitting.")
        def roll_over(self):
            """Simulate rolling over in response to a command."""
            print(f"{self.name} rolled over!")

    my_dog = Dog('Willie', 6)
    print(f"My dog's name is {my_dog.name}.")
    print(f"My dog is {my_dog.age} years old.")

    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()
    print(f"\nYour dog's name is {your_dog.name}.")
    print(f"Your dog is {your_dog.age} years old.")
    your_dog.sit()

    # 小练习
    class Restaurant:

        def __init__(self, restaurant_name, cuisine_type):
            self.name = restaurant_name
            self.cuisine_type = cuisine_type
        def describe_restaurant(self):
            print(f"This restaurant'name is {self.name}, "
                f"its classcal cuisine is {self.cuisine_type}")
        def open_restaurant(self):
            print(f"{self.name} is open!")

    A_restaurant = Restaurant('Chinese Town', 'hancan')
    B_restaurant = Restaurant('Mexicow Town', 'juanbing')
    print(f"My favorite restaurant is {A_restaurant.name}, "
        f"and I really like {A_restaurant.cuisine_type}.")
    A_restaurant.open_restaurant()

    class Car:
        """A simple attempt to represent a car."""
        def __init__(self, make, model, year):
            """Initialize attributes to describe a car."""
            self.make = make
            self.model = model
            self.year = year
            self.odometer_reading = 0
        def get_descriptive_name(self):
            """Return a neatly formatted descriptive name."""
            long_name = f"{self.year} {self.make} {self.model}"
            return long_name.title()
        def read_odometer(self):
            """Print a statement showing the car's mileage."""
            print(f"This car has {self.odometer_reading} miles on it.")
    my_new_car = Car('audi', 'a4', 2019)
    print(my_new_car.get_descriptive_name())
    my_new_car.read_odometer()
    # 修改class内部的某些特征值
    my_new_car.odometer_reading = 23
    my_new_car.read_odometer()

    # 2022-12-3日 学习到第202页  Fighting!

第六节 文件数据读取

    class Car:
        """A simple attempt to represent a 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 = f"{self.year} {self.make} {self.model}"
            return long_name.title()
        def read_odometer(self):
            print(f"This car has {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 ElectricCar(Car):
        """Represent aspects of a car, specific to electric vehicles."""
        def __init__(self, make, model, year):
            """Initialize attributes of the parent class."""
            super().__init__(make, model, year)

    my_tesla = ElectricCar('tesla', 'model s', 2019)
    print(my_tesla.get_descriptive_name())


    # The Python Standard Library
    from random import randint
    ar = randint(1, 6)

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


    # 第十一章 Files and Exceptions
    # 读取文件数据
    filename = "E:/START_51710/haa1/DATA/tec1995/CODG0010.95I"
    with open(filename) as file_object:
        contents = file_object.read()
    print(contents)

    # 2022-12-5日 学习到第222页 File Paths   Fighting!
    # 文件的绝对路径:可以使用\\或者/进行分割,但\不行,容易和转义符混淆
    with open(filename) as file_object:
        for line in file_object:
            print(line.rstrip())


    with open(filename) as file_object:
        lines = file_object.readlines()

    for line in lines:
        line1 = line.strip()
        print(line1.split())

    # 将str转换为可处理的数字:int float
    # 替换字符串中的某一项
    # 在命令行中可以达成目的
    messageanimal = "I really like dogs."
    messageanimal.replace('dogs', 'cats')

    # 将数据写入文件
    # read mode ('r'), write mode ('w'), append mode ('a')
    # a mode that allows you to read and write to the file ('r+')
    # 下面就是将指定CODE的数据写到了programming.txt中
    filename = 'E:\\pythonProject\\test1\\programming.txt'
    with open(filename, 'w') as file_object:
        for line2 in lines:
            file_object.write(line2)
    with open(filename, 'a') as file_object:
        file_object.write("I also love finding meaning in large datasets.\n")
        file_object.write("I love creating apps that can run in a browser.\n")

    # try - except - else
    # 可以现在命令行尝试,最后一行会提示错误原因,将原因作为except 后的条件即可
    # 1、对于除法分母不能为0的情况
    print("Give me two numbers, and I'll divide them.")
    print("Enter 'q' to quit.")
    while True:
        first_number = input("\nFirst number: ")
        if first_number == 'q':
            break

        second_number = input("Second number: ")
        if second_number == 'q':
            break

        try:
            answer = int(first_number) / int(second_number)
        except ZeroDivisionError:
            # pass 使用pass就是在出现这样的问题时默默的过去
            print("You can't divide by 0!")
        else:
            print(answer)

    # 2、对于文件路径错误或者文件名错误或文件根本不存在的情况
    filename = 'alice.txt'
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {filename} does not exist.")

    # 文本分析 Analyzing Text
    # 删除空格
    title = "Alice in Wonderland"
    title_words = title.split()
    # .count('words') 可以帮你数一下这个词出现了多少次
    line = "Row, row, row your boat"
    row_number_low = line.count('row')
    row_number_lowupper = line.lower().count('row')

    # json 将得到的数字或者其他项目储存起来,供下次直接使用
    # json.dump(数据,文件名)  写入数据
    import json
    numbers = [2, 3, 5, 7, 11, 13]
    filename = 'numbers.json'
    with open(filename, 'w') as f:
        json.dump(numbers, f)
    # json.load(文件名) 将json文件中的数据导入到变量中
    import json
    filename = 'numbers.json'
    with open(filename) as f:
        numbers_1 = json.load(f)
    print(numbers_1)

    # 将各部分拆分,重构;将冗杂的逻辑按照步骤更加清晰
    import json
    def get_stored_username():
        """Get stored username if available."""
        filename = 'username.json'
        try:
            with open(filename) as f:
                username = json.load(f)
        except FileNotFoundError:
            return None
        else:
            return username
    def get_new_username():
        """Prompt for a new username."""
        username = input("What is your name? ")
        filename = 'username.json'
        with open(filename, 'w') as f:
            json.dump(username, f)
        return username
    def greet_user():
        """Greet the user by name."""
        username = get_stored_username()
        if username:
            print(f"Welcome back, {username}!")
        else:
            username = get_new_username()
            print(f"We'll remember you when you come back, {username}!")
    greet_user()

    # 2022-12-6日 学习到第208页 第十章学习完成


祝好~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值