The point of learning Python is to let the snowball roll when you learn to program ideas.

Completed articles

The title link
1. This is the right way to start learning Python Juejin. Cn/post / 691636…
2. Learn data types and input and output functions without barriers, and snowball into Python Juejin. Cn/post / 691668…
3. No programming without twists, learn Python by snowballing Juejin. Cn/post / 691711…
4. Learn Python halfway through the list Juejin. Cn/post / 691744…

This series of articles will be completed before the Spring Festival of 2021, welcome to follow, like, comment -- dream eraser

5. The nature of Python loops is that a piece of code is too lazy to repeat itself

The concept of a loop in a program is very easy to understand. A similar piece of code does not want to be written repeatedly, and then the program to complete the operation is a loop. For example, if you increment from 1 to 100, if you increment in sequence, you’ll find that the code is long and stinky, and the best way to write it is to loop through it.

5.1 a for loop

The for loop iterates over (also called iterating) the elements of an object. Each iteration does something to the elements. As of this blog, iterable objects are currently of the list type.

The syntax for the for loop is as follows:

for item inMy_list (iterable):forThe code blockCopy the code

The item in the above code is the object that we get each time we loop through it. We iterate over each value in the object.

One of the most important concepts here is the iterable object, which you’ll need to remember in English and use a lot later.

There are many types of iterables, such as lists, tuples, dictionaries, and collections, but we’ll learn more about lists later.

5.1.1 The For loop is basically used

So once you look at lists, one of the basic things you need to establish about the for loop is that the for loop gets each item in the list in turn, in turn.

Write code with the same attention to indentation as if statements.

Next, print each item in the list through a for loop.

my_list = ["apple"."orange"."banana"."pear"]
for item in my_list:
    print(item)
Copy the code

A for loop can consist of multiple lines of code as long as the indentation is consistent, for example:

my_list = ["apple"."orange"."banana"."pear"]
for item in my_list:
	print("Export a fruit")
    print(item)
Copy the code

5.1.2 For loop nested if statement

A for loop can contain multiple pieces of code, which can be nested with an if statement.

my_list = [1.2.3.4.5.6.7]
for item in my_list:
    if item >3:
        print("This element is greater than 3.")
        print(The element is:,item)
Copy the code

If the list is greater than 3, print the content of the if statement. You can try to complete the else statement.

5.2 range function

In Python, you can generate an arithmetic sequence using the range function. This arithmetic sequence is an iterable. If you use the type function to check the object type, you will find that the type of the object generated by the range function is range.

my_range = range(4)
print(my_range)
print(type(my_range))
Copy the code

The output is:

range(0, 4)
<class 'range'>
Copy the code

It can be seen that the range function generates a range object. The range function is used above, and the syntax format is range(4). The general syntax format is as follows:

range(start,stop,step)
Copy the code

The value of step is 1 by default. If start is omitted, the value ranges from 0 to stop-1 by default. Specific run the following code can be clear.

my_range1 = range(4)
for i in my_range1:
    print(i)

print("#"*10)
my_range2 = range(1.4)
for i in my_range2:
    print(i)

print("#"*10)
my_range3 = range(1.6.2)
for i in my_range3:
    print(i)
Copy the code

The output is as follows, using either a for loop or a list function.

0
1
2
3
# # # # # # # # # #
1
2
3
# # # # # # # # # #
1
3
5
Copy the code

Range function is a common function in subsequent programming, and it is needed to generate an arithmetic sequence in many scenarios, so please firmly grasp this function. By mastering, I mean now you need to type a good dozen codes.

5.3 Supplementary knowledge for loop

5.3.1 Nesting for loops

The nesting of code blocks in one loop within another is called nesting of loops, and you need to be careful when writing nested code for loops.

Indent blocks carefully, and check which for loop the block belongs to

Parsing is a classic case, when eraser learning here waste a lot of effort, until the final exam did not understand, the entry stage this should be more difficult to understand the program, through Python output a multiplication table.

for i in range(1.10) :for j in range(1.10) :print("%d * %d = %3d "%(i,j,i*j),end="")
    print("")
Copy the code

After the code runs, it looks like the following:

This program includes for loops, nesting for loops, formatting output strings, and different levels of indentation.

So when you do a loop, you can think of it this way: the outer loop goes once, the inner loop goes once.

The meaning of this sentence is difficult to understand at this stage of learning. What does it mean? A lot of books will probably have flowcharts that show you where the branches go, where the branches go. It was a struggle, an Epiphany from the eraser’s point of view.

Mark two lines in the above code.

The outer loop is the top loop, it goes through once, and the inner loop, the for loop that contains the variable j, goes through once, so it goes through all of them. That’s the conclusion.

  • When I is equal to 1, j goes from 1 to 10, and then it prints one moreprint(" ");
  • When I is equal to 2, I still has to go from 1 to 10, and then output one moreprint(" ");
  • When I =3… And then output oneprint(" ")
  • At I =4, and then I print oneprint(" ")

When I is equal to 9, the inner loop completes the last loop. All loops are completed, ending the program.

