This article is participating in Python Theme Month. See the link to the event for more details

Introduction to basic Python concepts

Python is an interpreted language. Python uses indentation alignment to organize code execution, so any code that is not indented is automatically executed at load time

One, data type

Python supports three different numeric types:

type The keyword Value range
plastic int infinite
floating-point float The decimal
The plural complex It’s made up of real and imaginary numbers

There are six standard data types in Python:

  1. Number (Number)
  2. String(String)
  3. The List (List)
  4. The Tuple (a Tuple)
  5. Sets (set)
  6. Dictionart (dictionary)

Where cannot become data:

  • Number (Number)
  • String(String)
  • The Tuple (a Tuple)
  • Sets (set)

Variable:

  • The List (List)
  • Dictionart (dictionary)

We can use type or isinstance to determine the type

class A:
	pass

class B:
	pass

print(isinstance(A(), A));
print(type(A()) == A);

print(isinstance(B(), A));
print(type(B()) == A);
Copy the code

The output is True True False False

Type () does not consider a subclass to be a supertype. Isinstance () will consider a subclass to be a superclass type


Second, the variable

To define a variable in Python, you do not need to write the variable type, but you must initialize it.

Python automatically matches variable naming rules based on the type of data we are writing: it consists of letters, numbers, and underscores. The first letter must be either a letter or an underscore, and it is case-sensitive, not a keyword

When we need to input Chinese, we need to include the header # — coding: UTF-8 — or #coding= UTF-8

  • Enter a = input(” Please enter…”) ) returns a value of type STR
  • The output print (” hello world “)

Three, string

Now that we’ve solved the headaches of character encoding, let’s look at Strings in Python.

In the latest Python 3 release, strings are encoded in Unicode, that is, Python’s strings support multiple languages. For single-character encodings, Python provides the ord() function to get the integer representation of the character, and the CHR () function to convert the encoding to the corresponding character:


Four, operators

Python operator error:

  • Arithmetic operators: *,, /, //, +, (: means power, //: means divisible)
  • Logical operators: and,or,not and,or,not
  • The assignment operator: =, and the combination of the above arithmetic operator and =, such as +=, -=
  • Identity operator: is is not


List five,

Lists are the most basic data structure in Python. Each value in the list has a corresponding positional value, called an index, where the first index is 0, the second index is 1, and so on.

Defining a list

list1 = [1.2.3]
list2 = [1.2.'3']
Copy the code

Access list


Six, yuan group

Python tuples are similar to lists, except that the elements of a tuple cannot be modified. Tuples use curly brackets (), lists use square brackets [].

Tuple creation is as simple as adding elements in parentheses separated by commas.

tup1 = () # empty tuple
tup2 = (1.2.'3') 

tup3 = tup1 + tup2 # Tuple sum

del tup1 Delete tuple
Copy the code

Seven, the dictionary

Dictionaries are another variable container model that can store objects of any type. The key must be unique

Each key=>value pair of the dictionary is separated by a colon:, each pair is separated by a comma (,), and the entire dictionary is enclosed in curly braces {}. The format is as follows:

dic = {key1 : value1, key2 : value2}
Copy the code

Define and describe a dictionary

dict = {'Name': 'python'}
print ("dict['Name']: ".dict['Name'])

Dict ['Name']: python
Copy the code

Eight,

A set is an unordered sequence of elements that do not repeat.

You can use braces {} or set() to create a set. Note: to create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.

Create syntax:

gather = {value1,value2}
# or
gather set(value)
Copy the code

Basic operations:

# define
gather = (1.2.3.4.5)

# add
gather.add(6)

# remove
gather.remove(1)

# Remove a random element
gather.pop() 

Count the number of elements
len(gather)

# Clear collection elements
gather.clear()

# Determine whether the element exists
2 in gather
Copy the code

Branch structure

If-else if-elif-else(I don’t want to write else here)

Logical result:

  • Anything in Python that is “empty” is false
  • “” To write nothing is false, to write anything is true
  • Empty tuples, empty lists, empty dictionaries, and 0 are all false

Example:

a = 1
b = 1

if a < b:
	print("A less than b")
elif a==b:
	print("A is b")
else:
	print("A greater than b")
Copy the code

Ten, cyclic structure

Loop statements in Python are for and while statements.

  • The while loop

The general form of the while statement in Python:

whileJudgment condition (condition) : Execute statement ()......Copy the code

Example: Calculate a sum from 1 to 100

n = 100 
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("Sum from 1 to %d: %d" % (n,sum))
Copy the code

  • The while loop uses an else statement

If the condition following the while is false, the else block is executed.

Grammar:

whileJudgment condition (condition) : Execute statement ()......else: Execute statement ()......Copy the code

Combined with the above example:

  • For statement

A Python for loop can iterate over any iterable, such as a list or a string.

The general format of a for loop is as follows:

for <variable> in <sequence>:
    <statements>
else:
    <statements>
Copy the code

Example:

arr = [1.2.3.4.5]
for x in arr:
	print (x)
Copy the code