python中级项目下载_中级Python复习:教程,项目思想和技巧

python中级项目下载

本文旨在向Python初学者和开发人员介绍Python中使用的一些关键概念,这些概念一开始就没有讲授。

如果您可以创建二次方根求解器,则可以理解本文。 这些是我一天之内没有学到的概念,而是几年后自学成才的一些概念。

我尝试将其制作为视频,但视频最终为1:45
几个小时 我自己需要很多动力才能观看
这么长的“教程”,我更喜欢用文章来获取我的信息
因为我可以选择相关细节而不是试图跳过
视频的各个部分。

一切如何开始

我通过CS Circles学习了Python基础知识然后继续改进/测试我的问题解决能力。 为此,我做了一些CCC问题,您可以在DMOJ中找到(以及其他竞赛问题)。 其他可提高算法问题解决能力的网站包括HackerRankLeetCode (尽管这主要是为面试做准备)。

在执行此操作时,我正在使用默认的IDLE编辑器进行编码! 我做了3个月,然后发现PyCharm
学习曲线稍有一点,但在功能方面更好
并提高生产力。 如今,我同时使用PyCharm和Visual Studio Code

我个人有一个完整的文件夹,专用于代码片段,我可以
将来使用,所以我建议您也这样做,甚至可以添加一些
本文中的代码片段的一部分,以便您可以阅读
自己的示例,而不是使用Google搜索或返回本文。

一般提示

这些技巧与编程无关,而只是生活和生产力的提高。

了解键盘快捷键
既要了解程序特定的内容(浏览器,资源管理器,所选的IDE等),也要了解OS特定的内容(例如Win + R来运行)。

了解命令行

实际上,您可以从命令行执行Python代码,而无需手动进行计算或打开IDE来创建和运行脚本。
除了常见的批处理功能(例如ls,cd),还知道如何使用
命令行中的Python将为您节省大量时间

知道如何使用Google

Google(或您选择的搜索引擎)是我最好的朋友,也应该是您的朋友。 它节省了我很多时间,因此也可以节省您一个时间。
很多时间。 如果您不使用它或不知道如何做,它将无法做到这一点
用它。 当您搜索Google内容时,您的查询必须具有足够的笼统性,以便您可以找到答案,但还必须具有足够的针对性,以便
答案是相关的。

问题分解策略

这与谷歌搜索并驾齐驱。 假设您有问题/项目。 您需要将其分解为较小的部分。 然后,您需要分析每个部分,并查看它们是否足够小以使您可以完成每个部分。 如果不是这样,则可能是您丢失了一些您应该使用Google的知识,或者零件太大,需要再次进行细分。 您继续执行此递归过程,直到您的项目完成为止。
分为可解决的部分,以便您可以完成它们然后进行编织
一起一个项目。 当我通过Google搜索并找到答案时,
不要指望他们会是我需要的100%。 我通常需要混音
他们进入我想要的,那也是您应该期望的:光秃秃的
使您至少向前迈出至少一步的最小解决方案。

陈述了这些技巧后,接下来您可以做几件事。 您
可以浏览文档的其余部分,并在代码段上做注释
我推荐(我会做些什么),仅阅读标题,跳至
项目构想部分,或者因为我的技巧如此而完全停止阅读
有用。

刷新器

在CS圈子中,他们带来了打印功能及其某些功能
可选参数,但是很容易忘记它们,所以这里是
再次。

>>>  # The default parameters for print are sep=' ', and end='\n'
>>>  print( '4' , '21' , 2020 , sep= '/' , end= '\n---------\n' )
4 / 21 / 2020
---------

开始吧

输入函数和字符串格式

输入函数具有可选参数,因此它也可以用作
提示,如果您使用的是Python 3.6+,则可以使用f字符串。

name = input('Enter your name: ' )
print( f'Hello {name} !' )  # modern way of string formatting
# if input='reader', output: Hello reader!

