程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The essence of Python loop is that a piece of code is too lazy to write repeatedly

編輯:Python

# Python The essence of a loop is that a piece of code is too lazy to repeat

The concept of loops in programs is very easy to understand , A similar piece of code doesn't want to be repeated , Then let the program complete this operation, which is a loop . For example, from 1 Add to 100, If you go in turn, you'll find , The code is smelly and long , The best way to write it is to let the program accumulate in turn through loops .

for loop


for You can loop through the objects ( Also called iterative ) operation , Each traversal can process the elements accordingly , As of this blog , Ergodic ( iteration ) The object is currently of list type .

for The syntax of the loop is as follows :

for item in my_list( Iteratable object ):
for Code block 

In the above code item That's what you get from each loop , You can iterate over each value in the object .

One of the most important concepts here is iteratable objects (iterable object), English you also need to remember , We often use .

Iteratable objects contain many types , There are lists, for example 、 Tuples 、 Dictionaries and collections , In addition to the list, the rest will be learned later .

for Basic use of recycling

After learning the list , about for Loop you need to build a basic concept that is for The loop gets each item in the list in turn , Attention is to get... In turn .

When writing code with if You should also pay attention to indenting .

Next through for Cycle through each item in the list .

my_list = ["apple","orange","banana","pear"]
for item in my_list:
print(item)

for As long as the indent is consistent in the loop statement , It can be made up of multiple lines of code , for example :

my_list = ["apple","orange","banana","pear"]
for item in my_list:
print(" Output a fruit ")
print(item)

for A nested loop if Judgment statement

for There can be multiple pieces of code in the loop , In fact, it can be nested if Of the statement , You can refer to :

my_list = [1,2,3,4,5,6,7]
for item in my_list:
if item >3:
print(" The element ratio 3 Big ")
print(" The element is :",item)

The above code can judge when the elements in the list are greater than 3 When , Output if What's in the sentence , You can try to complete else sentence .

range function


stay Python Through range Function generates an arithmetic sequence , This arithmetic sequence is an iterative object , If you use type The function looks at the object type and finds range The object type generated by the function is range, The specific code is as follows :

my_range = range(4)
print(my_range)
print(type(my_range))

The output is :

range(0, 4)
<class 'range'>

You can see range The function generates a range object , In the above range function , The grammar format is range(4), The general syntax format is as follows :

range(start,stop,step)

Only one stop Are mandatory ,step The default value is 1, If omitted start Default means from 0 To stop-1. Specific operation of 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)

The output is as follows , We all use for The output of a loop statement , adopt list Functions can also .

0
1
2
3
##########
1
2
3
##########
1
3
5

range Function is a common function in subsequent programming , In many scenarios, it is necessary to generate an isochromatic sequence , So please grasp this function firmly . The so-called grasp means that now you need to type a good code .

for Cycle to supplement knowledge


for A nested loop

A block of code in one loop is nested in another loop called nesting of loops , When you write loop nested code, you need to pay attention to .

The indentation of the code block must pay attention to , Check which code block belongs to for loop

It's a classic case , I spent a lot of energy here when I was studying with the eraser , I didn't understand until the final exam , At the beginning stage, this should be a more difficult procedure to understand , adopt 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(" ")

After running the code, it is shown in the figure below :

This program contains for loop ,for A nested loop , Format output string , There are different levels of indentation .

When the loop is executed , You can understand that first , The outer circle turns 1 All over , Inner loop run 1 circle .

The meaning of this sentence has just come to this stage , It's hard to understand. , What do you mean ? Many textbooks may write flow charts , Tell you how to get to the branch , How can we go there? . It's hard , In the eyes of the eraser, it's an epiphany .

Mark two lines in the code above .

The outer loop is the top cycle , It circulates once , The cycle inside , It's including variables j the for loop , To cycle 1 circle , It's all over again .

That's the conclusion .

  • When i = 1 When ,j from 1 All the way to 10, And then output a print(" ");
  • When i=2 When ,i Or from 1 Change to 10, And then output a print(" ");
  • When i=3 When ..., And then output a print(" ")
  • i=4 When , And then output a print(" ")

When i=9 When , The inner loop goes through the last loop . All the cycles are finished , End the program .

Special note print When the function outputs , By default, it will bring a \n, I've learned the previous course , The symbol stands for line break . If you want to get rid of it print The line break that comes with the function , Need to use end Parameters , namely print(" What to output ",end=" ").

don 't worry , Although I have explained the process in detail , The students who can understand will realize it on the spot , Can't understand or can't understand , This place is really hard ( Is it difficult? ?), But don't worry , As you write more and more code , Slowly you will , Can't write this does not affect the follow-up study , In a word, you can understand it by writing it twice more .

