Table of contents
1. Constants and expressions
We can use Python as a calculator to perform some calculations, such as
print(1 + 2 - 1)
print(1 + 2 * 2)
print(1 + 2 / 2)
NOTE: In the above code,
A formula like 1 + 2 - 3 is called an expression the result of the calculation is called the return value of the expression
2. Variables and types
2.1 What are variables
30.2 + 12.3 + 23.4 + 9.3, write code to find the variance of these four numbers .
avg = (30.2 + 12.3 + 23.4 + 9.3) / 4
total = (30.2 - avg) ** 2 + (12.3 - avg) ** 2 + (23.4 - avg) ** 2 + (9.3 - avg) ** 2
result = total / 3
print(result)
Note:
2.2 Syntax of variables
a = 10
Variable names are composed of numbers, letters and underscoresnumber cannot start withThe variable name cannot be repeated with "keyword"Variable names are case sensitive. num and Num are two different variable names
Soft rules ( recommended compliance )
Use descriptive words to express the variable name , try to express the role of the variable.A variable name can be composed of multiple words , it doesn't matter if it is longer , but the meaning should be clearWhen the variable name contains multiple words , it is recommended to use " camel case ". Such as totalCount , personInfo , etc. , exceptExcept for the first word , the first letter of the remaining words is capitalized
2) Using variables
a = 10
print(a)
Modify the value of a variable
# 定义变量
a = 10
# 修改变量值
a = 20
print(a)
Note : In Python , modifying variables also uses the = operation , which does not seem to be significantly different from defining variables .
For the same variable, the variable is defined at the beginning, and the variable is modified later
a = 10
b = 20
# 将 b = 的值赋予 a
a = b
print(a)
print(b)
2.3 Types of variables
a = 10
print(type(a))
PS: type is similar to print , and it is also a built-in function of python . You can use type to check the type of a variable.
a = 0.1
print(type(a))
Python's decimal only has a type of float , not a double type . But in fact, Python's float is equivalent to C++/Java 's double, representing double-precision floating-point numbers
3) string
a = 'hello'
print(type(a))
Enclosed with ' ' or " " , it is called a string . It can be used to represent text.
a = 'hello'
print(len(a))
For two strings, you can use + to concatenate
a = 'hello'
b = 'world'
print(a + b)
4) Boolean
a = True
b = False
print(type(a))
print(type(b))
(5) Others
In addition to the above types , there are list, tuple, dict, custom types, etc. in Python
2.4 Dynamic Type Features
a = 10
print(type(a))
b = 'hello'
print(type(b))
During the execution of the program , the type of a is initially int, and then becomes str.