搜尋
首頁後端開發Python教學適合初學者的 Python 專案及其原始碼

Beginner-Friendly Python Projects with Source Code

介紹

從適合初學者的 Python 專案開始是鞏固您對編碼基礎知識的理解的絕佳方法。當您從事這些小型專案時,您將提高基本技能,包括使用資料類型、管理使用者輸入、使用條件和處理基本邏輯。這些專案旨在供程式設計新手使用,並將幫助您以實用的方式練習 Python 概念。下面,我們將介紹五個流行的 Python 項目,並附有逐步指南和程式碼範例。

1. 基本計算器

為什麼這個項目?

計算器是一個結合了使用者輸入、函數定義和基本算術的基礎項目。它非常適合初學者,因為它教授函數使用和基本錯誤處理(例如除以零)等核心概念。該專案也強調可重複使用程式碼,因為每個操作(加法、減法等)都可以分成自己的函數。

項目描述:

此計算器根據使用者輸入執行基本運算 - 加法、減法、乘法和除法。

逐步指南:

  • 為每個運算定義一個函數(加法、減法等)。

  • 建立接受使用者輸入數字和操作類型的主函數。

  • 使用簡單的條件檢查處理除以零。

  • 根據使用者輸入呼叫適當的函數。

原始碼:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error: Division by zero"
    return x / y

def calculator():
    print("Select operation: 1. Add 2. Subtract 3. Multiply 4. Divide")
    choice = input("Enter choice (1/2/3/4): ")
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(f"Result: {add(num1, num2)}")
        elif choice == '2':
            print(f"Result: {subtract(num1, num2)}")
        elif choice == '3':
            print(f"Result: {multiply(num1, num2)}")
        elif choice == '4':
            print(f"Result: {divide(num1, num2)}")
    else:
        print("Invalid input")

calculator()

2. 待辦事項清單應用程式

為什麼這個項目?

待辦事項清單應用程式可協助您練習資料儲存、循環和條件。這也是在控制台中建立使用者介面的簡單介紹。透過使用列表,您將學習如何管理多個項目以及如何使用循環來顯示和操作資料。

項目描述:

建立一個基本的待辦事項列表,使用者可以在其中新增、檢視和刪除任務。

逐步指南:

  • 定義一個清單來儲存任務。

  • 建立新增、顯示和刪除任務的函數。

  • 使用循環導航選單選項並為每個操作取得使用者輸入。

  • 將任務列印在編號清單中以方便參考。

原始碼:

tasks = []

def add_task():
    task = input("Enter a new task: ")
    tasks.append(task)
    print(f"Task '{task}' added.")

def view_tasks():
    if not tasks:
        print("No tasks available.")
    else:
        for i, task in enumerate(tasks, start=1):
            print(f"{i}. {task}")

def delete_task():
    view_tasks()
    try:
        task_num = int(input("Enter task number to delete: ")) - 1
        removed_task = tasks.pop(task_num)
        print(f"Task '{removed_task}' deleted.")
    except (IndexError, ValueError):
        print("Invalid task number.")

def menu():
    while True:
        print("\n1. Add Task  2. View Tasks  3. Delete Task  4. Exit")
        choice = input("Enter your choice: ")
        if choice == '1':
            add_task()
        elif choice == '2':
            view_tasks()
        elif choice == '3':
            delete_task()
        elif choice == '4':
            print("Exiting To-Do List App.")
            break
        else:
            print("Invalid choice. Please try again.")

menu()

3. 猜數字遊戲

為什麼這個項目?

猜謎遊戲向您介紹循環、條件和隨機性。此專案非常適合理解控制流程和使用者互動的基礎知識。它還教您處理用戶回饋,這對於創建引人入勝的程式至關重要。

項目描述:

在這個猜謎遊戲中,程式隨機選擇一個數字,玩家嘗試在一定範圍內猜測它。

逐步指南:

  • 使用隨機模組產生隨機數。

  • 創建一個循環,允許玩家多次猜測。

如果猜測過高或過低,請提供回饋。一旦猜到正確的數字,就會顯示嘗試次數。

原始碼:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error: Division by zero"
    return x / y

def calculator():
    print("Select operation: 1. Add 2. Subtract 3. Multiply 4. Divide")
    choice = input("Enter choice (1/2/3/4): ")
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(f"Result: {add(num1, num2)}")
        elif choice == '2':
            print(f"Result: {subtract(num1, num2)}")
        elif choice == '3':
            print(f"Result: {multiply(num1, num2)}")
        elif choice == '4':
            print(f"Result: {divide(num1, num2)}")
    else:
        print("Invalid input")

calculator()

4. 簡單密碼產生器

為什麼這個項目?

產生密碼是了解字串運算和隨機性的好方法。此專案可以幫助您練習產生隨機序列,並加強您對資料類型和使用者定義函數的理解。

項目描述:

密碼產生器根據字母、數字和符號的組合建立隨機密碼。

逐步指南:

  • 使用字串和隨機模組建立字元池。

  • 建立一個函數來隨機選擇使用者定義的密碼長度的字元。

  • 將產生的密碼輸出給使用者。

原始碼:

tasks = []

def add_task():
    task = input("Enter a new task: ")
    tasks.append(task)
    print(f"Task '{task}' added.")

def view_tasks():
    if not tasks:
        print("No tasks available.")
    else:
        for i, task in enumerate(tasks, start=1):
            print(f"{i}. {task}")

def delete_task():
    view_tasks()
    try:
        task_num = int(input("Enter task number to delete: ")) - 1
        removed_task = tasks.pop(task_num)
        print(f"Task '{removed_task}' deleted.")
    except (IndexError, ValueError):
        print("Invalid task number.")

def menu():
    while True:
        print("\n1. Add Task  2. View Tasks  3. Delete Task  4. Exit")
        choice = input("Enter your choice: ")
        if choice == '1':
            add_task()
        elif choice == '2':
            view_tasks()
        elif choice == '3':
            delete_task()
        elif choice == '4':
            print("Exiting To-Do List App.")
            break
        else:
            print("Invalid choice. Please try again.")

menu()

5. 石頭剪刀布遊戲

為什麼這個項目?

這款經典遊戲透過條件和隨機性以及使用者輸入處理來增強您的技能。這也是對遊戲邏輯和編寫函數的一個很好的介紹,用於比較選擇並確定獲勝者。

項目描述:

這個版本的石頭剪刀布讓玩家與電腦對戰。

逐步指南:

  • 建立一個選擇清單(石頭、布、剪刀)。

  • 使用 random.choice() 進行電腦的移動,使用 input() 進行玩家的選擇。

  • 比較選擇以確定獲勝者。

  • 顯示結果並提示再次播放。

原始碼:

import random

def guessing_game():
    number_to_guess = random.randint(1, 100)
    attempts = 0
    print("Guess the number between 1 and 100.")

    while True:
        guess = int(input("Enter your guess: "))
        attempts += 1
        if guess  number_to_guess:
            print("Too high!")
        else:
            print(f"Congratulations! You've guessed the number in {attempts} attempts.")
            break

guessing_game()

結論

完成這些初學者 Python 專案將為您提供基本程式設計概念的實務經驗並提高您的信心。每個專案都提供實用知識,隨著您的技能增長,這些知識可以擴展到更複雜的應用程式。試驗代碼,添加您自己的功能,看看您的創造力將帶您走向何方!

如果您對任何項目有任何疑問都可以問我。

以上是適合初學者的 Python 專案及其原始碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用