Chapter 2: Elements of Language

Chapter 2: Elements of Language

See: Chapter 1: Initial python
resource directory: Code (2)
Article resource download: (Chapter 1-15)
Link: https://pan.baidu.com/s/1Mh1knjT4Wwt__7A9eqHmng?pwd=t2j3
Extraction code: t2j3
or transfer Go to the column "python tutorial" to view

Instructions and procedures

The hardware system of a computer usually consists of five major components, including: arithmetic unit, controller, memory, input device and output device. Among them, the combination of the arithmetic unit and the controller is what we usually call the central processing unit, and its function is to execute various calculations and control instructions and process data in computer software. What we usually call a program is actually a collection of instructions. Our program is to organize a series of instructions together in a certain way, and then use these instructions to control the computer to do what we want it to do. The computers we use most of the time today, although their components are becoming more and more sophisticated in workmanship and their processing capabilities are becoming more and more powerful, they still belong to the "von Neumann structure" computer in essence . There are two key points in the "Von Neumann structure". One is to separate the storage device from the central processing unit, and the other is to encode data in binary. Binary is a counting method of "every two to one", which is not substantially different from the "every ten to one" counting method used by us humans. Humans use the decimal system because they have ten fingers (because when counting After the ten fingers are used up, you can only carry. Of course, there are exceptions to everything. The Mayans may have counted their toes because they were barefoot for many years, so they used the 20-digit counting method. Under the guidance of this counting method, the Mayan calendar is different from the calendar we usually use. According to the Mayan calendar, 2012 is the last year of the last so-called "solar period", while 2013 is the new year. The beginning of the "Sun Period", and later this incident was misrepresented as "2012 is the end of the world predicted by the Mayans". Today we can boldly guess that the reason for the slow development of Maya civilization is probably related to the use of decimal notation). For computers, binary is the easiest to implement on physical devices (high voltage means 1, low voltage means 0), so computers in the "von Neumann structure" use binary. Although we don't need every programmer to be able to use a binary way of thinking to work, it is still useful to understand binary and its conversion relationship with the decimal system in our lives, as well as the conversion relationship between binary and octal and hexadecimal. necessary. If you are not familiar with this point, you can use Wikipedia or Baidu Baike by yourselfPopular science.

Explanation : The recent research on quantum computers has been pushed to the forefront. Quantum computers perform calculations based on quantum mechanics and use quantum teleportation to transmit information. In June 2018, Intel announced that it had developed a new quantum chip and passed the test in an environment near absolute zero; in 2019, both IBM and Google launched their own quantum computers.

variables and types

In programming, a variable is a carrier for storing data. The variable in the computer is the actual data or a piece of memory space for storing data in the memory. The value of the variable can be read and modified, which is the basis of all calculations and controls. There are many types of data that computers can process. In addition to numerical values, they can also process various data such as text, graphics, audio, and video. Then different data need to define different storage types. There are many data types in Python, and it also allows us to customize new data types (this will be discussed later), let's introduce several commonly used data types first.

  • Integer: Python can handle integers of any size (there are two types of integers in Python 2.x int, longbut this distinction is of little significance to Python, so int is the only integer in Python 3.x ), and supports binary (for example 0b100, converted to decimal is 4), octal (for example 0o100, converted to decimal is 64), decimal ( 100) and hexadecimal ( 0x100, converted to decimal is 256) notation.
  • Floating-point type: Floating-point numbers are also decimal numbers. The reason why they are called floating-point numbers is that when expressed in scientific notation, the position of the decimal point of a floating-point number is variable. In addition to mathematical notation (such as), floating-point numbers also 123.456support Scientific notation (eg 1.23456e2).
  • String type: String is any text enclosed in single quotes or double quotes, such as 'hello'and "hello", string also has raw string notation, byte string notation, Unicode string notation, and can be written as multiple The form of the line (beginning with three single quotes or three double quotes and ending with three single quotes or three double quotes).
  • Boolean type: Boolean values ​​have only two values True, Falseeither True, or False, in Python, you can use directly Trueto Falserepresent Boolean values ​​(please pay attention to capitalization), or they can be calculated by Boolean operations (for example, 3 < 5Boolean values ​​will be generated True, and 2 == 1yields a boolean value False).
  • Complex number type: The shape is 3+5jthe same as the complex number representation in mathematics, the only difference is that the imaginary part is ireplaced j. In fact, this type is not commonly used, you just need to understand it.