对于循环

我想向您说明一个for循环,而不是while循环
用其他语言。 在Python中,for循环是对可迭代对象的迭代。

范围函数具有三个参数,其中两个是可选的。 不要使用显式起始值0的range函数进行写操作,因为0是默认的起始值(除非您要修改默认的阶跃值1)。

在此示例中,我将向您确切说明“不是while循环”的含义,以及for循环(特别是范围)如何不添加到临时值中。

# range(start=0, stop, step=1)
# range(5) == range(0, 5) == range(0, 5, 1)

for i in range( 5 ):
    print(i)
    i += 2
# Guess the output. HINT: i += 2does nothing

如果运行此代码,您会注意到输出增加了1
每次,即使我们在每个循环中将2加到i上。 这是因为
设置为范围内的下一个值,实际上并没有增加
每次一次。 这意味着我们实际上可以遍历各种
可迭代对象(如列表),而不必使用范围和索引。

some_letters = ['a' , 'b' , 'c' , 'd' , 'e' ]
for letter in some_letters:
    # do something
    pass

在这里,我介绍了关键字pass,这是为了避免在其他空白块中出错。

如果您确实想跟踪索引和项目,则仍然
不必使用范围,可以使用内置函数枚举。

for i, letter in enumerate(some_letters, start= 0 ):
    print( f'item at index {i} is {letter} ' )

您可以将枚举视为将一个可迭代对象转换为成对的可迭代对象(索引,索引处的可迭代项)。

您还可以使用next函数来检索
迭代(如果没有下一个项目,将引发错误)。

文件I / O

我之所以这样包括在内,是因为如果您在Google上搜索“如何读取python中的文件”,则会获得此信息 ,该方法以旧方法而非现代方法进行教学。

# make sure test.txt exists with text in it

# OLD 
f = open( 'test.txt' )  # note default is mode='r'
# do something with f here
f.close()
with open( 'test.txt' ) as f: # NEW; no close() needed
   print(f.read())
   # f.read() moves the "cursor" to the end of the file
   assert not f.read()
   f.seek( 0 )
   assert f.read()
   # f.read() returns a string now (unless test.txt is empty)

with open( 'test.txt' , 'w' ) as f:
    # f.read()  ERROR do not do this
    f.write( 'this is a test\n' )  # note there is no end parameter
    f.writelines([ 'line1\n' , 'line2\n' ])  # note no auto newline# other modes: a for append, rb for reading-bytes, wb for writing bytes, and r+/w+ for both reading and writing at the same time

如果您好奇为什么r + / w +不是默认值,请考虑一个文件如何
如果被“写入”,则无法打开以进行写入
另一个程序。 如果您只需要读取文件,则可以在
另一个程序意味着您不会干扰另一个
程序。

错误处理

# handling the error
try :
    raise RuntimeWarning( 'Something could go wrong' )
except RuntimeWarning as e:  # as e is optional
    # handle the exception here

# ignoring the error
# old
try :
    raise Exception( 'BOO' )
except Exception: pass

# new
from contextlib import suppress
def ignore_error (exception: Exception) : 
    """
    Use three quotes for docstrings or long strings
    """
    # : for type hinting (in a dynamic typed language!) and
    # yes you can pass exceptions and functions as parameters
    with suppress(exception):
        raise exception( 'BOO' )
        print( 'not printed' )

ignore_error(RuntimeError)
print( 'this gets printed' )

至此,如果您遵循PyCharm,您将看到一些混乱的行,尤其是在上面代码中的“ Exception”下。
这些弯曲的行可帮助您避免语法错误,遵循样式
准则,并注意可能正在做的代码
您不希望它这样做。

更多数据类型

那么,我一直在提到这些可迭代项? 是的,列表是可迭代的,元组(您应该已经知道)也是如此。

也有字典,集合和生成器(此处不讨论)。
字典就像其他语言的哈希表一样,因为它们
“哈希”存储信息的密钥。

empty_dict = {}  # or dict()
my_dict = {'key' : 'value' }
# How to get value from dict
my_dict[ 'a' ]  # raises KeyError if 'a' not in dictionary
my_dict.get( 'a' , DEFAULT_VALUE)

if 'key' in my_dict:
    val = my_dict[ 'key' ]
val = my_dict.get( 'key' , None)
if val is not None: pass
with suppress(KeyError):
    val = my_dict[ 'key' ]

# iterations
for k in my_dict: pass  # or for k in my_dict.keys()
for v in my_dict.values(): pass
for k, v in my_dict.items():
    # since items() generates the items as the iteration happens, 
    #  my_dict cannot be modified in this loop.
    # For modification use tuple(my_dict.items())
    pass

# remove key from dict
del my_dict[ 'key' ]  # can raise KeyError

# if you want to use the value, use .pop() and define a default 
# value to avoid KeyErrorsmy_dict.pop( 'key' , DEFAULT_VALUE)

# set
empty_set = set()  # {} would initialize an empty dict
my_set = { 1 , 2 , 3 }
if 1 in set: pass
# there are many set methods, go check them out yourself
# some include: union, intersect, difference
# you can use + and - as well

数据结构使用率(效率)

您使用的数据结构对于编写良好的代码非常重要。

如果顺序无关紧要,则使用字典+每个键都具有与其相关的信息(值);如果顺序无关紧要,则+使用每个键的值(例如,跟踪自己“已使用”的内容);如果需要,则使用元组有序数据,但不需要修改数据(例如坐标),如果需要顺序和可变性,则使用列表(最灵活)

如果需要跟踪,则不能使用集合或字典或集合
重复。 这是因为集合和字典对键进行哈希处理,以便
检查键是否在字典中是超快速的(O(1))。 这确实
表示您不能将列表,集合和生成器用作键(但是只要列表未嵌套,就可以使用元组)。

字典也像JSON对象一样,因此您实际上可以使用json模块将它们导出到JSON文件。 请注意,如果您使用集合作为值,则它们会转换为导出的json文件中的列表。

杂项功能

有时您会看到诸如func(*args, **kwargs)类的func(*args, **kwargs)

# args = a list of arguments
# kwargs = keyword arguments 
# (in the function it'll be a dictionary)
# *args: list in the function **kwargs: dict in the function
def complex_func (*args, **kwargs) :
    pass

def normal_func (a, b, c, sample_param= 5 ) :
   pass

sample_args = { 'sample_param' : 3 }
args = [ 0 , 1 , 2 ]

complex_func( 1 , 2 , 3 , test= 'true' )  # how you'd call it
complex_func(*args, **sample_args)  # also works on normal functions
normal_func(*args, **sample_args)

清单理解和三元

Python最漂亮的部分之一是列表理解。 一个班轮创建列表。

# example: input is space separated integers
integers = [int(x) for x in input.split()]
# split(sep=' ', maxsplit=-1), -1 means no limit
no_negatives = [x for x in integers if x > 0 ]  # only if
positives = [x if x > 0 else -x for x in integers]  # if and else
back_to_str = ' ' .join((str(x) for x in integers))
# items in the list to join need to be of type str
print(integers)

# this next case demonstrates the ternary operator _ if _ else _
print( 'list is' , 'not empty' if integers else 'empty' )

您还可以使用列表推导来创建字典和集合

set_example = {xfor x in range( 3 )}
dict_example = { x : x for x in range( 3 )}
generator_example = (x for x in range( 3 ))  # use sparingly

第三个例子是发电机。 有一些用例,因此在使用它们之前,请先进行研究,因为它们是本文的高级主题。

可迭代与原始

基本变量和可迭代变量之间有一个非常重要的区别。 例如。

