This is the 18th day of my participation in Gwen Challenge

Getting started with Python, start fighting ๐Ÿ˜† from Teacher Liao Xuefeng’s Python tutorial

Introduction to the

Developed by Guido van Rossum date: Christmas 1989 Features: “Elegant”, “clear”, “Simple” Language type: Explanation (advanced) Benefits:

  1. Python provides a very good base of code covering networks, files, GUIs, databases, text, and much more, aptly called “batteries included.”
  2. The same task requires 1000 lines of code in C, 100 lines in Java, and maybe 20 lines in Python.

Disadvantages:

  1. The first disadvantage is that it is very slow to run, very slow compared to C programs. After all, it is an interpreted language, which has to be translated line by line into machine code that the CPU can understand, whereas C compiled programs are compiled directly into machine code that the CPU can execute before running, so they are very fast.
  2. Code cannot be encrypted.

Use scenario: Python is suitable for developing web applications, including websites, backend services, etc. Web crawler Web application development system Network operation and maintenance science and digital computing GRAPHICAL interface development network programming natural language processing (NLP) artificial intelligence blockchain is followed by many daily needs of small tools, including system administrators need scripting tasks and so on; The other is to repackage the programs developed in other languages for easy use.

The installation

Download Python 3.8.3 from the official website

The steps are as follows:

Click Install and wait. Finally, click remove window maximum path length limit

Open the command window and enter Python. If an interactive interface is displayed, the installation is successful. To exit the interface, press CTRL +D on Linux. On Windows, enter Exit () or close the command line window

The interpreter

Python is an interpreted language and naturally requires the CPython interpreter to execute. Py files. Other interpreters:

  1. IPython: IPython only enhances the interaction. CPython uses >>> as the prompt, while IPython uses In [serial number]: as the prompt.
  2. PyPy: The goal is speed of execution. PyPy uses JIT technology to compile Python code on the fly (note that it is not interpreted), so it can significantly improve the speed of Python code execution. Differences between PyPy and CPython
  3. Jython: Running on the Java platform, Python code can be compiled directly into Java bytecode for execution.
  4. IronPython: Runs on Microsoft. Net platform Python interpreter, can directly compile Python code into. Net bytecode.

Summary:

There are many Python interpreters, but CPython is the most widely used. If you want to communicate with Java or. The best way to interact with the Net platform is not through Jython or IronPython, but through network calls that ensure independence between programs.

basis

  1. Write in indent format
  2. Case sensitivity
  3. Start of comment #

When a statement ends with a colon:, the indented statement is considered a code block. If (){} the code inside the braces should be indented as follows:

# print absolute value of an integer:
a = 100
if a >= 0:
    print(a)
else:
    print(-a)
Copy the code

Data types and variables

  • The integer
  • Floating point (1.23×109 is 1.23e9)
  • string
  • Boolean values (and, OR, and not operations)
  • Null value (represented by None)
  • The list and a tuple

tip:

  1. The variable name must be a combination of uppercase and lowercase letters, numbers, and underscores, and cannot start with a number
  2. In Python, constants are usually represented by all-caps variable names
  3. Languages in which the variable itself is not of fixed type are called dynamic languages, as opposed to static languages. Static languages must specify the type of a variable when defining it, and an error will be reported if the assignment does not match the type. Java is static (int a = 123)
  4. The/division evaluates to a floating-point number, even if two integers are exactly divisible:9/3 3.0
  5. There is also a division called //, called floor division, where the division of two integers is still an integer:10 / / 3 3

string

escape

Escape characters use \, r “to indicate” inside the string is not escaped by default, the “” content” “format represents multiple lines of content

A character encoding

Python3 defaults to UTF-8 and retrieves the integer representation of the character through the ord() function, which converts the encoding to the corresponding character ORD (‘A’) 65 CHR (65) A

Bytes

A string consists of characters. A character consists of several bytes.

Python represents bytes with single or double quotation marks prefixed with b: x = b’ABC’.

Bytes are read if a byte stream is read from the network or disk. To change bytes to STR, use the decode() method:

A 'hello world' print(b) b'hello world' print(CHR (b[0])Copy the code
formatting

The format used is consistent with the C language, with %

>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
Copy the code
len()

Gets the length of the string, the length of bytes

A = 'hello world 'b=a.encode() print(len(a)) # 13 print(len(b)) # 17Copy the code

The list and a tuple

list
   classmates = ['Michael', 'Bob', 'Tracy']
Copy the code

We can use the final element with the final word of the classmates[-1] and the final word of the classmates[-2]

  • Add dataclassmates.append('Adam') [‘Michael’, ‘Bob’, ‘Tracy’, ‘Adam’]
  • Insert dataclassmates.insert(1, 'Jack') [‘Michael’, ‘Jack’, ‘Bob’, ‘Tracy’, ‘Adam’]
  • Delete end dataclassmates.pop() [‘Michael’, ‘Jack’, ‘Bob’, ‘Tracy’]
  • Delete the element at the specified position using pop(I)classmates.pop(1) [‘Michael’, ‘Bob’, ‘Tracy’]
  • To replace an element with another, assign the value directly to the corresponding index position:classmates[1] = 'Sarah' [‘Michael’, ‘Sarah’, ‘Tracy’]
  • The data types of the elements in the list can also be different, for example L = ['Apple', 123, True, ['asp', 'php']]
tuple

A tuple, once initialized, cannot be modified. However, if a tuple contains a list, it is possible to change the value of the list. There is a value in the word ‘Michael’, ‘Bob’, ‘Tracy’.

Note:

An empty tuple can be written as (), such as t=().

A tuple with only 1 element must be defined with a comma to disambiguate it

a=(1)
print(a[-1])  # TypeError: 'int' object is not subscriptable
t=(1,)
print(t[-1])
Copy the code

conditional

Elif: < execute 1> elif: < execute 2> elif: < execute 3> else: < execute 4> # if, as long as x is a non-zero value, non-empty string, non-empty list, etc., it is True, otherwise False. If x: print('True')Copy the code

cycle

for… In circulation

names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)

Copy the code

The range() function produces a sequence of integers starting at 0 and less than 5: list(range(5)) outputs [0, 1, 2, 3, 4]

The while loop

Calculate the sum of all odd numbers up to 100

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)
Copy the code

dict

Python has built-in support for dictionaries: dict, which stands for dictionary and is also called map in other languages. It uses key-value storage for extremely fast lookups

D = {' Michael ': 95, "Bob", 75, "Tracy" : 85} d output [' Michael'] # 95Copy the code

check

  1. There are two ways to avoid the error that the key does not exist. One is to check whether the key exists by using in'Thomas' in dOutput is False
  2. Get () is a get() method provided by dict, which returns None if the key does not exist, or a self-specified value:
D.set ('Thomas') # None d.set ('Thomas', -1) # value: -1Copy the code

delete

To delete a key, use the pop(key) method, and the corresponding value is also removed from the dict:

>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85}
Copy the code

increase

>>> d['Adam'] = 67
>>> d['Adam']
67  
Copy the code

change

d={'aa':1,'bb':2}
d['Adam'] = 67
print(d)
d['Adam'] = 99
print(d)  
Copy the code

Note:

Compared to lists, dict has the following characteristics: extremely fast lookups and inserts that don’t slow down as keys are added; Need to take up a lot of memory, memory waste.

Lists, on the other hand, take longer to find and insert as more elements are added; Occupies small space, wastes little memory. So dict is a way to trade space for time.

Dict keys must be immutable objects. Such as strings, integers, etc., and list is mutable, can not be used as a key

Algorithms that compute positions using keys are called hashes.

set

A set, like a dict, is a set of keys, but does not store values. Because key cannot be repeated

These data structures (arrays, collections, key-value pairs, etc.) are unordered and unique in both ES6 and Java.

Example: To create a set, supply a list as the input set:

S = set([1, 1, 2, 2, 3, 3])Copy the code

A set can be regarded as a set of disordered and non-repeating elements in the mathematical sense. Therefore, two sets can perform mathematical operations such as intersection and union:

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}
Copy the code

The only difference between a set and a dict is that it does not store the corresponding value. However, the principle of a set is the same as that of a dict. Therefore, mutable objects cannot be placed in a set, because it is impossible to determine whether two mutable objects are equal or not.

S = set ([1, 2, [1, 2, 3]]) print (s) # unhashable type: 'list'Copy the code

The last

There are python notes ~ ๐Ÿ˜„

If you think this article is good, please give it a thumbs-up ๐Ÿ˜

Let’s start this unexpected meeting! ~

Welcome to leave a message! Thanks for your support! ใƒพ(โ‰งโ–ฝโ‰ฆ*)o go!!

I’m 4ye and I’ll see you soon next time!!