Python は、プログラミング言語人気指数 PYPL で何度も 1 位にランクされています。
コードが読みやすく、構文が単純であるため、これまでに作成された言語の中で最も単純であると考えられています。
NumPy、Pandas、TensorFlow などのさまざまな AI および機械学習ライブラリの豊富さは、Python の中核的な要件の 1 つです。
あなたがデータ サイエンティストまたは AI/機械学習の初心者の場合、Python はその旅を始めるのに最適な選択です。
今回は、Xiao F が、シンプルですが非常に役立つ Python プログラミングの基本知識を学習します。
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"]
>>> 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}
>>> # 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']}]
# 定义用户年龄 age = 27 dob = '16/12/1994' # 定义用户生日
""" Python小常识 This is a multi line comment """
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---World
>>> name = input("Enter your name: ") Enter your name: Codemaker >>> print("Hello", name) Hello Codemaker
>>> str1 = "Hello World" >>> print("The length of the stringis ", len(str1)) The length of the stringis 11
>>> str(123) 123 >>> str(3.14) 3.14
>>> int("123") 123 >>> int(3.14) 3
>>> num = 5 >>> if (num > 0): >>>print("Positive integer") >>> else: >>>print("Negative integer")
>>> 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 access
>>> # 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 S
>>> # 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
函数是用于执行任务的可重用代码块。在代码中实现模块化并使代码可重用,这是非常有用的。
>>> # This prints a passed string into this function >>> def display(str): >>>print(str) >>>return >>> display("Hello World") Hello World
即使语句在语法上是正确的,它也可能在执行时发生错误。这些类型的错误称为异常。我们可以使用异常处理机制来避免此类问题。
在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
字符串是用单引号或双引号(',")括起来的字符集合。
我们可以使用内置方法对字符串执行各种操作,如连接、切片、修剪、反转、大小写更改和格式化,如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
>>> 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 サイトの他の関連記事を参照してください。