stay python If you want to output some numbers, you can use range() Print
for example
for value inrange(1,5):
print(value)
1
2
3
4
When we output, we will output from 1 To 4 Four numbers of , But what we write is (1,5).
Although the input (1,5) But it will not be output to 5, Don't print 5, This is a common phenomenon in programming languages c It will also involve , If you need to print 1-5 Just output (1,6) That's all right. .
When we use range The output may not be what we expected , We can add or subtract one to the input .
meanwhile , If we only input the following numbers, such as range(6), At this point, the 0 Start to output ,0-5 For the output .
We want to put range() The result of is converted into a list , We need to use list()
classnumbers=list(range(1,6))
print(classnumbers)
[1,2,3,4,5]
We can set the third parameter , In order to give range() To specify the step size .
for instance range(1,11,2) The first number represents the starting position from 1 Start ,11 Is to 11 It's over ,2 It means every 2 Output one empty number .
numbers=list(range(1,11,2))
print(numbers)
[2,4,6,8,10]
Of course, from 2 Start from 3 Start , Or from 11 End from 22 end , You can specify the length of the interval .
We want one from 1-10 Square data of , We can use (**) Represents a power operation ,
squares=[]
for value in range(1,11):
square=value**2
squares.append(square)
print(squares)
[1,4,9,16,25,36,49,64,81]
If you want the code
squares=[]
for value in range(1,11):
squares.append(value=**)
print(squares)
[1,4,9,16,25,36,49,64,81]
To make things cleaner, we can put variables squares Put it directly into the formula .