Python basic instructions (Part 1)

Insert image description here

constants and expressions

print(1 + 2 - 3)
print(1 + 2 * 3)
print(1 + 2 / 3)

operation result

0
7
1.6666666666666665

printIt is a Pythonbuilt-in function
that can use + - * / ( ) other operators to perform arithmetic operations. Multiplication and division are calculated first, followed by addition and subtraction.
There can be no space or multiple spaces between operators and numbers. But it is generally customary to write a space

An expression in the form of 1 + 2 - 3this is called an expression in a programming language. The result of the expression is called the return value of the expression.
This 1 , 2 , 3kind is called a literal constant, + - * / and this kind is called an operator or operator.

Note : C / C++Students who are familiar with may think that 2 / 3the result is 0(the decimal part is truncated), but Pythonthe result obtained in is a decimal, which is more in line with the intuition of daily use.

Variables and types

1. What is a variable?

In Python, variables are identifiers used to store data values. These identifiers can be a combination of letters, numbers, and underscores, but they must follow some naming rules. For example, variable names cannot start with numbers, cannot contain spaces, and so on. Variables in Python are dynamically typed, which means that you do not need to declare the data type of the variable in advance, Python will automatically determine its type based on the value assigned to the variable.

Here is a simple Python variable example:

x = 10  # 创建一个整数类型的变量x并赋值为10
name = "John"  # 创建一个字符串类型的变量name并赋值为"John"
is_student = True  # 创建一个布尔类型的变量is_student并赋值为True
total = (67.5 - avg) ** 2 + (89.0 - avg) ** 2 + (12.9 - avg) ** 2 + (32.2 - avg) ** 2 #创建一个浮点数类型的变量total并赋值为四个小数的方差

Variables in Python have some significant differences compared to C:

  1. Dynamic typing : In C, you need to explicitly specify the data type of a variable when declaring it, whereas in Python, the data type of a variable is automatically determined by the value assigned to it. This makes Python more flexible and concise.
  2. No declaration required : In C, you have to explicitly declare a variable before using it, but this is not required in Python. You can assign a value directly to a variable and Python will automatically create it.
  3. No semicolon required : In C, statements usually end with a semicolon, while Python uses indentation to represent blocks of code and does not require a semicolon.
  4. More advanced data types : Python has many built-in advanced data types, such as lists, dictionaries, sets, and tuples, which make processing complex data structures in Python more convenient.
  5. Garbage collection : Python has automatic memory management and garbage collection mechanisms, eliminating the need to manually manage memory allocation and release.

Overall, Python is more concise and easier to learn than the C language, but some performance may be sacrificed in some cases. When choosing a programming language, there are trade-offs based on project needs and performance requirements.

Note:
x,name,is_student,total They are all variables.
**In Python, they represent exponentiation operations. ** 2That is, finding squares.

2. Syntax of variables

2.1 Define variables

a = 10

The statement to create a variable is very simple, where

ais the variable name. When we create many variables, we can use their names to distinguish them. It is the
=assignment operator, which means putting =the data on the right into =the space on the left

Note: The names of variables must follow certain rules

Hard rules (must be followed)

Variable names consist of numbers, letters and underscores.

Numbers cannot begin.

Variable names cannot repeat "keywords".

Variable names are case-sensitive. num and Num are two different variable names.

Soft rules (recommended to follow)

Use descriptive words in variable names to express the function of the variable as much as possible.

A variable name can be composed of multiple words. It doesn't matter if it is longer, but the meaning must be clear.

When the variable name contains multiple words, it is recommended to use "camel case naming". In this form totalCount, personInfoexcept for the first word, the first letters of the remaining words are capitalized.

In mathematics, variables are usually represented by simple English letters or Latin letters such as x, y, z. However, this is not recommended in programming. The reason is that in programming, many variables are usually created at the same time in a program. If only Using a single letter to represent it, when there are too many variables, it is difficult to remember which variable does what, which brings certain difficulties to maintaining the program. Therefore, we recommend using clearly descriptive names to represent The purpose of the variable.

2.2 Using variables

Read the value of a variable

a = 10
print(a)

Modify the value of a variable

a = 20
print(a)

In Python, modifying variables also uses the = operation, which does not seem to be significantly different from defining variables .
Of course, you can also assign the value of one variable to another variable

a = 10
b = 20
a = b
print(a)
print(b)

3. Type of variable

Python's integer type (int), floating point type (float), string type (str) and logical value (bool) have some differences from the corresponding types in C language :

  1. Integer type (int):

    • Integer types in Python are dynamic and do not need to be specified. Python will automatically determine its type based on the value assigned to the variable.
    • Python's integer type can represent integers of any size without a fixed range limit. This is called "arbitrary-precision integers".
    • In C, the size of integer types depends on the compiler and platform, and usually has a fixed number of bits and range.

    In Python, integer types can represent very large integers without worrying about overflow issues. For example:

    x = 1234567890123456789012345678901234567890
    print(x)
    print(type(x))
    

    This number might cause overflow or precision issues in C, but no problem in Python.

    1234567890123456789012345678901234567890
    <class 'int'>
    
  2. Floating point type (float):

    • Floating point types in Python are also dynamic and do not require explicit type specification.
    • Python uses the double-precision floating-point standard (IEEE 754), which typically supports 15 to 17 digits of decimal precision.
    • In C, the size and precision of floating point types depend on the compiler and platform, and can be single or double precision floating point numbers.

    Python’s floating point type has double precision and can represent decimal values, for example:

    y = 3.14159265358979323846
    print(y)
    print(type(y))
    

    This floating point number has enough precision in Python to represent an approximation of π. In C, floating point precision depends on the compiler and platform and may not be precise enough.

    3.141592653589793
    <class 'float'>
    
  3. String type (str):

    • Python's string type is a Unicode string, which means that it can represent characters from most character sets in the world, including ASCII characters and non-ASCII characters.
    • Python's strings are immutable, which means that once created, their contents cannot be modified.
    • In C, strings are usually character arrays, are null-terminated, and can be modified.

    Python's string type can contain a variety of characters, including Unicode characters. This makes it very convenient when working with text data in different character sets, for example:

    name = "李雷"
    print(name)
    print(type(name))
    

    This is a string containing Chinese characters and Python can handle it easily. In C, handling Unicode characters can be more complicated, requiring the use of wide character or Unicode conversion functions.

    李雷
    <class 'str'>
    

Overall, the integer and floating point types in Python have greater flexibility and precision, while the string types have better Unicode support and immutability. These differences make Python more convenient for handling various data types, but there are trade-offs in performance, as C is generally more efficient at handling the underlying data. Depending on your specific needs, you can choose to use different languages ​​and data types.

Note : In Python, there is no difference between a string composed of single quotes and a string composed of double quotes. 'hello'and "hello"are completely equivalent.

You can use the len function to get the length of a string

a = 'hello'
print(len(a))

output5

You can use + to concatenate two strings

a = 'hello
b = 'world'
print(a + b)

outputhelloworld

Here is the addition of two strings. You cannot add strings and integers/floating point numbers.

  1. Logical value (bool) :
    • The Boolean type in Python has two values: True and False.
    • Boolean types are often used for conditional judgments, such as in if statements.
    • Python's Boolean type is case-sensitive. True and False must start with an uppercase letter. Lowercase true and false are not Boolean values.
is_true = True
is_false = False

if is_true:
    print("这是True")

if not is_false:
    print("这是False")
print(type(is_true))
print(type(is_false))

output

这是True
这是False
<class 'bool'>
<class 'bool'>
  1. other

In addition to the above types, Pythonthere are also list, tuple, dictcustom types and so on. We will introduce them separately later.

4. Why are there so many types?

The type determines how much space the data occupies in memory.
For example, the float type occupies 8 bytes in memory.

Computers use binary to represent data. That is, each bit can only represent 0 or 1.
1 binary bit is called a "bit", and 8 binary bits is called a "byte" (Byte)
A float variable occupies 8 bytes of space in the memory, which is 64 binary bits. My computer has 16GB of memory space, which means a total of 1024 * 1024 * 1024 * 8 so many binary bits.

The type actually stipulates what kind of operations can be performed on this variable.
For example, int / floatvariables of type can perform + - * /operations such as ,
while strvariables of type can only perform + (and the behavior is string concatenation), which cannot be performed - * /, but they can also be used lenand other operations. operate.

Summary: The type system actually "classifies" variables. Variables (data) of the same type often have similar characteristics and usage rules

5. Dynamic type characteristics

In Python, the type of a variable can change during the "program running" process. This feature is called "dynamic typing"

a = 10
print(type(a))
a = 'hello'
print(type(a))

Output :

<class 'int'>
<class 'str'>

During the execution of the program, the type of a is int at first, and then becomes str.
Languages ​​such as C++/Java do not allow such operations. The type of a variable is fixed after it is defined. This feature is called "static typing"
Dynamic typing is a double-edged sword

For small and medium-sized programs, the amount of code can be greatly reduced (for example, writing one piece of code can support multiple types at the same time).
For large programs, it increases the cost of interaction between modules. (The code provided by programmer A is difficult to be understood by programmer B. )

Comment

In Python, there are two main types of comments: single-line comments and multi-line comments. Comments are used to add explanations or annotations to the code and will not be executed by the interpreter.

  1. Single-line comments: A single-line comment starts with a pound #sign, and the following content is treated as a comment until the end of the line. Single-line comments are often used to add a brief explanation of the code.

Example:

# 这是一个单行注释
x = 5  # 这是赋值语句,将5赋给变量x
  1. Multi-line comments: There are no block comments in Python like in C or C++, but you can use triple quotes '''or """to create a multi-line string and place it in the code to achieve the effect of a multi-line comment. Although this actually creates a string, if you don't assign it to a variable it will be treated as a comment.

Example:

'''
这是一个
多行注释
它实际上是一个多行字符串,但没有分配给变量
'''
print("Hello, World!")

Or use double quotes:

"""
这也是一个
多行注释
"""
print("Hello, World!")

Please note that although multi-line strings can be used for multi-line comments, usually developers prefer to use single-line comments and function/class/method documentation strings (docstrings) to add comments and documentation.

Example:

def add(x, y):
    """
    这是一个函数的文档字符串
    它用于计算两个数字的和
    """
    return x + y

Such docstrings can help()be viewed using functions, and there are tools that can generate documentation. In actual development, documentation strings are very helpful for code readability and maintainability.

Annotation specifications

  1. Accurate content: The content of comments should be consistent and matched with the code, and should be updated in a timely manner when the code is modified.
  2. Reasonable length: Notes should be neither too concise nor lengthy.
  3. Use Chinese: Generally, Chinese companies require notes to be written in Chinese, while foreign companies are a different matter.
  4. Be positive: Do not include negative energy in comments (such as leader SB, etc.).It is said that it was in the news and was shot, the manual operation was funny

input Output

1. Interaction between program and user

The program needs to interact with the user

The process by which the user transfers information to the program is called "input".
The process by which the program displays the results to the user is called "output".

The most basic method of input and output is the console. The user inputs some strings through the console, and the program prints out some strings through the console.

When PyCharm runs the program, the window that pops up below can be regarded as a console.

Insert image description here
The cmd program that comes with windows can also be regarded as a console

Insert image description here

The most common method of input and output is a graphical interface

Of course, Python can also be used to develop programs with graphical interfaces. However, graphical program development itself is a big topic, and we will introduce it in detail later.

2. Output through the console

For example, output a variable of other types

a = 10
print(a)
b = True
print(b)

output

10
True

More often than not, the content we want to output is a mixture of strings and variables.

Example: output num = 10

num = 10
print(f'num = {
      
      num}')

Use f as a prefix string, called f-string
inside which can be used { }to embed an other variable/expression

3. Enter through the console

python uses the input function to read user input from the console

num = 0
num = input('请输入一个整数: ')
print(f'你输入的整数是 {
      
      num}')

output after input

请输入一个整数: 2
你输入的整数是 2

The parameter of input is equivalent to a "prompt message", or it may not be present.
The return value of input is the content input by the user. It is a string type

a = input('请输入第一个整数: ')
b = input('请输入第二个整数: ')
print(f'a + b = {
      
      a + b}')

output after input

请输入第一个整数: 20
请输入第二个整数: 23
a + b = 2023

The result here is string concatenation, not arithmetic operations. If you want to perform arithmetic operations, you need to convert the type first

a = input('请输入第一个整数: ')
b = input('请输入第二个整数: ')
a = int(a)
b = int(b)
print(f'a + b = {
      
      a + b}')

output after input

请输入第一个整数: 20
请输入第二个整数: 23
a + b = 43

By int( )converting the variable to inttype.
Similarly, float( ), bool( ), str( )the corresponding type conversion can be completed using etc.

Code example: Enter 4 decimals and find the average of the 4 decimals

a = input('请输入第一个数字: ')
b = input('请输入第二个数字: ')
c = input('请输入第三个数字: ')
d = input('请输入第四个数字: ')
a = float(a)
b = float(b)
c = float(c)
d = float(d)
avg = (a + b + c + d) / 4
print(f'平均值: {
      
      avg}')

output after input

请输入第一个数字: 21.2
请输入第二个数字: 20.3
请输入第三个数字: 21.4
请输入第四个数字: 21.5
平均值: 21.1

Code example: Calculate the area of ​​a triangle using Heron's formula

import math
a=float(input("输入直角三角形第一条边"))
b=float(input("输入直角三角形第二条边"))
c=float(input("输入直角三角形第三条边"))
#计算海伦公式中p的值,即半周长
p=(a+b+c)/2
s=math.sqrt(p*(p-a)*(p-b)*(p-c))
print(s)

output after input

输入直角三角形第一条边3
输入直角三角形第二条边4
输入直角三角形第三条边5
6.0

operator

1. Arithmetic operators

+ - * / % ** //Operators that perform arithmetic operations like this are called arithmetic operators

  1. Like other languages, /0 cannot be used as a divisor. Otherwise an exception will be thrown.
print(10 / 0)

output

Traceback (most recent call last):
  File "C:\Users\xzq20\PycharmProjects\pythonProject1\hello.py", line 1, in <module>
    print(10 / 0)
          ~~~^~~
ZeroDivisionError: division by zero

Exception is a common mechanism in programming languages. It means that some "unexpected circumstances" occurred during the running of the program, causing the program to be unable to continue execution.

  1. 整数 / 整数The result may be a decimal. Without truncation
print(1 / 2)

output

0.5
  1. %Not "percent", but the remainder
print(7 % 2)

output

1
  1. **It is to find powers. It can not only calculate integer powers, but also decimal powers.
print(4 ** 2)
print(4 ** 0.5)

output

16
2.0
  1. //It is round division (also called floor division). When an integer is divided by an integer, the result is still an integer (the decimal part is discarded and rounded down. It is not rounded)
print(7 // 2)
print(-7 // 2)

output

3
-4

2. Relational operators

Operators like < <= > >= == != this series are called relational operators, and they compare the relationship between operands .

in

<=is "less than or equal to"

>=is "greater than or equal to"

==is "equal to"

!=is "not equal to"

If the relationship is true, the expression returns True. If the relationship is not true, the expression returnsFalse

a = 10
b = 20
print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)

output

True
True
False
False
False
True

Relational operators not only compare integers/floating point numbers, but also compare strings.

a = 'hello'
b = 'world'
print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)

output

True
True
False
False
False
True

You can directly use ==or !=to determine whether the string contents are equal. (This is C / C++different from ).
The rule for string comparison is "lexicographic order" (equivalent to the map application in C++)

For floating point numbers, do not use == to determine equality.

print(0.1 + 0.2 == 0.3)

output

False

The representation of floating point numbers in computers is not precise! During the calculation process, very small errors are prone to occur.

print(0.1)
print(0.2)
print(0.3)
print(0.1 + 0.2)

output

0.1
0.2
0.3
0.30000000000000004

It can be seen that 0.1 + 0.2the result of is not 0.3, but with a small tail. Although this tail is very small, but ==every penny counts, it will still lead to ==the result ofFalse

This is not only true for Python, but also for mainstream programming languages. This is IEEE754a problem introduced by the floating point format specified by the standard. This was mentioned in my previous C language blog

Correct comparison method : no longer strictly compare equal, but determine that the difference is less than the allowable error range

a = 0.1 + 0.2
b = 0.3
print(-0.000001 < (a - b) < 0.000001)

In actual engineering practice, errors are inevitable, as long as the errors are within a reasonable range

3. Logical operators

Operators like and or notthis series are called logical operators.

and And : Both operands are True, and the final result is True. Otherwise, it is False. (If one is false, it is False)
or Or : Both operands are False, and the final result is False. Otherwise, it is True. (If one is true, it is False. True)
not Logical negation : If the operand itself is True, then False is returned. If the operand itself is False, then True is returned

a = 10
b = 20
c = 30
print(a < b and b < c)
print(a < b and b > c)
print(a > b or b > c)
print(a < b or b > c)
print(not a < b)
print(not a > b)

output

True
False
False
True
False
True

a special way of writing

a < b and b < cThis operation is equivalent to a < b < c. This setting is different from most programming languages.

short circuit evaluation

Similar to other programming languages, Python also has rules for short-circuit evaluation .

For and, if the expression on the left is False, the whole must be False, and the expression on the right will no longer be executed.
For or, if the expression on the left is True, the whole must be True, and the expression on the right will no longer be executed.

print(10 > 20 and 10 / 0 == 1)
print(10 < 20 or 10 / 0 == 1)

output

False
True

4. Assignment operator

  1. =usage of

=Indicates assignment. We have used this many times. Pay attention to the ==distinction.
=In addition to the basic usage, you can also assign values ​​to multiple variables at the same time.

chain assignment

a = b = 10

multiple assignment

a, b = 10, 20

Code example: Swap two variables

Basic writing method (similar to C writing method)

a = 10
b = 20
tmp = a
a = b
b = tmp

Based on multiple assignment

a = 10
b = 20
a, b = b, a
  1. compound assignment operator

Python also has some compound assignment operators. For example, += -= *= /= %=
where a += 1is equivalent to a = a + 1. The same is true for other compound assignment operators.

a = 10
a = a + 1
print(a)
b = 10
b += 1
print(b)

Note :

Like C / C++in , there is ++ --such an increment/decrement operator. PythonIn does not support this operation. If you need to use it, use it directly += 1or -= 1
++ --The biggest problem is that it is easy to not distinguish the difference between prefix and postfix. This syntax Pythonis in This was avoided during design to avoid such unintuitive and confusing syntax.

In addition to the above, there are some operators in Python, such as identity operator ( is, is not), member operator ( in, not in), bit operator ( & | ~ ^ << >>), etc.

Conditional statements

Use the if else keyword to express conditional statements in Python

if

if expression:
	do_something1
	do_something2
next_something

If the expression value is True, do_something1, do_something2, next_something will be executed.
If the expression value is False, only next_something will be executed, and do_something1, do_something2 will not be executed.

if - else

if expression:
	do_something1
else:
	do_something2

If expression value is True, do_something1 is executed.
If expression value is False, do_something2 is executed.

if - elif - else

if expression1:
	do_something1
elif expression2:
	do_something2
else:
	do_something3

If expression1 value is True, do_something1 is executed

If expression1 is False, and expression2 is True, do_something2 is executed.

If expression1 is False, and expression2 is False, do_something3 is executed.

Note: The way of writing conditional statements in Python is different from many programming languages.

The conditional expression after if, without (), uses: as the end. The
"statement block" to be executed after if / else hits the condition, is represented by indentation (usually 4 spaces or 1 tab), instead of { }
For multiple conditional branches, instead of writing else if, write elif.

Indentation and code blocks

A code block refers to a group of codes that are executed together.
In Python, indentation is used to represent code blocks. Different levels of indentation have different execution effects of the program.

Code 1

a = input("请输入一个整数: ")
if a == "1":
	print("hello")
	print("world")

Code 2

a = input("请输入一个整数: ")
if a == "1":
	print("hello")
print("world")

the difference

In code 1, print("world") has one level of indentation. This statement belongs to the code block within the if, which means that it will only be executed if the condition is true. If the condition is not true, it will not be executed. In code 2, print("world
" ) is not indented. This statement is code outside the if and does not belong to the code block inside the if. This means that the condition will be executed regardless of whether it is true or not. In addition, code blocks can also be nested inside the code block.

a = input("请输入第一个整数: ")
b = input("请输入第二个整数: ")
if a == "1":
	if b == "2":
		print("hello")
	print("world")
print("python")

In this code

print("hello") has two levels of indentation and belongs to the code block where the condition if b == "2" is true.
print("world") has one level of indentation and belongs to the code block where the condition of if a == "1" is true.
print("python") has no indentation. This statement will be executed regardless of whether the above two conditions are true.

The advantage of representing code blocks based on indentation is that programmers are forced to write clear indentations to clarify the relative relationship between codes. If the indentation is not written correctly, an error will be reported directly. Like C++ / Java Language, even if no indentation is written at all, the syntax will not report an error. The readability of the code is relatively poor. At the same time, the disadvantage is that if there are many indentation levels, it is easy to not distinguish which level a certain statement belongs to.

if a == 1:
	if b == 2:
		if c == 3:
			if d == 4:
				if e == 5:
					if f == 6:
						if g == 7:
							print("hello")
						print("1")
					print("2")

Therefore, there is the saying "Writing Python requires your own vernier caliper"

Empty statement pass

Example: Enter a number, if the number is 1, print hello

a = int(input("请输入一个整数:"))
if a == 1:
	print("hello")

It can also be written equivalently as

a = int(input("请输入一个整数:"))
if a != 1:
	pass
else:
	print("hello")

Pass represents an empty statement, which does not have any impact on the execution of the program. It just takes up a place to keep the Python syntax format in compliance with the requirements.

but cannot be written as

a = int(input("请输入一个整数:"))
if a != 1:

else:
	print("hello")

If it does not conform to Python syntax, an error will be reported directly.

loop statement

1. while loop

Basic syntax format

while 条件:
	循环体

If the condition is true, the loop body code is executed.
If the condition is false, the loop ends.

Example: Find 1! + 2! + 3! + 4! + 5!

num = 1
sum = 0
while num <= 5:
	factorResult = 1
	i = 1
	while i <= num:
		factorResult *= i
		i += 1
	sum += factorResult
	num += 1
print(sum)

This program uses double loops, that is, loops can also be included in loop statements.

2. for loop

Basic syntax format

for 循环变量 in 可迭代对象:
	循环体

Notice:

Python's for is different from other languages. There is no "initialization statement", "loop condition determination statement", "loop variable update statement", but a simpler so-called "iterable object", which refers to "containing multiple elements internally
. A special variable that can take out elements one by one."

Example 1: Print 1-10

for i in range(1, 11):
	print(i)

Using the range function, an iterable object can be generated. The generated range is [1, 11), that is, [1, 10]

Example 2: Print 2, 4, 6, 8, 10

for i in range(2, 12, 2):
	print(i)

Through the third parameter of range, you can specify the "step size" during iteration. That is, how many times should the loop variable be added at a time?

Example 3: Print 10-1

for i in range(10, 0, -1):
	print(i)

The step size of range can also be set to a negative number

Example 3: Find the sum of 1 - 100

sum = 0
for i in range(1, 101):
	sum += i
print(sum)

The usage of continnue and break is similar to that in C language and will not be explained here.

Guess you like

Origin blog.csdn.net/kingxzq/article/details/133022362
Recommended