a =5
b = a
a = 6
print(a == b)  # false
# vs.
a = [ 1 , 2 , 3 ]
b = a
c = [ 1 , 2 , 4 ]
a[ 2 ] = 4
print(a == b == c)  # true
print(a is b)  # true; same refrence
print(a is c)  # false

在处理嵌套可迭代对象以及如何创建嵌套可迭代对象并复制它们时,这一点尤其重要。 自己尝试这些示例。

lols = [[0 ] for i in range( 3 )] # [0] is created 3 times
lols[ 0 ][ 0 ] = 5
print(lols)  # [[5], [0], [0]]
# vs.
a = [[ 0 ]]
lols = a * 3  # same as lols = [[0] * 3]
lols[ 0 ][ 0 ] = 5
print(lols)  # [[5], [5], [5]]

复制可迭代项

要制作浅表副本,请使用.copy()。 但是,请注意,对于任何嵌套的可迭代对象,仅复制引用,而不复制实际的嵌套列表。 这就是为什么它被称为浅表副本。 要进行深度复制,我们可以使用复制模块。

new_copy = lols.copy()# I prefer this over using [:]
reversed_list = lols[:: -1 ]
# I rarely use this^ as reversed() and .reverse() exist
new_copy[ 0 ][ 0 ] = 6  # lols == [[6], [6], [6]]
assert lols == new_copy and not lols is new_copy

from copy import deepcopy

new_copy = deepcopy(list_of_lists)
new_copy = list_of_lists
new_copy[ 0 ][ 0 ] = 4  # [[4], [4], [4]] because 3x of the same list
assert lols != new_copy and lols is not new_copy

记忆化

记忆化是对函数返回结果进行缓存,以加快重复计算的速度。 一个例子是斐波那契数列的递归实现。

def memo (func) :  # remove print statements in a practical setting
    cache = {}

    def _helper (x) : # constrained to one param (in this case)
        # you could have multiple params (x, y, ...) and then 
        # cache using tuple keys
        if x not in cache:
            print( 'not in cache' )
            cache[x] = func(x)
        else :
            print( 'in cache' )
        return cache[x]

    return _helper


@memo  # square = memo(square) <-- what it means
def square (x) :
    return x * x

for i in range( 3 ):
    square(i), square(i)  # second one uses cached result

练习是使使用记忆的附加功能(a,b)生效。

Lambdas

如果计算时间短,通常代替功能参数。 例如,排序。

['aa' , 'Bb' , 'Cc' , 'dD' ].sort(key= lambda string: string.upper())
[( 'a' , 1 ), ( 'b' , 0 )].sort(key= lambda pair: pair[ 1 ])
sorted([( 'a' , 1 ), ( 'b' , 0 )], key= lambda pair: pair[ 1 ])
max([( 'a' , 1 ), ( 'b' , 0 )], key= lambda pair: pair[ 1 ])  # and min

模组

模块将在您将要执行的项目中扮演重要角色。 一些内置的是os,shutil,copy,glob和线程。

操作系统

import os
os.mkdir()  # to make a NEW dir
os.chdir()  # choose a current working dir
os.getcwd()  # get current working dir
os.path.exists()
os.rename()
os.remove()  # for existing files only
os.rmdir()
os.getenv( 'key' )  # gets an environmental variable

# use the shutil module for directories with sub directoriese

环境变量

.env文件中指定项目机密

# in .env
KEY=VALUE

# in *.py
with open( '.env' ) as f:
    for line in f.read().splitlines():
        k, v = line.split( '=' , 1 )
        os.environ[k] = v

球状

用于获取文件/文件夹列表

from glob import glob

print(glob( '*.py' ))  # get all .py files in cwd, * is a wildcard
# exercise: find out how to get all .py files in cwd + its subdirs

穿线

我已经写了给你看一些线程例子在这里 。 只需按照要点中的说明进行操作即可。


第三方模块

您需要使用`pip install module_name`来安装模块。

一些常见的模块是请求,beautifulsoup4,PIL和flask。 如果您正在从事大型项目,则可能最终会使用第三方模块。

