これらのプロジェクトで Python の基礎をすべてカバー |クイズからパスワードマネージャーまで。
プロジェクトを作成することは、学んだことを実践に移すための最良の方法です。これらのプロジェクトはシンプルで簡単に見えるかもしれませんが、Python プログラミングの強力な基盤を構築する上で重要な役割を果たします。これらのプロジェクトは、Python の基本のほとんどをカバーし、誰もが実践的な練習を通じてコーディング スキルを学び向上できるようにするために作成しました。
1. クイズゲーム
これは何ですか? コンピューターが質問し、プレイヤーがそれに答えるシンプルなクイズ ゲームです。
使用される概念:
- リストとタプル
- ランダムモジュール
- ループ
- 条件文
- ユーザー入力の処理
- スコア追跡
仕組み: ゲームは、プレイヤーを歓迎し、プレイしたいかどうかを尋ねることから始まります。次に、事前定義されたリストからランダム化された一連の質問が提示されます。プレイヤーの答えがチェックされ、それに応じてスコアが更新されます。ゲームでは各回答に対するフィードバックが提供され、最後に最終スコアが表示されます。
import random # Import the random module for shuffling print("Welcome to the Quiz Game") # Print welcome message wanna_play = input("Do you want to play the game (yes/no): ").lower() # Ask if the user wants to play if wanna_play != 'yes': # If user does not want to play, quit quit() print("Okay, then! Let's play") # Print message to start the game # Creating a list of tuples containing questions and answers question_answer_pairs = [ ("What does CPU stand for?", "Central Processing Unit"), ("Which programming language is known as the 'mother of all languages'?", "C"), ("What does HTML stand for?", "HyperText Markup Language"), # ... (more questions) ] # Shuffle the list of tuples to ensure random order random.shuffle(question_answer_pairs) score = 0 # Iterate through the shuffled list of tuples for question, correct_answer in question_answer_pairs: user_answer = input(f"{question} ").strip() # Ask the question and get user input if user_answer.lower() == correct_answer.lower(): # Check if the answer is correct print("Correct answer") score += 1 # Increase score for a correct answer else: print(f"Incorrect answer. The correct answer is: {correct_answer}") score -= 1 # Decrease score for an incorrect answer print(f"Current Score: {score}") # Print the final score print(f"Quiz over! Your final score is {score}/{len(question_answer_pairs)}")
2. 数字当てゲーム (コンピューター当て)
これは何ですか? ユーザーが選択した数字をコンピューターが推測する数字推測ゲームです。
使用される概念:
- 機能
- ループ
- 条件文
- ユーザー入力の処理
- 二分探索アルゴリズム
仕組み: ユーザーは範囲を定義し、その範囲内の数値を選択します。次に、コンピューターは二分探索アプローチを使用して数値を推測し、ユーザーはその推測が高すぎるか、低すぎるか、または正しいかについてフィードバックを提供します。ゲームは、コンピュータが正しく推測するか、数値が指定された範囲外であると判断するまで続きます。
def guess_number(): """ Function where the computer attempts to guess a number chosen by the user within a specified range. The user defines the lower and upper bounds of the range and provides a number for the computer to guess. The computer uses a binary search approach to guess the number and the user provides feedback to guide it. """ # Get the lower bound of the range from the user low = int(input("Enter the lower range: ")) # Get the upper bound of the range from the user high = int(input("Enter the higher range: ")) # Check if the provided range is valid if low >= high: print("Invalid range. The higher range must be greater than the lower range.") return # Exit the function if the range is invalid # Get the number from the user that the computer will attempt to guess Your_number = int(input(f"Enter your number for the computer to guess between {low} and {high}: ")) # Check if the number entered by the user is within the specified range if Your_number < low or Your_number > high: print("The number you entered is out of the specified range.") return # Exit the function if the number is out of the range # Initialize the computer's guess variable computer_guess = None # Loop until the computer guesses the correct number while computer_guess != Your_number: # Compute the computer's guess as the midpoint of the current range computer_guess = (low + high) // 2 print(f"The computer guesses: {computer_guess}") # Get feedback from the user about the computer's guess feedback = input(f"Is {computer_guess} too low, too high, or correct? (Enter 'h' for higher, 'l' for lower, 'c' for correct): ").strip().lower() # Process the user's feedback to adjust the guessing range if feedback == 'c': if computer_guess == Your_number: print("The computer guessed your number correctly! Congrats!") return # Exit the function once the correct number is guessed else: continue elif feedback == 'h': high = computer_guess - 1 # If the guess is too high, lower the upper range elif feedback == 'l': low = computer_guess + 1 # If the guess is too low, increase the lower range else: print("Invalid feedback, please enter 'h', 'l', or 'c'.") # Handle invalid feedback # Call the function to start the guessing game guess_number()
3. 数字当てゲーム (ユーザー当て)
これは何ですか? ユーザーがランダムに生成された数字を推測する数字推測ゲームです。
使用される概念:
- 機能
- ランダムモジュール
- ループ
- 条件文
- 例外処理
- ユーザー入力の検証
仕組み: コンピューターは指定された範囲内の乱数を生成します。ユーザーは推測を行い、プログラムは推測が高すぎるか低すぎるかに関するフィードバックを提供します。ゲームは、ユーザーが正しい数字を推測するか、終了するまで続きます。
import random # Import the random module to use its functions for generating random numbers def guess_random_number(number): """ Function to allow the user to guess a random number between 1 and the specified `number`. This function generates a random integer between 1 and the provided `number` (inclusive). It then repeatedly prompts the user to guess the random number, providing feedback on whether the guess is too high or too low, until the correct number is guessed. The function handles invalid inputs by catching exceptions and informing the user to enter a valid integer. """ # Generate a random number between 1 and the specified `number` (inclusive) random_number = random.randint(1, number) guess = None # Initialize the variable `guess` to None before starting the loop # Loop until the user guesses the correct number while guess != random_number: try: # Prompt the user to enter a number between 1 and `number` guess = int(input(f"Enter a number between 1 and {number}: ")) # Provide feedback based on whether the guess is too low or too high if guess < random_number: print("Too low, guess a greater number.") elif guess > random_number: print("Too high, guess a smaller number.") except ValueError: # Handle the case where the user inputs something that isn't an integer print("Invalid input. Please enter a valid integer.") # Congratulate the user once they guess the correct number print("You have guessed the random number correctly. Congrats!") # Call the function with an upper limit of 10 guess_random_number(10)
4. ハングマンゲーム
これは何ですか? プレイヤーが隠された単語を 1 文字ずつ推測する古典的な単語推測ゲームです。
使用される概念:
- モジュールのインポート
- リストからランダムに選択
- 文字列操作
- ループ
- 条件文
- リスト内包表記
仕組み: ゲームは、事前定義されたリストからランダムな単語を選択します。その後、プレイヤーは一度に 1 文字ずつ推測します。推測が正しければ単語内の文字の位置がわかりますが、推測が間違っていればプレイヤーの残りライフが減ります。プレイヤーが単語全体を推測するか、ライフがなくなるとゲームは終了します。
import random from word_list import words # Import the words from word_list.py file def hangman(): random_word = random.choice(words) # Generate the random word print(random_word) # Print the chosen word for testing purposes; remove in production word_display = ["_"] * len(random_word) # Create blank lines "_" equal to the length of the word guessed_letters = [] # Empty list to store the letters that have been guessed lives = 5 # Number of lives for the player print("Welcome to Hangman!") # Print welcome statement print(" ".join(word_display)) # Display the current state of the word while lives > 0: # The game continues to run as long as the player has more than 0 lives user_guess = input("Enter a single letter for your guess: ").lower() # Ask the player to input a letter # Check whether the player entered a valid input if len(user_guess) != 1 or not user_guess.isalpha(): print("Invalid input. Please enter a single letter.") continue # Check if the letter has already been guessed if user_guess in guessed_letters: print(f"You've already guessed '{user_guess}'. Try another guess.") continue # Add the guessed letter to the guessed_letters list guessed_letters.append(user_guess) # Check if the guessed letter is in the random_word if user_guess in random_word: # Update word_display with the correctly guessed letter for index, letter in enumerate(random_word): if letter == user_guess: word_display[index] = user_guess print("Good guess!") else: lives -= 1 # Reduce the number of remaining lives by 1 for an incorrect guess print(f"Wrong guess! Remaining lives: {lives}") # Display the current state of the word print(" ".join(word_display)) # Check if the player has guessed all letters if "_" not in word_display: print("Congratulations, you guessed the word!") break else: # This runs if no lives are left print(f"You have run out of lives. The word was: {random_word}") hangman() # Function to start the game
5.じゃんけん
これは何ですか? ユーザーがコンピューターと対戦する古典的な「じゃんけん」ゲームです。
使用される概念:
- ループ
- 条件文
- 機能
- ランダムモジュール
- ユーザー入力の処理
仕組み: ユーザーはジャンケン、ペーパー、またはチョキのいずれかを選択し、コンピューターも同様にオプションの 1 つをランダムに選択します。次に、プログラムは選択肢を比較して勝者を決定し、ユーザーにもう一度プレイするかどうかを尋ねます。
import random # Import the random module to generate random choices for the computer. def playGame(): while True: # Infinite loop to keep the game running until the user decides to stop. # Ask the user to enter their choice and convert it to lowercase. user_choice = input("Enter 'r' for rock, 'p' for paper, 's' for scissors: ").strip().lower() # Check if the user input is valid (i.e., 'r', 'p', or 's'). if user_choice not in ['r', 'p', 's']: print("Invalid Input. Please try again.") continue # If the input is invalid, restart the loop. print(f"You chose {user_choice}") # Display the user's choice. # Computer randomly picks one of the choices ('r', 'p', 's'). computer_choice = random.choice(['r', 'p', 's']) print(f"The computer chose {computer_choice}") # Display the computer's choice. # Check if the user's choice is the same as the computer's choice. if user_choice == computer_choice: print("It's a tie.") # It's a tie if both choices are the same. elif _iswinner(user_choice, computer_choice): print("You won!") # The user wins if their choice beats the computer's choice. else: print("You lost.") # The user loses if the computer's choice beats theirs. # Ask the user if they want to play again. play_again = input("Do you want to play again? Enter 'yes' or 'no': ").strip().lower() # If the user doesn't enter 'yes', end the game. if play_again != 'yes': print("Thank you for playing!") # Thank the user for playing. break # Exit the loop and end the game. def _iswinner(user, computer): # Determine if the user's choice beats the computer's choice. # Rock ('r') beats Scissors ('s'), Scissors ('s') beat Paper ('p'), Paper ('p') beats Rock ('r'). if (user == "r" and computer == "s") or (user == "p" and computer == "r") or (user == "s" and computer == "p"): return True # Return True if the user wins. # Start the game by calling the playGame function. playGame()
6. 2 ユーザー ティック タック トゥ
それは何ですか 三目並べは、プレイヤーが 3x3 のグリッド上のスペースを順番にマークする古典的な 2 人用ゲームです。目標は、水平、垂直、または斜めのいずれかで、最初に 3 つのマークを連続して取得することです。 1 人のプレイヤーがこれを達成するか、勝者なしでグリッド上のすべてのスペースが埋まり、結果的に引き分けになると、ゲームは終了します。
*使用される概念: *
- 関数の定義と呼び出し
- データ構造 (2D リスト)
- ループ (for、while)
- 条件文 (if、else)
- 入力の処理と検証
- ゲーム状態管理
- 文字列の書式設定
- 例外処理
def print_board(board): """Prints the game board in a structured format with borders.""" print("\n+---+---+---+") # Print the top border of the board for row in board: # print each row with cell values separated by borders print("| " + " | ".join(row) + " |") # print the border after each row print("+---+---+---+") def check_winner(board): """Checks for a winner or a draw.""" # define all possible winning lines: rows, columns, and diagonals lines = [ [board[0][0], board[0][1], board[0][2]], # Row 1 [board[1][0], board[1][1], board[1][2]], # Row 2 [board[2][0], board[2][1], board[2][2]], # Row 3 [board[0][0], board[1][0], board[2][0]], # Column 1 [board[0][1], board[1][1], board[2][1]], # Column 2 [board[0][2], board[1][2], board[2][2]], # Column 3 [board[0][0], board[1][1], board[2][2]], # Diagonal from top-left to bottom-right [board[0][2], board[1][1], board[2][0]] # Diagonal from top-right to bottom-left ] # Check each line to see if all three cells are the same and not empty for line in lines: if line[0] == line[1] == line[2] and line[0] != ' ': return line[0] # Return the player ('X' or 'O') who has won # Check if all cells are filled and there is no winner if all(cell != ' ' for row in board for cell in row): return 'Draw' # Return 'Draw' if the board is full and no winner return None # Return None if no winner and the game is not a draw def main(): """Main function to play the Tic Tac Toe game.""" # Initialize the board with empty spaces board = [[' ' for _ in range(3)] for _ in range(3)] current_player = 'X' # Start with player 'X' while True: print_board(board) # Print the current state of the board try: # Prompt the current player for their move move = input(f"Player {current_player}, enter your move (1-9): ") move = int(move) # Convert the input to an integer # Check if the move is valid (between 1 and 9) if move < 1 or move > 9: print("Invalid move, try again.") continue # Ask for a new move except ValueError: # Handle cases where the input is not an integer print("Invalid move, try again.") continue # Ask for a new move # Convert the move number to board coordinates (row, col) row, col = divmod(move - 1, 3) # Check if the cell is already occupied if board[row][col] != ' ': print("Cell already occupied. Choose a different cell.") continue # Ask for a new move # Place the current player's mark on the board board[row][col] = current_player # Check if there is a winner or if the game is a draw winner = check_winner(board) if winner: print_board(board) # Print the final board state if winner == 'Draw': print("The game is a draw!") else: print(f"Player {winner} wins!") # Announce the winner break # End the game # Switch players current_player = 'O' if current_player == 'X' else 'X' if __name__ == "__main__": main() # Start the game
7. パスワードマネージャー
これは何ですか? ユーザーが暗号化されたパスワードを保存および取得できるようにするシンプルなパスワード マネージャーです。
Concepts used:
- File I/O operations
- Encryption using the cryptography library
- Functions
- Exception handling
- User input handling
- Loops
How it works: The program uses the Fernet symmetric encryption from the cryptography library to securely store passwords. Users can add new passwords or view existing ones. Passwords are stored in an encrypted format in a text file, and decrypted when viewed.
from cryptography.fernet import Fernet # The write_key function generates an encryption key and saves it to a file. # It's currently commented out, but you need to run it once to create the 'key.key' file. ''' def write_key(): key = Fernet.generate_key() with open("key.key", "wb") as key_file: key_file.write(key) ''' def load_key(): """This function loads the encryption key from the 'key.key' file.""" file = open("key.key", "rb") key = file.read() file.close() return key # Load the key and create a Fernet object key = load_key() fer = Fernet(key) def view(): """Function to view stored passwords in the 'passwords.txt' file""" with open('passwords.txt', 'r') as f: for line in f.readlines(): data = line.rstrip() user, passw = data.split("|") decrypted_password = fer.decrypt(passw.encode()).decode() print("User:", user, "| Password:", decrypted_password) def add(): """Function to add new account names and passwords to the 'passwords.txt' file""" name = input('Account Name: ') pwd = input("Password: ") with open('passwords.txt', 'a') as f: encrypted_password = fer.encrypt(pwd.encode()).decode() f.write(name + "|" + encrypted_password + "\n") # Main loop to ask the user what they want to do: view passwords, add new passwords, or quit while True: mode = input( "Would you like to add a new password or view existing ones (view, add), press q to quit? ").lower() if mode == "q": break if mode == "view": view() elif mode == "add": add() else: print("Invalid mode.") continue
Thanks for stopping and reading the blog.
Github Repo : https://github.com/iamdipsan/Python-Projects
以上がこれらのプロジェクトで Python の基礎をすべてカバー |クイズからパスワードマネージャーまで。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Pythonは学習と使用が簡単ですが、Cはより強力ですが複雑です。 1。Python構文は簡潔で初心者に適しています。動的なタイピングと自動メモリ管理により、使いやすくなりますが、ランタイムエラーを引き起こす可能性があります。 2.Cは、高性能アプリケーションに適した低レベルの制御と高度な機能を提供しますが、学習しきい値が高く、手動メモリとタイプの安全管理が必要です。

