Python は、プログラミング言語人気指数 PYPL で何度も 1 位にランクされています。
コードが読みやすく、構文が単純であるため、これまでに作成された言語の中で最も単純であると考えられています。
NumPy、Pandas、TensorFlow などのさまざまな AI および機械学習ライブラリの豊富さは、Python の中核的な要件の 1 つです。
あなたがデータ サイエンティストまたは AI/機械学習の初心者の場合、Python はその旅を始めるのに最適な選択です。
今回は、Xiao F が、シンプルですが非常に役立つ Python プログラミングの基本知識を学習します。
- #ディレクトリ
- データ型
- 変数
- リスト
- コレクション
- 辞書
- コメント
- 基本関数
- 条件文
- ループ文
- 関数
- 例外処理
- 文字列操作
- 正規表現
- 変数名は文字またはアンダースコア文字で始まる必要があります
- 変数名を数字で始めることはできません
- 変数名には英数字とアンダースコア (A ~ z、0 ~ 9、_) のみを含めることができます。
- 変数名は大文字と小文字が区別されます (age、Age、および AGE は 3 つの異なる変数です)
var1 = 'Hello World' var2 = 16 _unuseful = 'Single use variables'
>>> companies = ["apple","google","tcs","accenture"] >>> print(companies) ['apple', 'google', 'tcs', 'accenture'] >>> companies.append("infosys") >>> print(companies) ['apple', 'google', 'tcs', 'accenture', 'infosys'] >>> print(len(companies)) 5 >>> print(companies[2]) tcs >>> print(companies[-2]) accenture >>> print(companies[1:]) ['google', 'tcs', 'accenture', 'infosys'] >>> print(companies[:1]) ['apple'] >>> print(companies[1:3]) ['google', 'tcs'] >>> companies.remove("infosys") >>> print(companies) ["apple","google","tcs","accenture"] >>> companies.pop() >>> print(companies) ["apple","google","tcs"]4. SetSet は、重複するメンバーを持たない、順序付けされていないインデックスのないコレクションです。 重複したエントリをリストから削除する場合に便利です。また、和集合、積集合、差分などのさまざまな数学演算もサポートしています。
>>> set1 = {1,2,3,7,8,9,3,8,1} >>> print(set1) {1, 2, 3, 7, 8, 9} >>> set1.add(5) >>> set1.remove(9) >>> print(set1) {1, 2, 3, 5, 7, 8} >>> set2 = {1,2,6,4,2} >>> print(set2) {1, 2, 4, 6} >>> print(set1.union(set2))# set1 | set2 {1, 2, 3, 4, 5, 6, 7, 8} >>> print(set1.intersection(set2)) # set1 & set2 {1, 2} >>> print(set1.difference(set2)) # set1 - set2 {8, 3, 5, 7} >>> print(set2.difference(set1)) # set2 - set1 {4, 6}5. Dictionary辞書は、キーと値のペアとして順序付けされていない項目の変数コレクションです。 他のデータ型とは異なり、個別のデータを保存するのではなく、[キー:値] ペア形式でデータを保存します。この機能により、JSON 応答のマッピングに最適なデータ構造になります。
>>> # example 1 >>> user = { 'username': 'Fan', 'age': 20, 'mail_id': 'codemaker2022@qq.com', 'phone': '18650886088' } >>> print(user) {'mail_id': 'codemaker2022@qq.com', 'age': 20, 'username': 'Fan', 'phone': '18650886088'} >>> print(user['age']) 20 >>> for key in user.keys(): >>> print(key) mail_id age username phone >>> for value in user.values(): >>>print(value) codemaker2022@qq.com 20 Fan 18650886088 >>> for item in user.items(): >>>print(item) ('mail_id', 'codemaker2022@qq.com') ('age', 20) ('username', 'Fan') ('phone', '18650886088') >>> # example 2 >>> user = { >>> 'username': "Fan", >>> 'social_media': [ >>> { >>> 'name': "Linkedin", >>> 'url': "https://www.linkedin.com/in/codemaker2022" >>> }, >>> { >>> 'name': "Github", >>> 'url': "https://github.com/codemaker2022" >>> }, >>> { >>> 'name': "QQ", >>> 'url': "https://codemaker2022.qq.com" >>> } >>> ], >>> 'contact': [ >>> { >>> 'mail': [ >>> "mail.Fan@sina.com", >>> "codemaker2022@qq.com" >>> ], >>> 'phone': "18650886088" >>> } >>> ] >>> } >>> print(user) {'username': 'Fan', 'social_media': [{'url': 'https://www.linkedin.com/in/codemaker2022', 'name': 'Linkedin'}, {'url': 'https://github.com/codemaker2022', 'name': 'Github'}, {'url': 'https://codemaker2022.qq.com', 'name': 'QQ'}], 'contact': [{'phone': '18650886088', 'mail': ['mail.Fan@sina.com', 'codemaker2022@qq.com']}]} >>> print(user['social_media'][0]['url']) https://www.linkedin.com/in/codemaker2022 >>> print(user['contact']) [{'phone': '18650886088', 'mail': ['mail.Fan@sina.com', 'codemaker2022@qq.com']}]6. コメントポンド文字 (#) で始まり、メッセージが続き、行末で終わる 1 行のコメント。
# 定义用户年龄 age = 27 dob = '16/12/1994' # 定义用户生日複数行のコメントを特殊引用符 (""") で囲むと、メッセージを複数行に分割できます。
""" Python小常识 This is a multi line comment """7. 基本関数print () 関数は、指定されたメッセージをコンソールに出力します。さらに、画面に出力するためのパラメータとしてファイルまたはバッファ入力を指定することもできます。
print(object(s), sep=separator, end=end, file=file, flush=flush) print("Hello World") # prints Hello World print("Hello", "World")# prints Hello World? x = ("AA", "BB", "CC") print(x) # prints ('AA', 'BB', 'CC') print("Hello", "World", sep="---") # prints Hello---Worldinput() 関数は、ユーザー入力を収集するために使用されます。 ここで重要なのは、input() は入力したものをすべて文字列に変換するということです。したがって、年齢を整数値として指定すると、input() メソッドは文字列が返されるので手動で整数に変換する必要がある
>>> name = input("Enter your name: ") Enter your name: Codemaker >>> print("Hello", name) Hello Codemakerlen()でオブジェクトの長さを確認できる 文字列を入力すると文字数を取得できる
>>> str1 = "Hello World" >>> print("The length of the stringis ", len(str1)) The length of the stringis 11str() は、他のデータ型を文字列値に変換するために使用されます。
>>> str(123) 123 >>> str(3.14) 3.14int() は、文字列を整数に変換するために使用されます。 #8. 条件ステートメント条件ステートメントは、特定の条件に基づいてプログラムのフローを変更するために使用されるコードのブロックです。これらのステートメントは、特定の条件が満たされた場合にのみ実行されます。Python の場合では、if、if-else、ループ (for、while) を条件文として使用し、特定の条件に基づいてプログラムの流れを変更します。if-else 文。
>>> int("123") 123 >>> int(3.14) 3elif state.
>>> num = 5 >>> if (num > 0): >>>print("Positive integer") >>> else: >>>print("Negative integer")9 、ループ ステートメントループとは、特定の条件が満たされるまで特定のステートメント (本体内) を繰り返すために使用される条件ステートメントです。Python では通常、for ループと while ループを使用します。for ループ。
>>> name = 'admin' >>> if name == 'User1': >>> print('Only read access') >>> elif name == 'admin': >>> print('Having read and write access') >>> else: >>> print('Invalid user') Having read and write accessrange() 関数は、for ループ コントロールとして使用できる一連の数値を返します。基本的に 3 つのパラメータが必要ですが、2 番目と 3 番目はオプションです。パラメータは、開始値、停止値、ステップ番号です。ステップ番号は、反復ごとのループ変数の増分値です。
>>> # loop through a list >>> companies = ["apple", "google", "tcs"] >>> for x in companies: >>> print(x) apple google tcs >>> # loop through string >>> for x in "TCS": >>>print(x) T C Selse を使用することもできますこのキーワードは、ループの最後にいくつかのステートメントを実行します。 ループの最後に else ステートメントを指定し、ループの最後に実行する必要があるステートメントを指定します。 ##
>>> # loop with range() function >>> for x in range(5): >>>print(x) 0 1 2 3 4 >>> for x in range(2, 5): >>>print(x) 2 3 4 >>> for x in range(2, 10, 3): >>>print(x) 2 5 8
while ループ。
>>> for x in range(5): >>>print(x) >>> else: >>>print("finished") 0 1 2 3 4 finished
us for ループと同様に、while ループの最後に else を使用すると、条件が false のときにいくつかのステートメントを実行できます。
>>> count = 0 >>> while (count < 5): >>>print(count) >>>count = count + 1 >>> else: >>>print("Count is greater than 4") 0 1 2 3 4 Count is greater than 4
10、函数
函数是用于执行任务的可重用代码块。在代码中实现模块化并使代码可重用,这是非常有用的。
>>> # This prints a passed string into this function >>> def display(str): >>>print(str) >>>return >>> display("Hello World") Hello World
11、异常处理
即使语句在语法上是正确的,它也可能在执行时发生错误。这些类型的错误称为异常。我们可以使用异常处理机制来避免此类问题。
在Python中,我们使用try,except和finally关键字在代码中实现异常处理。
>>> def divider(num1, num2): >>> try: >>> return num1 / num2 >>> except ZeroDivisionError as e: >>> print('Error: Invalid argument: {}'.format(e)) >>> finally: >>> print("finished") >>> >>> print(divider(2,1)) >>> print(divider(2,0)) finished 2.0 Error: Invalid argument: division by zero finished None
12、字符串操作
字符串是用单引号或双引号(',")括起来的字符集合。
我们可以使用内置方法对字符串执行各种操作,如连接、切片、修剪、反转、大小写更改和格式化,如split()、lower()、upper()、endswith()、join()和ljust()、rjust()、format()。
>>> msg = 'Hello World' >>> print(msg) Hello World >>> print(msg[1]) e >>> print(msg[-1]) d >>> print(msg[:1]) H >>> print(msg[1:]) ello World >>> print(msg[:-1]) Hello Worl >>> print(msg[::-1]) dlroW olleH >>> print(msg[1:5]) ello >>> print(msg.upper()) HELLO WORLD >>> print(msg.lower()) hello world >>> print(msg.startswith('Hello')) True >>> print(msg.endswith('World')) True >>> print(', '.join(['Hello', 'World', '2022'])) Hello, World, 2022 >>> print(' '.join(['Hello', 'World', '2022'])) Hello World 2022 >>> print("Hello World 2022".split()) ['Hello', 'World', '2022'] >>> print("Hello World 2022".rjust(25, '-')) ---------Hello World 2022 >>> print("Hello World 2022".ljust(25, '*')) Hello World 2022********* >>> print("Hello World 2022".center(25, '#')) #####Hello World 2022#### >>> name = "Codemaker" >>> print("Hello %s" % name) Hello Codemaker >>> print("Hello {}".format(name)) Hello Codemaker >>> print("Hello {0}{1}".format(name, "2022")) Hello Codemaker2022
13、正则表达式
- 导入regex模块,import re。
- re.compile()使用该函数创建一个Regex对象。
- 将搜索字符串传递给search()方法。
- 调用group()方法返回匹配的文本。
>>> import re >>> phone_num_regex = re.compile(r'ddd-ddd-dddd') >>> mob = phone_num_regex.search('My number is 996-190-7453.') >>> print('Phone number found: {}'.format(mob.group())) Phone number found: 996-190-7453 >>> phone_num_regex = re.compile(r'^d+$') >>> is_valid = phone_num_regex.search('+919961907453.') is None >>> print(is_valid) True >>> at_regex = re.compile(r'.at') >>> strs = at_regex.findall('The cat in the hat sat on the mat.') >>> print(strs) ['cat', 'hat', 'sat', 'mat']
好了,本期的分享就到此结束了,有兴趣的小伙伴可以自行去实践学习。
以上が13 の重要な Python 知識の提案のコレクションの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

PythonArraysSupportVariousoperations:1)SlicingExtractsSubsets、2)Appending/ExtendingAdddesements、3)inSertingSelementSatspecificpositions、4)remvingingDeletesements、5)sorting/verversingsorder、and6)listenionsionsionsionsionscreatenewlistsebasedexistin