高级主题(未来的Python学习)

班级

我没有涉及类,因为与Python编程有关的更多是关于OOP的,并且类的用例很小。 学习课程时,您应该知道的一件事是__slots__属性,因此请自行搜索。

发电机

再次,这是一个高级主题,现在学习它只会导致混乱,最好是自己或在实际环境中学习。

装饰工

我只介绍了装饰器的基础知识。 还有许多其他第三方库和不同用例(例如计时功能)使用的装饰器,因此我建议您也对它们进行自己的研究。

git和git工作流程

当您与他人合作或在公司工作时,这一点非常重要。 Git是一种版本控制工具,用于防止错误伤害您,并让您同时使用多个功能。

其他内置模块

如itertools,线程,多处理等。

项目构想

您可以在下面找到项目构想列表:

PRACTICAL PROJECT IDEAS

Your own website/portfolio (no bootstrap, use raw HTML/CSS/JS + flask backend). Use Heroku (free) to host it [Hard]

A program that applies a blur to an image you select [Easy]
    (use tkinter/SG so that you don't have to hard code the filename every time someone uses the program)

A program that sets your desktop wallpaper and cycles through a folder of images, [Okay]
    change the wallpaper every x (you decide) seconds.

Web Scraping & Data Parsing [Hard]
    Go to https://www.cia.gov/library/publications/the-world-factbook/rankorder/2004rank.html and use inspect elements,
    Your job is to parse this web page and filter the data so that only the data with the latest "date of information"
    remains. Output should be order-preserved and in a CSV file (filename is arbitrary)
    To make it easier (not recommended), you can assume the latest date of info is 2017 EST.
    To make it even easier (not recommended) just preserve the order and output all of the data in a CSV
    hint: use requests, bs4, and the csv module
    Another challenge is to download the data as a txt file and convert that text file to a CSV file using Python
    hint: you may find ' '.join(iterable) useful

Using an API [Okay - Hard]
    Spotify Reference
    You' ll have to get a Spotify API key
    See https: //developer.spotify.com/documentation/web-api/reference/search/search/ and
    make a program that lets users search for tracks using the Spotify API (you return a list of tracks)
    See https: //elijahlopez.herokuapp.com/search-album-art/ for a demo but with album art
    You just need to spit out a list of tracks
    To make this harder, you will sort the tracks by popularity (you 'll have to search the documentation yourself)
    To make this even harder, you can add a sort by artists feature and MORE
    # requests, base64 module,

Try to send an email to yourself (your email -> your email) using Python [Easy - Hard]
    To make this harder, try to also send an attachment
    module: at least smptlib

You can try to make your own key logger [Okay - Hard]
    At first just append the contents to a .log or .txt file
        Use the ' a ' open type to append to bottom.
        HARDER: YOU WILL INCLUDE COPIED AND PASTED ITEMS WITH custom syntax
        # (e.g. USER_COPIED("")), (e.g. USER_PASTED(""))

Make your own soundboard with your own sounds [Hard because tedious]
    You PySimpleGUI for the GUI (I recommend but you don' t have to)

    - Let your soundboard include support for different "packs"
    - Specify a design/package guide for other users to create use their sounds on your soundboard
    default : your default pack
    PACKS_DIR/pack_name/sound_name/sound .mp3/ogg
    # pygame, playsound


Make your own game using pygame (OOP)


Turn one of these projects into an executable [Okay but Tedious]
    - use sys.exit() instead of quit()
    pyinstaller, or cx_freeze

Make your own discord bot [variable difficulty] ( async )

Email me or comment for bigger programming (not specifically Python) project ideas

如有任何疑问,请发表评论。

感谢您的阅读,并祝您学习顺利。

翻译自: https://hackernoon.com/intermediate-python-refresher-tutorial-project-ideas-and-tips-i28s320p

python中级项目下载

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值