variable naming

For each variable we need to give it a name, just as each of us has our own famous name. In Python, variable naming needs to follow the following hard rules and non-hard rules that are strongly recommended.

  • Hard rules:
    • A variable name consists of letters (generalized Unicode characters, excluding special characters), numbers, and underscores, and numbers cannot start with them.
    • Case sensitive (uppercase aand lowercase Aare two different variables).
    • Do not conflict with keywords (words with special meanings, which will be discussed later) and system reserved words (such as names of functions, modules, etc.).
  • PEP 8 requires:
    • Spell in lowercase letters and connect multiple words with an underscore.
    • Protected instance attributes begin with a single underscore (described later).
    • Private instance attributes start with two underscores (described later).

Of course, as a professional programmer, it is also very important to be familiar with the names when naming variables (in fact, all identifiers).

use of variables

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

"""
使用变量保存数据并进行加减乘除运算

Version: 0.1
Author: 骆昊
"""
a = 321
b = 12
print(a + b)    # 333
print(a - b)    # 309
print(a * b)    # 3852
print(a / b)    # 26.75

In Python, typefunctions can be used to check the type of variables. The concept of function in programming is consistent with the concept of function in mathematics. I believe everyone is familiar with functions in mathematics. It includes function names, independent variables and dependent variables. It doesn't matter if you don't understand this concept for the time being, we will explain the definition and use of functions in subsequent chapters.

"""
使用type()检查变量的类型

Version: 0.1
Author: 骆昊
"""
a = 100
b = 12.345
c = 1 + 5j
d = 'hello, world'
e = True
print(type(a))    # <class 'int'>
print(type(b))    # <class 'float'>
print(type(c))    # <class 'complex'>
print(type(d))    # <class 'str'>
print(type(e))    # <class 'bool'>

Variable types can be converted using built-in functions in Python.

  • int(): Convert a value or string to an integer, and the base can be specified.
  • float(): Convert a string to a floating point number.
  • str(): Convert the specified object into a string, and the encoding can be specified.
  • chr(): Convert an integer to a string (one character) corresponding to the encoding.
  • ord(): Convert a string (one character) to the corresponding encoding (integer).

The following code implements arithmetic operations on two integers by entering two integers through the keyboard.

"""
使用input()函数获取键盘输入(字符串)
使用int()函数将输入的字符串转换成整数
使用print()函数输出带占位符的字符串

Version: 0.1
Author: 骆昊
"""
a = int(input('a = '))
b = int(input('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))
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))

Explanation : The string output in the above print function uses the placeholder syntax, which %dis an integer placeholder %fand a decimal placeholder, which %%means a percent sign (because the percent sign represents a placeholder, so the placeholder with The placeholder string must be written as a percent sign ), the variable value after the string will replace the placeholder and output to the terminal, run the above program, and see the result of the program execution %%. %.

operator

Python supports a variety of operators. The following table roughly lists all operators in order of priority from high to low. The priority of an operator refers to what operation to do first and then to do it when multiple operators appear at the same time. what operation. 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
~ + - bitwise negation, sign
* / % // Multiply, Divide, Modulo, Divide
+ - add, subtract
>> << move right, move left
& bitwise AND
^ | bitwise exclusive or, bitwise 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
= += -= *= /= %= //= **= &= ` = ^=` `>>=` `<<=`

Note: In actual development, if you do not know the precedence of operators, you can use parentheses to ensure the execution order of operations.

assignment operator

The assignment operator should be the most common operator, and its role is to assign the value on the right to the variable on the left. The following example demonstrates the use of assignment operators and compound assignment operators.

"""
赋值运算符和复合赋值运算符

Version: 0.1
Author: 骆昊
"""
a = 10
b = 3
a += b        # 相当于:a = a + b
a *= a + 2    # 相当于:a = a * (a + 2)
print(a)      # 算一下这里会输出什么

Comparison and Logical Operators

Some comparison operators are also called relational operators, including ==, !=, <, >, <=, >=, I believe there is nothing to explain, everyone can understand at a glance, the only thing that needs to be reminded is that the comparison is equal ==, please pay attention to this place It is two equal signs, because =it is an assignment operator, as we just mentioned above, ==it is a comparison operator that compares equality. The comparison operators produce a boolean value, either is Trueor is False.

There are three logical operators, namely and, orand not. andIt literally means "and", so andthe operator will connect two Boolean values. If both Boolean values ​​are equal True, then the result of the operation is True; if one of the Boolean values ​​on the left and right is yes False, the final result of the operation is False. I believe everyone has already thought that if andthe Boolean value on the left is False, no matter what the Boolean value on the right is, the final result will be the same False, so the value on the right will be skipped (short-circuit processing) when doing calculations, which means In the case of andthe operator on the left False, the expression on the right is not executed at all. orLiterally means "or", so orthe operator also connects two boolean values, and if either of the two boolean values ​​is yes True, then the final result is True. Of course, orthe operator also has a short-circuit function. In Truethe case of a Boolean value on its left, the expression on the right will not be executed at all. notThe operator will be followed by a Boolean value, and its function is to get the opposite value of the Boolean value, that is, if the following Boolean value is the result of the operation, Trueand Falseif the following Boolean value is, Falsethe result of the operation is True.

"""
比较运算符和逻辑运算符的使用

Version: 0.1
Author: 骆昊
"""
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

Explanation : The priority of the comparison operator is higher than that of the assignment operator, so flag0 = 1 == 1first 1 == 1generate a Boolean value True, and then assign this value to the variable flag0. printThe function can output multiple values, which can be ,separated by commas, and the output content is separated by spaces by default.

practise

Exercise 1: Convert Fahrenheit to Celsius.

Tip: The conversion formula for Fahrenheit to Celsius is: C = ( F − 32 ) ÷ 1.8 C=(F - 32) \div 1.8C=(F32)÷1.8

Reference answer:

"""
将华氏温度转换为摄氏温度

Version: 0.1
Author: 骆昊
"""
f = float(input('请输入华氏温度: '))
c = (f - 32) / 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f, c))

Explanation : When using printthe function output, the string content can also be formatted. printThe string in the above function %.1fis a placeholder, floatwhich will be replaced by a variable value of a type later. Similarly, if there is one in the string , it can be replaced %dwith a variable value of a type later , and it will be replaced by the value of the string. In addition to this way of formatting strings, you can also format strings in the following way, where and can be regarded as sum first , indicating that the two placeholders will be replaced with variables and their values ​​during output , the latter indicates that this is a floating-point number, and one significant figure is reserved after the decimal point.int%s{f:.1f}{c:.1f}{f}{c}fc:.1f

print(f'{f:.1f}华氏度 = {c:.1f}摄氏度')

Exercise 2: Enter the radius of a circle to calculate the circumference and area.

Reference answer:

"""
输入半径计算圆的周长和面积

Version: 0.1
Author: 骆昊
"""
radius = float(input('请输入圆的半径: '))
perimeter = 2 * 3.1416 * radius
area = 3.1416 * radius * radius
print('周长: %.2f' % perimeter)
print('面积: %.2f' % area)

Exercise 3: Enter the year to judge whether it is a leap year.

Reference answer:

"""
输入年份 如果是闰年输出True 否则输出False

Version: 0.1
Author: 骆昊
"""
year = int(input('请输入年份: '))
# 如果代码太长写成一行不便于阅读 可以使用\对代码进行折行
is_leap = year % 4 == 0 and year % 100 != 0 or \
          year % 400 == 0
print(is_leap)

Explanation : The comparison operator will generate Boolean values, and the logical operator andand orwill combine these Boolean values, and finally get a Boolean value, which is output in leap years Trueand output in normal years False.

Guess you like

Origin blog.csdn.net/xyx2023/article/details/129628688