|
无论我们当前的技能水平如何,学习构建Python项目都是提高个人技能和增强作品集的必由之路。没有什么比亲自动手进行一些实际编码和构建Python项目更好的了!在本文中,我们收录了10个有趣的Python项目,从适合初学者的简单Python项目到中级和高级Python项目,我们可以利用它们来挑战自己或提高Python编程技能。适合初学者的Python项目让我们开始为初学者提供一系列项目,如果您刚刚开始并且想要学习Python,那么这是理想的选择。换言之,如果您渴望从事更具挑战性的事情,请阅读本文后面内容以查看更高级的项目。1.DiceRollGeneratorDiceRollGenerator(本文译为掷骰子生成器)作为与代码初学者最相关的Python项目之一,该程序模拟掷一两个骰子。这也是巩固对用户定义函数、循环和条件语句的理解的好方法。这些是Python初学者的基本技能,并且可能是您首先要学习的一些东西,无论是从在线课程还是Python书籍中。作为简单的Python项目之一,它是一个相当简单的程序,使用Pythonrandom模块来复制掷骰子的随机性质。您可能还会注意到,在掷骰子后,使用os模块来清除屏幕。请注意,可以将最大骰子值更改为任意数字,从而允许模拟许多棋盘游戏和角色扮演游戏中常用的多面体骰子。源代码:'''DiceRollGenerator-------------------------------------------------------------'''importrandomimportosdefnum_die():whileTrue:try:num_dice=input('Numberofdice:')valid_responses=['1','one','two','2']ifnum_dicenotinvalid_responses:raiseValueError('1or2only')else:returnnum_diceexceptValueErroraserr:print(err)defroll_dice():min_val=1max_val=6roll_again='y'whileroll_again.lower()=='yes'orroll_again.lower()=='y's.system('cls'ifos.name=='nt'else'clear')amount=num_die()ifamount=='2'oramount=='two':print('Rollingthedice...')dice_1=random.randint(min_val,max_val)dice_2=random.randint(min_val,max_val)print('Thevaluesare:')print('DiceOne:',dice_1)print('DiceTwo:',dice_2)print('Total:',dice_1+dice_2)roll_again=input('RollAgain?')else:print('Rollingthedie...')dice_1=random.randint(min_val,max_val)print(f'Thevalueis:{dice_1}')roll_again=input('RollAgain?')if__name__=='__main__':roll_dice()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253542.HangmanGame这是一个有趣的Python项目想法,用于模拟猜词游戏Hangman。在猜测方面使用了预定义的单词列表,但可以随意使用第三方词典API来改进这一点。此Python项目使用循环、函数和字符串格式来打印Hangman的进度。它还允许试验标准库的random、time和os模块。具体来说,使用random模块来选择要猜测的单词,并使用os模块来清除屏幕,以及使用time模块的.sleep()函数来引入暂停以增强游戏流程。如果您目前正在学习Python课程并且对这门语言仍然陌生,那么这是一个很好的中型项目,可以让您自我拓展!源代码:'''HangmanGame-------------------------------------------------------------'''importrandomimporttimeimportosdefplay_again():question='DoYouwanttoplayagain?y=yes,n=no\n'play_game=input(question)whileplay_game.lower()notin['y','n']:play_game=input(question)ifplay_game.lower()=='y':returnTrueelse:returnFalsedefhangman(word):display='_'*len(word)count=0limit=5letters=list(word)guessed=[]whilecount1:print('Invalidinput.Enterasingleletter\n')guess=input(f'HangmanWord:{display}Enteryourguess:\n').strip()ifguessinguessed:print('Oops!Youalreadytriedthatguess,tryagain!\n')continueifguessinletters:letters.remove(guess)index=word.find(guess)display=display[:index]+guess+display[index+1:]else:guessed.append(guess)count+=1ifcount==1:time.sleep(1)print('_____\n''|\n''|\n''|\n''|\n''|\n''|\n''__|__\n')print(f'Wrongguess:{limit-count}guessesremaining\n')elifcount==2:time.sleep(1)print('_____\n''||\n''||\n''|\n''|\n''|\n''|\n''__|__\n')print(f'Wrongguess:{limit-count}guessesremaining\n')elifcount==3:time.sleep(1)print('_____\n''||\n''||\n''||\n''|\n''|\n''|\n''__|__\n')print(f'Wrongguess:{limit-count}guessesremaining\n')elifcount==4:time.sleep(1)print('_____\n''||\n''||\n''||\n''|O\n''|\n''|\n''__|__\n')print(f'Wrongguess:{limit-count}guessesremaining\n')elifcount==5:time.sleep(1)print('_____\n''||\n''||\n''||\n''|O\n''|/|\\n''|/\\n''__|__\n')print('Wrongguess.You\'vebeenhanged!!!\n')print(f'Thewordwas:{word}')ifdisplay==word:print(f'Congrats!Youhaveguessedtheword\'{word}\'correctly!')breakdefplay_hangman():print('\nWelcometoHangman\n')name=input('Enteryourname:')print(f'Hello{name}!BestofLuck!')time.sleep(1)print('Thegameisabouttostart!\nLet\'splayHangman!')time.sleep(1)os.system('cls'ifos.name=='nt'else'clear')words_to_guess=['january','border','image','film','promise','kids','lungs','doll','rhyme','damage','plants','hello','world']play=Truewhileplay:word=random.choice(words_to_guess)hangman(word)play=play_again()print('ThanksForPlaying!Weexpectyoubackagain!')exit()if__name__=='__main__':play_hangman()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391403.CountdownClockandTimerCountdownClockandTimer(倒计时和计时器)这个Python项目的想法很有趣!在这里,我们创建了一个倒计时器,它通过用户输入要求用户输入几秒,然后一秒一秒地倒计时,直到显示一条消息。使用Python时间模块的.sleep()函数来暂停1秒的时间间隔,我们将其与一些实用的字符串格式结合起来以生成倒计时显示。源代码:'''CountdownTimer-------------------------------------------------------------'''importtimedefcountdown(user_time):whileuser_time>=0:mins,secs=divmod(user_time,60)timer='{:02d}:{:02d}'.format(mins,secs)print(timer,end='\r')time.sleep(1)user_time-=1print('Liftoff!')if__name__=='__main__':user_time=int(input("Enteratimeinseconds:"))countdown(user_time)1234567891011121314151617181920212223带有源代码的中级Python项目4.CurrencyConverterCurrencyConverter(货币转换器)是要求安装的Python库中最流行的Python项目想法之一,在本例中是requests模块。它不包含在Python标准库中,因此请使用源代码中显示的pip命令将其安装到系统上。通过requests模块,可以向FixerAPI发出HTTP请求,从而将一种货币转换为另一种,可能会注意到我们正在使用第3方API,因此需要注册才能获取免费的API密钥。然后可在源代码中显示的字段中输入API密钥,之后就可以开始了!该项目允许获得更多有关循环和用户输入的练习,但它通过HTTP请求对此进行了扩展,以检索JSON格式的API数据。如果不熟悉JSON,它与Python字典非常相似,这意味着可以访问键值对来获取我们想要的数据。在本例中正在查找API调用的货币换算结果。有关可检索的不同数据的更多详细信息。源代码:'''CurrencyConverter-------------------------------------------------------------pipinstallrequests'''importrequestsdefconvert_currency():init_currency=input('Enteraninitialcurrency:')target_currency=input('Enteratargetcurrency:')whileTrue:try:amount=float(input('Entertheamount:'))except:print('Theamountmustbeanumericvalue!')continueifnotamount>0:print('Theamountmustbegreaterthan0')continueelse:breakurl=('https://api.apilayer.com/fixer/convert?to='+target_currency+'&from='+init_currency+'&amount='+str(amount))payload={}headers={'apikey':'YOURAPIKEY'}response=requests.request('GET',url,headers=headers,data=payload)status_code=response.status_codeifstatus_code!=200:print('Uhoh,therewasaproblem.Pleasetryagainlater')quit()result=response.json()print('Conversionresult:'+str(result['result']))if__name__=='__main__':convert_currency()12345678910111213141516171819202122232425262728293031323334353637383940414243444546475.Pascal’sTriangle这个Python项目使用条件语句和循环打印出Pascal三角形。它还使用标准库的数学模块和阶乘函数来评估用于生成三角形中值的“组合数”方程。对三角形的种子数进行实验,以检查如何使用“组合”方程在三角形中生成连续值。源代码:'''Pascal'sTriangle-------------------------------------------------------------Numberofcombinationsvia"nchoosek"ornCk=n!/[k!*(n-k)!]'''frommathimportfactorialdefpascal_triangle(n):foriinrange(n):forjinrange(n-i+1):print(end='')forjinrange(i+1):print(factorial(i)//(factorial(j)*factorial(i-j)),end='')print()if__name__=='__main__':pascal_triangle(5)123456789101112131415161718192021222324256.BlackjackBlackjack作为最酷的Python项目之一,这将吸引任何喜欢纸牌游戏的人,因为我们将模拟Blackjack。这是一款超级流行的纸牌游戏,规则相对简单:最重要的是你需要21才能获胜,或者需要比庄家更高的分数而不至于破产!这是迄今为止清单上最大的项目。它结合了在以前的项目中已经介绍过的大部分技能,包括创建类、循环、条件语句、导入模块、接受用户输入和字符串格式化。花点时间研究此代码的不同部分,并将其与早期的项目联系起来,以了解不同的技术如何协同工作。没有什么是你没见过的;它只是打包方式略有不同,并组合起来创建一个功能齐全的游戏模拟器。源代码:'''Blackjack-------------------------------------------------------------'''importrandomimportosclassCard:def__init__(self,card_face,value,symbol):self.card_face=card_faceself.value=valueself.symbol=symboldefshow_cards(cards,hidden):s=''forcardincards:s=s+'\t________________'ifhidden:s+='\t________________'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t||'print(s)s=''forcardincards:ifcard.card_facein['J','Q','K','A']:s=s+'\t|{}|'.format(card.card_face)elifcard.value==10:s=s+'\t|{}|'.format(card.value)else:s=s+'\t|{}|'.format(card.value)ifhidden:s+='\t||'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t|**|'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t|**|'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t|**|'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t|**|'print(s)s=''forcardincards:s=s+'\t|{}|'.format(card.symbol)ifhidden:s+='\t|*|'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t|*|'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t|*|'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t||'print(s)s=''forcardincards:s=s+'\t||'ifhidden:s+='\t||'print(s)s=''forcardincards:ifcard.card_facein['J','Q','K','A']:s=s+'\t|{}|'.format(card.card_face)elifcard.value==10:s=s+'\t|{}|'.format(card.value)else:s=s+'\t|{}|'.format(card.value)ifhidden:s+='\t|*|'print(s)s=''forcardincards:s=s+'\t|________________|'ifhidden:s+='\t|________________|'print(s)print()defdeal_card(deck):card=random.choice(deck)deck.remove(card)returncard,deckdefplay_blackjack(deck):player_cards=[]dealer_cards=[]player_score=0dealer_score=0os.system('clear')whilelen(player_cards)21andcard_pos21:breakos.system('clear')print('DEALERCARDS:')show_cards(dealer_cards[:-1],True)print('DEALERSCORE=',dealer_score-dealer_cards[-1].value)print()print('PLAYERCARDS:')show_cards(player_cards,False)print('PLAYERSCORE=',player_score)os.system('clear')print('PLAYERCARDS:')show_cards(player_cards,False)print('PLAYERSCORE=',player_score)print()print('DEALERISREVEALINGTHEIRCARDS....')print('DEALERCARDS:')show_cards(dealer_cards,False)print('DEALERSCORE=',dealer_score)ifplayer_score==21:print('PLAYERHASABLACKJACK,PLAYERWINS!!!')quit()ifplayer_score>21:print('PLAYERBUSTED!!!GAMEOVER!!!')quit()input('Continue...')whiledealer_score21andcard_pos21:breakinput('Continue...')ifdealer_score>21:print('DEALERBUSTED!!!YOUWIN!!!')quit()elifdealer_score==21:print('DEALERHASABLACKJACK!!!PLAYERLOSES!!!')quit()elifdealer_score==player_score:print('TIEGAME!!!!')elifplayer_score>dealer_score:print('PLAYERWINS!!!')else:print('DEALERWINS!!!')definit_deck():suits=['Spades','Hearts','Clubs','Diamonds']#UNICODEvaluesforcardsymbolimagessuit_symbols={'Hearts':'\u2661','Diamonds':'\u2662','Spades':'\u2664','Clubs':'\u2667'}cards={'A':11,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}deck=[]forsuitinsuits:forcard,valueincards.items():deck.append(Card(card,value,suit_symbols[suit]))returndeckif__name__=='__main__':deck=init_deck()play_blackjack(deck)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310高级Python项目7.TexttoSpeech(文字转语音)此Python项目使用一系列新库将现有文章转换为可播放的mp3文件。需要安装nltk(自然语言工具包)、newspaper3k和gtts。您会发现该程序很简单,我们只需传入要转换的文章的URL,然后让定义的函数使用新安装的模块处理文本到语音的转换。因此,下次当您想将文章变成可播放的播客时,请考虑尝试一下,它绝对是值得复制的很酷的Python代码之一!源代码:'''TextToSpeech-------------------------------------------------------------pipinstallnltknewspaper3kgtts'''importnltkfromnewspaperimportArticlefromgttsimportgTTSdeftext_to_speech(url):article=Article(url)article.download()article.parse()nltk.download('punkt')article.nlp()article_text=article.textlanguage='en'my_obj=gTTS(text=article_text,lang=language,slow=False)my_obj.save("read_article.mp3")if__name__=='__main__':text_to_speech(url='https://hackr.io/blog/top-tech-companies-hiring-python-developers')12345678910111213141516171819202122232425262728298.PongArcadeGamePongArcadeGame是一个非常有趣的项目,因为我们使用Pythonturtle模块来模拟经典街机游戏Pong!我们使用了turtle模块中的各种方法来创建游戏组件,并检测球与玩家球拍的碰撞。我们还定义了一系列键绑定,以设置左右玩家划桨的用户控件。请随意尝试游戏的设置,以更好地了解每个设置是如何工作和影响整个游戏。除了这些新引入的turtle图形函数之外,还使用字符串格式来输出当前记分板和用户定义的函数,以保持代码整洁,这些是现阶段应该熟悉的概念。源代码:'''PongArcadeGame-------------------------------------------------------------'''importturtledefupdate_score(l_score,r_score,player,score_board):ifplayer=='l':l_score+=1else:r_score+=1score_board.clear()score_board.write('LeftPlayer:{}--RightPlayer:{}'.format(l_score,r_score),align='center',font=('Arial',24,'normal'))returnl_score,r_score,score_boarddefsetup_game():screen=turtle.Screen()screen.title('PongArcadeGame')screen.bgcolor('white')screen.setup(width=1000,height=600)l_paddle=turtle.Turtle()l_paddle.speed(0)l_paddle.shape('square')l_paddle.color('red')l_paddle.shapesize(stretch_wid=6,stretch_len=2)l_paddle.penup()l_paddle.goto(-400,0)r_paddle=turtle.Turtle()r_paddle.speed(0)r_paddle.shape('square')r_paddle.color('black')r_paddle.shapesize(stretch_wid=6,stretch_len=2)r_paddle.penup()r_paddle.goto(400,0)ball=turtle.Turtle()ball.speed(40)ball.shape('circle')ball.color('blue')ball.penup()ball.goto(0,0)ball.dx=5ball.dy=-5score_board=turtle.Turtle()score_board.speed(0)score_board.color('blue')score_board.penup()score_board.hideturtle()score_board.goto(0,260)score_board.write('LeftPlayer:0--RightPlayer:0',align='center',font=('Arial',24,'normal'))returnscreen,ball,l_paddle,r_paddle,score_boarddefpong_game():game_components=setup_game()screen=game_components[0]ball=game_components[1]l_paddle=game_components[2]r_paddle=game_components[3]score_board=game_components[4]l_score=0r_score=0defl_paddle_up():l_paddle.sety(l_paddle.ycor()+20)defl_paddle_down():l_paddle.sety(l_paddle.ycor()-20)defr_paddle_up():r_paddle.sety(r_paddle.ycor()+20)defr_paddle_down():r_paddle.sety(r_paddle.ycor()-20)screen.listen()screen.onkeypress(l_paddle_up,'e')screen.onkeypress(l_paddle_down,'x')screen.onkeypress(r_paddle_up,'Up')screen.onkeypress(r_paddle_down,'Down')whileTrue:screen.update()ball.setx(ball.xcor()+ball.dx)ball.sety(ball.ycor()+ball.dy)ifball.ycor()>280:ball.sety(280)ball.dy*=-1ifball.ycor()500:ball.goto(0,0)ball.dy*=-1l_score,r_score,score_board=update_score(l_score,r_score,'l',score_board)continueelifball.xcor()360)and(ball.xcor()r_paddle.ycor()-40)):ball.setx(360)ball.dx*=-1if((ball.xcor()-370)and(ball.ycor()l_paddle.ycor()-40)):ball.setx(-360)ball.dx*=-1if__name__=='__main__':pong_game()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371389.TextEditor(文本编辑器)这个有趣的Python项目以最后一个tkinter示例为基础,创建了一个GUI来模拟自己的文本编辑器。此示例还使用标准GUI组件,包括标签、按钮和输入字段。不过还添加了像真正的文本编辑器一样打开和保存文件的功能。如果不熟悉文件处理,那么这个Python项目是了解如何读入和保存文件的好方法。尝试使用下面的代码来巩固您的理解,并看看是否可以扩展此代码以创建您习惯于在文本编辑器中使用的其他功能,例如“查找单词”功能。源代码:'''TextEditor-------------------------------------------------------------'''importtkinterastkfromtkinter.filedialogimportaskopenfilename,asksaveasfilenamedeftext_editor():defopen_file():filepath=askopenfilename(filetypes=[('TextFiles','*.txt'),('AllFiles','*.*')])ifnotfilepath:returntxt_edit.delete(1.0,tk.END)withopen(filepath,'r')asinput_file:text=input_file.read()txt_edit.insert(tk.END,text)window.title(f'TextEditor-{filepath}')defsave_file():filepath=asksaveasfilename(defaultextension='txt',filetypes=[('TextFiles','*.txt'),('AllFiles','*.*')],)ifnotfilepath:returnwithopen(filepath,'w')asoutput_file:text=txt_edit.get(1.0,tk.END)output_file.write(text)window.title(f'TextEditor-{filepath}')window=tk.Tk()window.title('TextEditor')window.rowconfigure(0,minsize=800,weight=1)window.columnconfigure(1,minsize=800,weight=1)txt_edit=tk.Text(window)fr_buttons=tk.Frame(window,relief=tk.RAISED,bd=2)btn_open=tk.Button(fr_buttons,text='Open',command=open_file)btn_save=tk.Button(fr_buttons,text='SaveAs...',command=save_file)btn_open.grid(row=0,column=0,sticky='ew',padx=5,pady=5)btn_save.grid(row=1,column=0,sticky='ew',padx=5)fr_buttons.grid(row=0,column=0,sticky='ns')txt_edit.grid(row=0,column=1,sticky='nsew')window.mainloop()if__name__=='__main__':text_editor()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606110.SpeedTypingTest(快速打字测试)SpeedTypingTest是一个有趣的Python项目,它测试你能多快准确地打出一个句子。该程序要求我们通过tkinter模块创建图形用户界面(GUI)。如果您是GUI新手,这个示例是一个很好的介绍,我们使用一系列简单的标签、按钮和输入字段来创建窗口,还使用Pythontimeit模块来处理打字测试的计时方面,并使用random模块来随机选择测试短语。仅在此示例中添加了两个测试短语,但可以随意尝试更多甚至集成第三方词典以获得更广泛的示例。源代码:'''SpeedTypingTest-------------------------------------------------------------'''importtkinterfromtimeitimportdefault_timerastimerimportrandomdefspeed_test():speed_test_sentences=['Thisisarandomsentencetocheckspeed.','Speed,Iamlightningmcqueen.']sentence=random.choice(speed_test_sentences)start=timer()main_window=tkinter.Tk()main_window.geometry('600x400')label_1=tkinter.Label(main_window,text=sentence,font='times20')label_1.place(x=150,y=10)label_2=tkinter.Label(main_window,text='StartTyping',font='times20')label_2.place(x=10,y=50)entry=tkinter.Entry(main_window)entry.place(x=280,y=55)defcheck_result():ifentry.get()==sentence:end=timer()label_3.configure(text=f'Time:{round((end-start),4)}s')else:label_3.configure(text='WrongInput')button_1=tkinter.Button(main_window,text='Done',command=check_result,width=12,bg='grey')button_1.place(x=150,y=100)button_2=tkinter.Button(main_window,text='TryAgain',command=speed_test,width=12,bg='grey')button_2.place(x=250,y=100)label_3=tkinter.Label(main_window,text='',font='times20')label_3.place(x=10,y=300)main_window.mainloop()if__name__=='__main__':speed_test()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455需要100个实战项目资源请关注+留言获取
|
|