numpyarraysAressertialentionsionceivationsefirication-efficientnumericalcomputations andDatamanipulation.theyarecrucialindatascience、mashineelearning、物理学、エンジニアリング、および促進可能性への適用性、scaledatiencyを効率的に、forexample、infinancialanalyyy

UseanArray.ArrayOverAlistinPythonは、Performance-criticalCode.1)homogeneousdata:araysavememorywithpedelements.2)Performance-criticalcode:Araysofterbetterbetterfornumerumerumericaleperations.3)interf

いいえ、notallistoperationSaresuptedbyarrays、andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorintorintorinsertizizing、whosimpactsporformance.2)リスト

toaccesselementsinapythonlist、useindexing、negativeindexing、slicing、oriteration.1)indexingstartsat0.2)negativeindexingAcsesess.3)slicingextractStions.4)reterationSuseSuseSuseSuseSeSeS forLoopseCheckLentlentlentlentlentlentlenttodExeror。

Arraysinpython、特にvianumpy、arecrucialinscientificComputing fortheirefficienty andversitility.1)彼らは、fornumericaloperations、data analysis、andmachinelearning.2)numpy'simplementation incensuresfasteroperationsthanpasteroperations.3)arayableminablecickick

Pyenv、Venv、およびAnacondaを使用して、さまざまなPythonバージョンを管理できます。 1)Pyenvを使用して、複数のPythonバージョンを管理します。Pyenvをインストールし、グローバルバージョンとローカルバージョンを設定します。 2)VENVを使用して仮想環境を作成して、プロジェクトの依存関係を分離します。 3)Anacondaを使用して、データサイエンスプロジェクトでPythonバージョンを管理します。 4)システムレベルのタスク用にシステムPythonを保持します。これらのツールと戦略を通じて、Pythonのさまざまなバージョンを効果的に管理して、プロジェクトのスムーズな実行を確保できます。

numpyarrayshaveveraladvantages-averstandardpythonarrays:1)thealmuchfasterduetocベースのインプレンテーション、2)アレモレメモリ効率、特にlargedatasets、および3)それらは、拡散化された、構造化された形成術科療法、


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

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

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

ホットトピック









