程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

13 necessary Python knowledge, recommended collection!

編輯:Python

Hello everyone , I'm little F.

Python In the programming language popularity index PYPL Has ranked first for many times .

Because of its code readability and Simpler Syntax , It is considered the simplest language ever .

NumPy、Pandas、TensorFlow And so on AI And the richness of the machine learning library , yes Python One of the core requirements .

If you are a data scientist or AI/ Beginners of machine learning , that Python Is the right choice to start your journey .

This time , Small F Will take you to explore some Python Basic knowledge of programming , Simple but useful .

  • Catalog

    • data type

    • Variable

    • list

    • aggregate

    • Dictionaries

    • notes

    • Basic function

    • Conditional statements

    • Loop statement

    • function

    • exception handling

    • String manipulation

    • Regular expressions

▍1、 data type

Data types are data specifications that can be stored in variables . The interpreter allocates memory for variables according to their type .

Here is Python Various data types in .

▍2、 Variable

Variables are containers for storing data values .

Variables can have short names ( Such as x and y) Or a more descriptive name (age、carname、total_volume). 

Python Variable naming rule :

  • Variable names must start with a letter or an underline character

  • Variable names cannot begin with numbers

  • Variable names can only contain alphanumeric characters and underscores (A-z、0-9 and _)

  • Variable names are case sensitive (age、Age and AGE There are three different variables )

var1 = 'Hello World'
var2 = 16
_unuseful = 'Single use variables'

The output is as follows .

▍3、 list

list (List) Is an ordered and changeable collection , Allow duplicate members .

It may not be homogeneous , We can create one that contains different data types ( Such as integers 、 Strings and objects ) A list of .‍

>>> 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、 aggregate

aggregate (Set) Is an unordered and indexed collection , There are no duplicate members .

Useful for removing duplicate entries from a list . It also supports various mathematical operations , For example, Union 、 Intersection and difference .

>>> 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、 Dictionaries

A dictionary is a collection of variable unordered items as key value pairs .

Unlike other data types , It uses 【 key : value 】 Save data for format , Instead of storing a single piece of data . This feature makes it a mapping JSON The best data structure for response .

>>> # example 1
>>> user = { 'username': 'Fan', 'age': 20, 'mail_id': '[email protected]', 'phone': '18650886088' }
>>> print(user)
{'mail_id': '[email protected]', '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)
[email protected]
20
Fan
18650886088
>>> for item in user.items():
>>>  print(item)
('mail_id', '[email protected]')
('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': [
>>>                     "[email protected]",
>>>                     "[email protected]"
>>>                 ],
>>>             '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': ['[email protected]', '[email protected]']}]}
>>> print(user['social_media'][0]['url'])
https://www.linkedin.com/in/codemaker2022
>>> print(user['contact']) 
[{'phone': '18650886088', 'mail': ['[email protected]', '[email protected]']}]

▍6、 notes

Single-line comments , In pound characters (#) start , It is followed by a message and ends at the end of the line .

#  Define user age
age = 27
dob = '16/12/1994' #  Define the user's birthday 

Multiline comment , Use special quotation marks (""") Cover up , You can put messages on multiple lines .

"""
Python Common sense
This is a multi line comment
"""

▍7、 Basic function

print() Function to print the provided message in the console . In addition, you can provide file or buffer input as parameters for printing on the screen .

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

input() The function is used to collect user input from the console .

Here we need to pay attention to ,input() Will convert anything you enter into a string .

therefore , If you provide age as an integer value , but input() Method returns it as a string , At this point, you need to manually convert it to an integer .

>>> name = input("Enter your name: ")
Enter your name: Codemaker
>>> print("Hello", name)
Hello Codemaker

len() You can view the length of the object . If you enter a string , You can get the number of characters in the specified string .

>>> str1 = "Hello World"
>>> print("The length of the string  is ", len(str1))
The length of the string  is 11

str() Used to convert other data types to string values .

>>> str(123)
123
>>> str(3.14)
3.14

int() Used to convert a string to an integer .

>>> int("123")
123
>>> int(3.14)
3

▍8、 Conditional statements

Conditional statements are blocks of code that are used to change the flow of a program based on specific conditions . These statements are executed only if certain conditions are met .

stay Python in , We use if,if-else, loop (for,while) As a conditional statement, change the flow of a program according to certain conditions .

if-else sentence .

>>> num = 5
>>> if (num > 0):
>>>    print("Positive integer")
>>> else:
>>>    print("Negative integer")

elif sentence .

>>> 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

▍9、 Loop statement

A loop is a conditional statement , Used to repeat certain statements ( In its body ), Until a condition is met .

stay Python in , We usually use for and while loop .

for loop .

>>> # 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

range() Function returns a sequence of numbers , It can be used as for Cycle control .

It basically requires three parameters , The second and third are optional . The parameter is the starting value 、 Stop value and number of steps . The number of steps is the increment value of the loop variable for each iteration .

>>> # 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

We can also use else Keyword executes some statements at the end of the loop .

Provide... At the end of the loop else Statement and the statement to be executed at the end of the loop .

>>> for x in range(5):
>>>  print(x)
>>> else:
>>>  print("finished")
0
1
2
3
4
finished

while loop .

>>> count = 0
>>> while (count < 5):
>>>  print(count)
>>>  count = count + 1
0
1
2
3
4

We can do it in while The end of the loop uses else, Be similar to for loop , Execute some statements when the condition is 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、 function

Functions are reusable blocks of code for performing tasks . Implement modularity in code and make code reusable , This is very useful .

>>> # This prints a passed string into this function
>>> def display(str):
>>>  print(str)
>>>  return
>>> display("Hello World")
Hello World

▍11、 exception handling

Even if the statement is grammatically correct , It may also have errors during execution . These types of errors are called exceptions . We can use exception handling mechanisms to avoid such problems . 

stay Python in , We use try,except and finally Keyword to implement exception handling in code .

>>> 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、 String manipulation

Strings are in single or double quotation marks (',") Enclosed character set .

We can use built-in methods to perform various operations on strings , If connected 、 section 、 trim 、 reverse 、 Case change and formatting , Such as split()、lower()、upper()、endswith()、join() and 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、 Regular expressions

  • Import regex modular ,import re. 

  • re.compile() Use this function to create a Regex object . 

  • Pass the search string to search() Method . 

  • call group() Method returns the matching text .

>>> import re
>>> phone_num_regex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
>>> 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']

Okay , This is the end of this issue , If you are interested, you can learn by yourself .

All rivers and mountains are always in love , Order one    OK? .

Recommended reading

···  END  ···


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved