**This article is included inPython from introduction to Mastery Series**

## 1. Instructions and procedures

The hardware system of a computer usually consists of five parts, including:**Arithmetic unit, controller, memory, input device and output device**。

Among them, the arithmetic unit and the controller together is what we usually call the central processor. Its function is to execute various operation and control instructions as well as to process the data in the computer software. The program we usually call is actually a collection of instructions. Our program is to organize a series of instructions together in a certain way, and then control the computer to do what we want it to do through these instructions.

Today, most of the computers we use, although their components are more and more sophisticated and their processing power is more and more powerful, but in essence, they still belong to“**Feng****·****Neumann structure**”Computer.“Feng·Neumann structure”There are two key points. One is to separate the storage device from the CPU. The other is to put forward to separate the data**Binary encoding**。

Binary is a“Every two enters one.”The counting method of the“Ten in one”There is no substantial difference in the counting method of the “ten fingers”. Human beings use the decimal system because they have ten fingers (because ten fingers can only carry after they are used up in counting, of course, there are exceptions in everything. Mayans may count their toes because they have been barefoot for many years, so they use the counting method of the “twenty base”. Under the guidance of this counting method, the Mayans use the decimal system The calendar is different from the calendar we usually use, but according to the calendar of the Maya,2012Year is the last so-called“Solar system”And2013Year is new“Solar system”At the beginning of the story, this story was misrepresented as”2012The end of the world predicted by the Maya“Today, we can boldly guess that the reason why the Maya civilization developed slowly is also related to the use of the decimal system.

For computers, binary is the easiest to implement on physical devices (high voltage representation1, low voltage0）, so“Feng·Neumann structure”All of our computers use binary. Although we don’t need every programmer to be able to use binary thinking mode to work, it is necessary to understand binary and its conversion relationship with decimal system in our life, as well as binary conversion relationship with octal and hexadecimal system. If you are not familiar with this, you can use Wikipedia or Baidu Encyclopedia for science popularization.

Prompt: Recently, the research on quantum computer has been pushed to the forefront. Quantum computer is based on quantum mechanics and uses quantum teleportation to transmit information.2018year6Month,IntelAnnounced the development of a new quantum chip and passed the test in the near absolute zero environment;2019year1Month,IBMThe first commercial quantum computer has been released to the world.

## 2. Variables and types

In program design, variable is a carrier of data storage. Variables in a computer are actual data or data stored in memory**A block of memory space**，**The value of a variable can be read and modified**, which is the basis of all calculations and controls.

There are many types of data that can be processed by computer. In addition to numerical value, it can also process all kinds of data, such as text, graphics, audio, video, etc., so different data needs to be defined with different storage types.PythonThere are many data types in, and it also allows us to customize new data types (this will be discussed later). Let’s first introduce several common data types.

**integer**: in Python, you can handle integers of any size (there are two types of integers in Python 2. X, int and long, but this distinction is not significant for Python, so in Python 3. X, integers are only**int**This one), and support binary (such as 0b100, converted to decimal is 4), octal (such as 0o100, converted to decimal is 64), decimal (100) and hex (0x100, converted to decimal is 256).**float**: floating point number**decimal**The reason why it is called floating-point number is that the decimal point position of a floating-point number can be changed when it is expressed according to the scientific notation. In addition to the mathematical notation (such as 123.456), floating-point number**It also supports scientific counting**(e.g. 1.23456e2).**String type**: string is**Any text in single or double quotation marks**For example, ‘hello’ and ‘hello’. Strings also have original string representation, byte string representation, Unicode string representation, and can be written in multiple lines (beginning with three single quotes or three double quotes, ending with three single quotes or three double quotes).**Boolean type**Boolean value**only****True****、****False****Two values**, either true or false. In Python, you can directly use true or false to represent Boolean values（**Please pay attention to case**）, or it can be calculated by Boolean operation (for example, 3 < 5 will generate boolean value true, and 2 = = 1 will generate boolean value false).**Complex type**: the form is like 3 + 5J. Like the representation of complex number in mathematics, the only difference is that I of virtual part is replaced by J. In fact, this type can’t be regarded as a common type. You can understand it.

### 2.1 Variable naming

For each variable we need to give it a name, just as each of us has his own loud name. stayPythonThe following are mandatory and strongly recommended non mandatory rules for variable naming.

l Hard rules:

n Variable name**Letter**(generalized)UnicodeCharacters, excluding special characters)**Numbers and underscores**Constitute**Number cannot start**。

n **Case sensitive**(uppercase)aLowercaseAIt’s two different variables.

n Do not follow**Keyword**(words with special meanings will be mentioned later) and**System reserved word**(name of function, module, etc.) conflicts.

l PEP 8Requirement:

n Spell in lowercase letters, and underline multiple words.

n The protected instance properties start with a single underscore (as we’ll see later).

n Private instance properties start with two underscores (as we’ll see later).

Of course, as a professional programmer, when naming variables (in fact, all identifiers) do**See name**Meaning is also very important.

### 2.2 Use of variables

Here are a few examples to illustrate the type and use of variables.

#### 01-arithmetic operation

```
"""
Use variables to save data and perform arithmetic operations
Version: 0.1
Author: along
"""
a = 21
b = 12
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
```

Note:PythonArithmetic operator

operator |
describe |
Example |

+ |
plus – Add two objects |
a + b Output result 33 |

– |
reduce – Get a negative number or a number minus another number |
a – b Output result 9 |

* |
ride – Multiply two numbers or return a string repeated several times |
a * b Output result 252 |

/ |
except – xDividey |
a / b Output result 1.75 |

% |
Take die – Returns the remainder of the Division |
a % b Output result 9 |

** |
power – ReturnxOfypow |
a**b by21Of12Secondary powerThe result is 7355827511386641 |

// |
Divide and conquer – Returns the integer part of the quotient（ |
a // b Output result 1 |

#### 02-Application of variable types

stayPythonCan be used in**type****function**Check the type of the variable. The concept of function in programming is consistent with that in mathematics, which includes function name, independent variable and dependent variable. If we don’t understand this concept for the time being, it doesn’t matter. We will explain the definition and use of functions in the following chapters.

```
"""
Use type() to check the type of the variable
Version: 0.1
Author: along
"""
a = 100
b = 12.345
c = 1 + 5j
d = 'hello, world'
e = True
print(type(a)) #
print(type(b)) #
print(type(c)) #
print(type(d)) #
print(type(e)) #
```

have access toPythonThe built-in functions in convert variable types.

l **int()**: converts a numeric value or string to an integer, specifying the base.

l **float()**: converts a string to a floating-point number.

l **str()**: converts the specified object to string form, and you can specify the encoding.

l **chr()**: converts an integer to a string (one character) corresponding to the encoding.

l **ord()**: converts a string (one character) to the corresponding encoding (integer).

The following code uses the keyboard to input two integers to realize the arithmetic operation of the two integers.

```
"""
Use the input() function to get keyboard input (string)
Use the int() function to convert the input string to an integer
Using the print() function to output a string with placeholders
Version: 0.1
Author: along
"""
a = int(input('a = '))
b = int(input('b = '))
c = float(input('c = '))
print('%d + %d = %d' % (a, b, a + b))
print('%d - %f = %f' % (a, c, a - c))
print('%d * %f = %f' % (a, c, a * c))
print('%d / %d = %f' % (a, b, a / b))
print('%d // %d = %d' % (a, b, a // b))
print('%d %% %d = %d' % (a, b, a % b))
print('%d ** %d = %d' % (a, b, a ** b))
```

Description: aboveprintThe string output in the function uses placeholder syntax, where

%dIt’s an integer.Placeholder for,%fIt’s a decimal.Placeholder for,%%Percent sign(because the percent sign represents a placeholder, the percent sign in a string with placeholders must be written as%%）, after string%The following variable values will replace the placeholders and output them to the terminal. Run the above program and see the program execution results.

## 3. operator

PythonMultiple operators are supported. The following table lists all operators roughly in the order of priority from high to low. The priority of operators refers to what operations are performed first and then when multiple operators appear at the same time. In addition to the assignment operators and arithmetic operators we have used before, we will talk about the use of other operators later.

operator |
describe |

[] [:] |
Subscript, slice |

** |
index |

~ + – |
Inverse position, Plus and minus sign |

* / % // |
Multiply, divide, module, divide |

+ – |
Addition and subtraction |

>> << |
Move right, move left |

& |
Bitwise |

^ | |
Bitwise exclusive or |

<= >= |
Less than or equal to, less than, greater than, greater than or equal to |

== != |
Equal to, not equal to |

is is not |
Identity operator |

in not in |
member operator |

not or and |
Logical operators |

= += -= *= /= %= //= **= &= ` |
= ^= >>= <<=` |

Explain: In actual development, if you don’t know the priority of operators, you can use parentheses to ensure the order of operation execution.

The following example demonstrates the use of assignment operators and composite assignment operators.

```
"""
Assignment operators and compound assignment operators
Version: 0.1
Author: along
"""
a = 10
b = 5
A + = B ා is equivalent to a = a + B
A * = a + 2 ා equivalent to: a = a * (a + 2)
Print (a) think about what's going to be output here
```

The following example demonstrates the use of comparison operators (relational operators), logical operators, and identity operators.

```
"""
Comparison, logic and the use of identity operators
Version: 0.1
Author: along
"""
flag0 = 1 == 1
flag1 = 3 > 2
flag2 = 2 < 1
flag3 = flag1 and flag2
flag4 = flag1 or flag2
flag5 = not (1 != 2)
print('flag0 =', flag0) # flag0 = True
print('flag1 =', flag1) # flag1 = True
print('flag2 =', flag2) # flag2 = False
print('flag3 =', flag3) # flag3 = False
print('flag4 =', flag4) # flag4 = True
print('flag5 =', flag5) # flag5 = False
print(flag1 is True) # True
print(flag2 is not False) # False
```

Note: one true or true, one false and false (memorize the school password)

## 4. Practice

### Practice1: Fahrenheit to Celsius.

Prompt: the conversion formula of Fahrenheit temperature to Celsius temperature is:$C=(F – 32) \div 1.8$。

Reference answer:

```
"""
Convert Fahrenheit to Celsius
Version: 0.1
Author: along
"""
F = float (input ('Please input Fahrenheit temperature: ')
c = (f - 32) / 1.8
Print ('%. 1F f =%. 1F C'% (F, c))
```

Note:%.1f Finger taking1The decimal of the remainder.

### Practice2: enter the radius of the circle to calculate the perimeter and area.

Reference answer:

```
"""
Enter radius to calculate the circumference and area of the circle
Version: 0.1
Author: along
"""
import math
R = float (input ('Please input the radius of the circle: ')
C=2 * math.pi * r
S=math.pi * r * r
Print ('perimeter:%. 2F '% C)
Print ('area:%. 2F '% s)
```

### Practice3: enter the year to determine if it is a leap year.

Reference answer:

```
"""
Input year output true if leap year output false otherwise
Version: 0.1
Author: along
"""
Year = int (input ('Please enter year: ')
#If the code is too long to read, you can use \ to wrap the code
is_leap = (year % 4 == 0 and year % 100 != 0) or \
year % 400 == 0
print(is_leap)
```