Pythonを1日2時間学ぶだけで十分ですか?それはあなたの目標と学習方法に依存します。 1)明確な学習計画を策定し、2)適切な学習リソースと方法を選択します。3)実践的な実践とレビューとレビューと統合を練習および統合し、統合すると、この期間中にPythonの基本的な知識と高度な機能を徐々に習得できます。

Pythonは開発効率でCよりも優れていますが、Cは実行パフォーマンスが高くなっています。 1。Pythonの簡潔な構文とリッチライブラリは、開発効率を向上させます。 2.Cのコンピレーションタイプの特性とハードウェア制御により、実行パフォーマンスが向上します。選択を行うときは、プロジェクトのニーズに基づいて開発速度と実行効率を比較検討する必要があります。

PythonとCにはそれぞれ独自の利点があり、選択はプロジェクトの要件に基づいている必要があります。 1)Pythonは、簡潔な構文と動的タイピングのため、迅速な開発とデータ処理に適しています。 2)Cは、静的なタイピングと手動メモリ管理により、高性能およびシステムプログラミングに適しています。

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

Pythonは、自動化、スクリプト、およびタスク管理に優れています。 1)自動化:OSやShutilなどの標準ライブラリを介してファイルバックアップが実現されます。 2)スクリプトの書き込み:Psutilライブラリを使用してシステムリソースを監視します。 3)タスク管理:スケジュールライブラリを使用してタスクをスケジュールします。 Pythonの使いやすさと豊富なライブラリサポートにより、これらの分野で優先ツールになります。

科学コンピューティングにおけるPythonのアプリケーションには、データ分析、機械学習、数値シミュレーション、視覚化が含まれます。 1.numpyは、効率的な多次元配列と数学的関数を提供します。 2。ScipyはNumpy機能を拡張し、最適化と線形代数ツールを提供します。 3. Pandasは、データ処理と分析に使用されます。 4.matplotlibは、さまざまなグラフと視覚的な結果を生成するために使用されます。

Web開発におけるPythonの主要なアプリケーションには、DjangoおよびFlaskフレームワークの使用、API開発、データ分析と視覚化、機械学習とAI、およびパフォーマンスの最適化が含まれます。 1。DjangoandFlask Framework:Djangoは、複雑な用途の迅速な発展に適しており、Flaskは小規模または高度にカスタマイズされたプロジェクトに適しています。 2。API開発:フラスコまたはdjangorestFrameworkを使用して、Restfulapiを構築します。 3。データ分析と視覚化:Pythonを使用してデータを処理し、Webインターフェイスを介して表示します。 4。機械学習とAI:Pythonは、インテリジェントWebアプリケーションを構築するために使用されます。 5。パフォーマンスの最適化:非同期プログラミング、キャッシュ、コードを通じて最適化
