Python コースのコード例
これは、Python の学習のために私が使用および作成した Python コードのドキュメントです。
わかりやすくてわかりやすいので、ぜひここから学んでみてください。
近いうちに、より高度なトピックについてブログを更新します。
目次
- 最初のプログラム
- 変数とデータ型
- 文字列
- 数字
- ユーザーからの意見を得る
- 基本的な計算機の構築
- 初めての Madlibs
- リスト
- リスト関数
- タプル
- 機能
- リターンステートメント
- If ステートメント
- 比較の場合
- 推測ゲーム 2
- For ループ
- 指数関数
- 2D リストと For ループ
最初のプログラム
このプログラムは、print() コマンドがどのように機能するかを示すために使用されます。
# This is a simple "Hello World" program that demonstrates basic print statements # Print the string "Hello world" to the console print("Hello world") # Print the integer 1 to the console print(1) # Print the integer 20 to the console print(20)
変数とデータ型
Python の変数は、値を保存するために予約されたメモリの場所です。
データ型は、変数が保持できるデータのタイプ (整数、浮動小数点、文字列など) を定義します。
# This program demonstrates the use of variables and string concatenation # Assign the string "Dipsan" to the variable _name _name = "Dipsan" # Assign the integer 20 to the variable _age _age = 20 # Assign the string "piano" to the variable _instrument _instrument = "piano" # Print a sentence using string concatenation with the _name variable print("my name is" + _name + ".") # Print a sentence using string concatenation, converting _age to a string print("I'm" + str(_age) + "years old") # Converting int to string for concatenation # Print a simple string print("i dont like hanging out") # Print a sentence using string concatenation with the _instrument variable print("i love " + _instrument + ".")
文字列
テキストの保存と操作に使用される文字のシーケンス。これらは、テキストを一重引用符 ('Hello')、二重引用符 ("Hello")、または複数行文字列の場合は三重引用符 ('''Hello''') で囲むことによって作成されます。例: 「Hello, World!」。
# This script demonstrates various string operations # Assign a string to the variable 'phrase' phrase = "DipsansAcademy" # Print a simple string print("This is a string") # Concatenate strings and print the result print('This' + phrase + "") # Convert the phrase to uppercase and print print(phrase.upper()) # Convert the phrase to lowercase and print print(phrase.lower()) # Check if the uppercase version of phrase is all uppercase and print the result print(phrase.upper().isupper()) # Print the length of the phrase print(len(phrase)) # Print the first character of the phrase (index 0) print(phrase[0]) # Print the second character of the phrase (index 1) print(phrase[1]) # Print the fifth character of the phrase (index 4) print(phrase[4]) # Find and print the index of 'A' in the phrase print(phrase.index("A")) # Replace "Dipsans" with "kadariya" in the phrase and print the result print(phrase.replace("Dipsans", "kadariya"))
数字
数値はさまざまな数値演算や数学関数に使用されます。
# Import all functions from the math module from math import * # Importing math module for additional math functions # This script demonstrates various numeric operations and math functions # Print the integer 20 print(20) # Multiply 20 by 4 and print the result print(20 * 4) # Add 20 and 4 and print the result print(20 + 4) # Subtract 4 from 20 and print the result print(20 - 4) # Perform a more complex calculation and print the result print(3 + (4 - 5)) # Calculate the remainder of 10 divided by 3 and print the result print(10 % 3) # Assign the value 100 to the variable _num _num = 100 # Print the value of _num print(_num) # Convert _num to a string, concatenate with other strings, and print print(str(_num) + " is my fav number") # Converting int to string for concatenation # Assign -10 to the variable new_num new_num = -10 # Print the absolute value of new_num print(abs(new_num)) # Absolute value # Calculate 3 to the power of 2 and print the result print(pow(3, 2)) # Power function # Find the maximum of 2 and 3 and print the result print(max(2, 3)) # Maximum # Find the minimum of 2 and 3 and print the result print(min(2, 3)) # Minimum # Round 3.2 to the nearest integer and print the result print(round(3.2)) # Rounding # Round 3.7 to the nearest integer and print the result print(round(3.7)) # Calculate the floor of 3.7 and print the result print(floor(3.7)) # Floor function # Calculate the ceiling of 3.7 and print the result print(ceil(3.7)) # Ceiling function # Calculate the square root of 36 and print the result print(sqrt(36)) # Square root
ユーザーからの意見を得る
このプログラムは、input() 関数を使用してユーザー入力を取得する方法を示すために使用されます。
# This script demonstrates how to get user input and use it in string concatenation # Prompt the user to enter their name and store it in the 'name' variable name = input("Enter your name : ") # Prompt the user to enter their age and store it in the 'age' variable age = input("Enter your age. : ") # Print a greeting using the user's input, concatenating strings print("hello " + name + " Youre age is " + age + " .")
基本的な計算機の構築
このプログラムは、2 つの数値を加算する単純な計算機を作成します。
# This script creates a basic calculator that adds two numbers # Prompt the user to enter the first number and store it in 'num1' num1 = input("Enter first number : ") # Prompt the user to enter the second number and store it in 'num2' num2 = input("Enter second number: ") # Convert the input strings to integers and add them, storing the result result = int(num1) + int(num2) # Print the result of the addition print(result)
最初の Madlibs
このプログラムは、単純な Mad Libs ゲームを作成します:
# This program is used to create a simple Mad Libs game. # Prompt the user to enter an adjective and store it in 'adjective1' adjective1 = input("Enter an adjective: ") # Prompt the user to enter an animal and store it in 'animal' animal = input("Enter an animal: ") # Prompt the user to enter a verb and store it in 'verb' verb = input("Enter a verb: ") # Prompt the user to enter another adjective and store it in 'adjective2' adjective2 = input("Enter another adjective: ") # Print the first sentence of the Mad Libs story using string concatenation print("I have a " + adjective1 + " " + animal + ".") # Print the second sentence of the Mad Libs story print("It likes to " + verb + " all day.") # Print the third sentence of the Mad Libs story print("My " + animal + " is so " + adjective2 + ".")
リスト
リストは、順序付けされ、変更可能な Python の項目のコレクションです。リスト内の各項目 (または要素) には、0 から始まるインデックスがあります。リストには、さまざまなデータ型の項目 (整数、文字列、または他のリストなど) を含めることができます。
リストは角括弧 [] を使用して定義され、各項目はカンマで区切られます。
# This script demonstrates basic list operations # Create a list of friends' names friends = ["Roi", "alex", "jimmy", "joseph"] # Print the entire list print(friends) # Print the first element of the list (index 0) print(friends[0]) # Print the second element of the list (index 1) print(friends[1]) # Print the third element of the list (index 2) print(friends[2]) # Print the fourth element of the list (index 3) print(friends[3]) # Print the last element of the list using negative indexing print(friends[-1]) # Print a slice of the list from the second element to the end print(friends[1:]) # Print a slice of the list from the second element to the third (exclusive) print(friends[1:3]) # Change the second element of the list to "kim" friends[1] = "kim" # Print the modified list print(friends)
リスト関数
このスクリプトは、さまざまなリスト メソッドを紹介します:
# This script demonstrates various list functions and methods # Create a list of numbers numbers = [4, 6, 88, 3, 0, 34] # Create a list of friends' names friends = ["Roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"] # Print both lists print(numbers) print(friends) # Add all elements from 'numbers' to the end of 'friends' friends.extend(numbers) # Add "hulk" to the end of the 'friends' list friends.append("hulk") # Insert "mikey" at index 1 in the 'friends' list friends.insert(1, "mikey") # Remove the first occurrence of "Roi" from the 'friends' list friends.remove("Roi") # Print the index of "mikey" in the 'friends' list print(friends.index("mikey")) # Remove and print the last item in the 'friends' list print(friends.pop()) # Print the current state of the 'friends' list print(friends) # Remove all elements from the 'friends' list friends.clear() # Print the empty 'friends' list print(friends) # Sort the 'numbers' list in ascending order numbers.sort() # Print the sorted 'numbers' list print(numbers)
タプル
タプルは、順序付けされているが変更できない (不変の) Python の項目のコレクションです。タプルを作成した後は、その要素を追加、削除、または変更することはできません。リストと同様に、タプルにはさまざまなデータ型の項目を含めることができます。
タプルは括弧 () を使用して定義され、各項目はカンマで区切られます。
# This script introduces tuples and their immutability # Create a tuple with two elements values = (3, 4) # Print the entire tuple print(values) # Print the second element of the tuple (index 1) print(values[1]) # The following line would cause an IndexError if uncommented: # print(values[2]) # This would cause an IndexError # The following line would cause a TypeError if uncommented: # values[1] = 30 # This would cause a TypeError as tuples are immutable # The following line would print the modified tuple if the previous line worked: # print(values)
機能
関数は、特定のタスクを実行する再利用可能なコードのブロックです。関数は入力 (引数と呼ばれます) を受け取り、それを処理して出力を返すことができます。関数は、コードを整理し、よりモジュール化し、繰り返しを避けるのに役立ちます。
n Python では、関数は def キーワード、その後に関数名、括弧 ()、コロン : を続けて使用して定義されます。関数内のコードはインデントされています。
このコードは、関数を定義して呼び出す方法を示しています:
# This script demonstrates how to define and call functions # Define a function called 'greetings' that prints two lines def greetings(): print("HI, Welcome to programming world of python") print("keep learning") # Print a statement before calling the function print("this is first statement") # Call the 'greetings' function greetings() # Print a statement after calling the function print("this is last statement") # Define a function 'add' that takes two parameters and prints their sum def add(num1, num2): print(int(num1) + int(num2)) # Call the 'add' function with arguments 3 and 4 add(3, 4)
リターンステートメント
この return ステートメントは、呼び出し元に値を送り返す (または「返す」) ために関数内で使用されます。 return を実行すると関数は終了し、return 後に指定した値が関数呼び出し元に返されます。
このプログラムは、関数で return ステートメントを使用する方法を示します。
# This script demonstrates the use of return statements in functions # Define a function 'square' that returns the square of a number def square(num): return num * num # Any code after the return statement won't execute # Call the 'square' function with argument 2 and print the result print(square(2)) # Call the 'square' function with argument 4 and print the result print(square(4)) # Call the 'square' function with argument 3, store the result, then print it result = square(3) print(result)
If ステートメント
if ステートメントは条件 (True または False を返す式) を評価します。
条件が True の場合、if ステートメントの下のコード ブロックが実行されます。
elif : 「else if」の略で、複数の条件をチェックできます。
これは、評価する条件が複数あり、最初の True 条件に対してコード ブロックを実行する場合に使用されます。
else:else ステートメントは、前述の if 条件または elif 条件がいずれも True でない場合にコード ブロックを実行します。
# This script demonstrates the use of if-elif-else statements # Set boolean variables for conditions is_boy = True is_handsome = False # Check conditions using if-elif-else statements if is_boy and is_handsome: print("you are a boy & youre handsome") print("hehe") elif is_boy and not (is_handsome): print("Youre a boy but sorry not handsome") else: print("youre not a boy")
比較する場合
このコードは、if ステートメントでの比較演算を示しています。
# This script demonstrates comparison operations in if statements # Define a function to find the maximum of three numbers def max_numbers(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 # Test the max_numbers function with different inputs print(max_numbers(20, 40, 60)) print(max_numbers(30, 14, 20)) print(max_numbers(3, 90, 10)) print("For min_number") # Define a function to find the minimum of three numbers def min_numbers(num1, num2, num3): if num1 <h2> 推理ゲーム 2 </h2> <p>このスクリプトは、より多くの機能を備えた推測ゲームを改善します:<br> </p> <pre class="brush:php;toolbar:false"># This script improves the guessing game with more features import random # Generate a random number between 1 and 20 secret_number = random.randint(1, 20) # Initialize the number of attempts and set a limit attempts = 0 attempt_limit = 5 # Loop to allow the user to guess the number while attempts <h2> For ループ </h2> <p>for ループは、リスト、タプル、文字列、範囲などの一連の要素を反復処理するために使用されます。 <br> このコードでは for ループが導入されています:<br> </p> <pre class="brush:php;toolbar:false"># List of numbers numbers = [1, 2, 3, 4, 5] # Iterate over each number in the list for number in numbers: # Print the current number print(number) # Output: # 1 # 2 # 3 # 4 # 5 # List of friends friends = ["Roi", "alex", "jimmy", "joseph", "kevin", "tony", "jimmy"] # Iterate over each friend in the list for friend in friends: # Print the name of the current friend print(friend) # Output: # Roi # alex # jimmy # joseph # kevin # tony # jimmy # Use range to generate numbers from 0 to 4 for num in range(5): print(num) # Output: # 0 # 1 # 2 # 3 # 4
指数関数
指数関数は、定数の底を変数の指数に累乗する数学関数です。
このスクリプトは math.pow 関数の使用方法を示しています:
# This script demonstrates the use of the exponential function def exponentialFunction(base,power): result = 1 for index in range(power): result = result * base return result print(exponentialFunction(3,2)) print(exponentialFunction(4,2)) print(exponentialFunction(5,2)) #or you can power just by print(2**3) #number *** power
2D List and For Loops
A 2D list (or 2D array) in Python is essentially a list of lists, where each sublist represents a row of the matrix. You can use nested for loops to iterate over elements in a 2D list. Here’s how you can work with 2D lists and for loops:
# This script demonstrates the use of 2D List and For Loops # Define a 2D list (list of lists) num_grid = [ [1, 2, 3], # Row 0: contains 1, 2, 3 [4, 5, 6], # Row 1: contains 4, 5, 6 [7, 8, 9], # Row 2: contains 7, 8, 9 [0] # Row 3: contains a single value 0 ] # Print specific elements in num_grid print(num_grid[0][0]) # Print value in the zeroth row, zeroth column (value: 1) print(num_grid[1][0]) # Print value in the first row, zeroth column (value: 4) print(num_grid[2][2]) # Print value in the second row, second column (value: 9) print("using nested for loops") for row in num_grid : for col in row: print(col)
This is how we can use 2D List and For Loops.
以上がPython をシンプルに: 初心者から上級者まで |ブログの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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

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

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

Pythonの実際のアプリケーションには、データ分析、Web開発、人工知能、自動化が含まれます。 1)データ分析では、PythonはPandasとMatplotlibを使用してデータを処理および視覚化します。 2)Web開発では、DjangoおよびFlask FrameworksがWebアプリケーションの作成を簡素化します。 3)人工知能の分野では、TensorflowとPytorchがモデルの構築と訓練に使用されます。 4)自動化に関しては、ファイルのコピーなどのタスクにPythonスクリプトを使用できます。

Pythonは、データサイエンス、Web開発、自動化スクリプトフィールドで広く使用されています。 1)データサイエンスでは、PythonはNumpyやPandasなどのライブラリを介してデータ処理と分析を簡素化します。 2)Web開発では、DjangoおよびFlask Frameworksにより、開発者はアプリケーションを迅速に構築できます。 3)自動化されたスクリプトでは、Pythonのシンプルさと標準ライブラリが理想的になります。

Pythonの柔軟性は、マルチパラダイムサポートと動的タイプシステムに反映されていますが、使いやすさはシンプルな構文とリッチ標準ライブラリに由来しています。 1。柔軟性:オブジェクト指向、機能的および手続き的プログラミングをサポートし、動的タイプシステムは開発効率を向上させます。 2。使いやすさ:文法は自然言語に近く、標準的なライブラリは幅広い機能をカバーし、開発プロセスを簡素化します。

Pythonは、初心者から上級開発者までのすべてのニーズに適した、そのシンプルさとパワーに非常に好まれています。その汎用性は、次のことに反映されています。1)学習と使用が簡単、シンプルな構文。 2)Numpy、Pandasなどの豊富なライブラリとフレームワーク。 3)さまざまなオペレーティングシステムで実行できるクロスプラットフォームサポート。 4)作業効率を向上させるためのスクリプトおよび自動化タスクに適しています。

はい、1日2時間でPythonを学びます。 1.合理的な学習計画を作成します。2。適切な学習リソースを選択します。3。実践を通じて学んだ知識を統合します。これらの手順は、短時間でPythonをマスターするのに役立ちます。


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

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

WebStorm Mac版
便利なJavaScript開発ツール

Dreamweaver Mac版
ビジュアル Web 開発ツール

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