In particular, the print function is printed with a \n symbol by default. As we learned in the previous lesson, this symbol represents a newline. If you want to remove the newline from print, use the end argument: print(” to print “,end=” “).

Rest assured, although I detailed said a process, can understand the students on the spot to understand, do not understand or do not understand, this place is really difficult (difficult?) But don't worry, as you write more and more code, you'll get better at it, and it won't affect the rest of your study, so just write it twice.

5.3.2 break Terminates the loop

So that’s the way you think about it, I don’t want to loop when some condition is met, that’s how break is used, when some condition is met it’s definitely using an if statement.

For example, if a number greater than 3 appears while iterating through a list, the loop is terminated as follows:

for i in range(1.10) :if i > 3 :
        print("If a number greater than 3 occurs, the loop is terminated.")
        break
Copy the code

5.3.3 continue Continue a loop

“Continue” is similar to “break” in that it is something to do when a condition is met, except that when the program hits the “continue” keyword, instead of terminating the loop, it enters the next loop, regardless of what work is left in the current loop.

for i in range(0.5) :if i > 3 :
        continue
    print("The current number is:",i)
Copy the code

In the above code, there is an if judgment in the for loop. When I >3, that is, the number in the list is greater than 3, and the next loop is directly entered, which leads to one thing: print will not execute after finding a number greater than 3 in the loop, so running the code will find the following result: Only numbers less than or equal to 3 are displayed.

The current number is 0. The current number is 1. The current number is 2Copy the code

5.3.4 the for… The else cycle

for … Else loops are a particular syntax construct in Python, which basically means to execute else when the for loop is finished executing. A lot of times the plain English can understand, you can describe clearly what this is to do, this knowledge point has actually mastered, the beginning stage does not need to be literal.

For example, test the following code:

for i in range(0.5) :if i > 3 :
        continue

    print("The current number is:",i)
else:
    print("Whatever the for loop above does, I'm going to execute it once.")
Copy the code

If and else is a pair. If and else is a pair.

ifCondition:pass
ifCondition:pass
else:
	pass
Copy the code

Pass is a placeholder. This keyword is supported in Python, but we haven’t figured out what code to write here.

The code above shows two ifs and an else. It is important to note that the else is a pair of the nearest if, and the uppermost if is a normal if. This problem is even more interesting when code is nested.

ifCondition:pass
ifCondition:ifCondition:pass
	else:
		pass
else:
	pass
Copy the code

So depending on the indentation, it’s really important that you find an if versus an else pair. The naked eye can not see the actual keyboard typing.

So based on what we just learned, do you now know how to pair for else?

5.4 the while loop

The while loop is also a loop syntax in Python, but it’s very easy to go into an infinite loop, just keep going until the computer crashes. It’s bad but it also has applications, as we’ll see later.

The syntax for the while loop is as follows:

whileCondition: code blockCopy the code

The condition is very important in the format. After the condition operation, it needs to check whether it is True or false. If it is True, it will enter the code block in the while to run the program.

5.4.1 Classic application of the while loop

The while loop is basically the same except that it has a different syntax from the for loop. Next, we finish a classic case of guessing numbers, which is a game of sorts.

# The final answer is 12, actually can use random number
answer = 12
# the number the user guessed
guess = 0
A. guess B. answer C. guess D. answer
whileguess! =answer: guess =int(input(Please enter a number between 1 and 100:))
    if guess > answer:
        print("Your number is too high.")
    elif guess < answer:
        print("Your number is low.")
    else:
        print("Congratulations, the number is 12.")
Copy the code

This case is small, but it incorporates a lot of what we’ve learned before, such as input getting user input, int converting a string to an integer, if… elif… Else statements and things like that, the simpler things are going to be the more frequent they are going to be in the rest of the course, so make sure that the basics are the most important.

5.4.2 while other instructions

The while loop is basically the same as the for loop, and in many cases you can even think of it as the same. Since the break and continue statements also apply to the while loop, there is no need to repeat the knowledge points here, which can be mastered later when entering complex coding.

5.5 Summary of this blog

Circulation also belong to the basic grammatical structure of the Python, branch and cycle after the study, combined with the basic order, that is enough for programming to complete many tasks, you can see, the real world and there is no other way to solve the problem, if the answer is no, program development would be that much actually.

But I also come from the novice, now look at these knowledge so easy ~, but the first time to learn, or issued this is what, what is going on, how to achieve the soul problem, do not worry too much, eyes stop, manual up, knock a knock on the keyboard can.

Programming is not difficult, the difficulty is the speed of the keyboard.

This article covers the range function, but the eraser omitted the list generator part because it is a bit difficult to learn at this stage and will be filled in later in the course.

The last bowl of chicken soup

Without the fullness of the purse, there is no peace of mind. O(∩_∩)O haha ~ 👗👗

💎 💎 💎 💎 💎 💎 💎 💎 💎 💎 💎


Today is the 4/100th day of continuous writing. If you have ideas or techniques you’d like to share, feel free to leave them in the comments section.