break End cycle

Stop the loop. That's how you understand it , When a condition is met , I don't want to cycle , This is it. break Usage scenarios of , When a certain condition is met, it must be used if sentence .

for example , When you loop through a list , If a value greater than 3 The number of , So stop the cycle , The code is as follows :

for i in range(1,10):
if i > 3 :
print(" Appear larger than 3 The number of , End cycle ")
break

continue Continue to cycle

continue And break similar , When certain conditions are met , What to do , It's just that the program encounters continue keyword , It's not terminating the loop , It's going into the next cycle , No matter what work remains of the current cycle , Don't do the .

for i in range(0,5):
if i > 3 :
continue
print(" The current figure is :",i)

In the above code for There is a loop if Judge , When i&gt;3 When , That is, the number in the list is greater than 3, Go directly to the next cycle , This leads to one thing that is found in the loop than 3 After the big numbers ,print It won't be executed , So running the code will find the following results , Only display less than or equal to 3 The number of .

 The current figure is : 0
The current figure is : 1
The current figure is : 2
The current figure is : 3

for ... else loop

for ... else Cycle is Python A specific grammatical structure in , In colloquialism, it is to be for Execute the loop when it is finished else. Most of the time, the vernacular can understand , You can use it to describe what this is for , This knowledge point has already been mastered , There's no need to be wordy at the beginning of learning .

For example, test the following code :

for i in range(0,5):
if i > 3 :
continue
print(" The current figure is :",i)
else:
print(" No matter what's on it for What does the cycle do , I'll do it all once ")

In fact, there is a knowledge point that needs to be added , It's code pairing , What is pairing ,if and else It's just a couple , Why is there such a saying , See the following code :

if Conditions :
pass
if Conditions :
pass
else:
pass

pass Indicates occupancy , stay Python The keyword is supported in , But I haven't figured out what code to write here , Let's get a word and hold it .

There are two in the code above if And a else, Be sure to pay attention to ,else And recent if It's a pair. , Uppermost if It's just an ordinary if. This kind of problem is more interesting when the code is nested .

if Conditions :
pass
if Conditions :
if Conditions :
pass
else:
pass
else:
pass

According to the indent relation , You need to find a good if And else Which pair is very important . If you can't see it with the naked eye, you actually tap the keyboard .

Synthesize what you just learned , Now you know how to deal with for else Have you paired up yet ?

while loop


while So is the cycle Python A kind of cyclic grammar in , But this kind of cycle can easily become a dead circle , It's going to cycle until the computer crashes , Dead loop has its disadvantages, but it also has its application scenarios , We will also learn from it later .

while The syntax of the loop is as follows :

while Conditions :
Code block 

In the format Conditions It's very important , After the conditional operation, we need to judge whether it is true or not , It's true (True) To enter while Code block in the running program .

while The classic application of loops

while Besides grammatical structure and for There are differences in the cycle , A lot of places are basically the same , Then finish a pass while A classic example of loop implementation - Guess the number , This is barely a game .

# The final answer is 12, You can actually use random numbers
answer = 12
# The number the user guessed
guess = 0
# Condition is Judge guess It's not equal to answer
while guess!=answer:
guess = int(input(" Please enter a 1~100 Number between :"))
if guess > answer:
print(" Your numbers are big ")
elif guess < answer:
print(" Your numbers are small ")
else:
print(" Congratulations, right , The number is 12 ")

The case is small , But it integrates a lot of what I've learned before , for example input Get user input ,int Convert string to integer ,if...elif...else Sentence, etc , The simpler the knowledge points, the more frequent they will appear in the follow-up courses , Be sure to pay attention to the basics .

while Other instructions

while The use of cycles and for The cycle is basically the same , Many times you can even think of it as one thing . because break And continue The same applies to while loop , There is no need to repeat the knowledge points here , When we go into complex coding later , Nature can master .

The summary of this blog


Cycles also belong to Python The basic grammatical structure of , After branching and looping , In addition to the most basic order of execution , That's enough for programming to do a lot of things , You can also think about , Is there any other way to solve the problem in the real world , If the answer is No, , In fact, program development is just about this .

But I'm a rookie too , Now look at this knowledge so easy ~, But the first time I studied , Or sent out what this is , ... , How to realize the soul problem , Don't worry too much , Eyes stop , By hand , Just tap the keyboard .

There is no difficulty in programming , The difficulty is the speed of pressing the keyboard .

This article talks about range function , But Charlie omitted The list generator part is a bit difficult to learn at this stage , It will be complemented in later courses .

The last bowl of poisonous chicken soup

Without the fullness of a purse , There is no peace of mind . O(∩_∩)O ha-ha ~


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved