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

0 basic learning python (7)

編輯:Python

Before we learn python You may need a thing to repeat the operation , Some may require a lot of duplicate code , It may be necessary to for To loop code .

###  for example

classnumbers=['zhang','wang','su','meng']
for classnumber in classnumbers:
print(classnumber)
zhang
wang
su
meng

We set up a list to write the names of our classmates in the list , Then we set a correlation quantity classnumber, Use for Cycle through , Finally, output the correlation quantity classnumber,python Will be from the list classnumbers Repeated extraction of elements from , The final output is all the names in the list .

Of course, if you want to add more operations to the loop .

for example :

classnumbers=['zhang','wang','su']
for calssnumber in classnumbers:
print (f"{classnumber.title()},that is a good guy
Zhang,that is a good guy
Wang,that is a good guy
Su,that is a good guy 

When we finish for After the cycle , Want to do something , Indent can be cancelled , Code without indentation can only be executed once

classnumbers=['zhang','wang','su']
for calssnumber in classnumbers:
print (f"{classnumber.title()},that is a good guy
print("they are good boys")
Zhang,that is a good guy
Wang,that is a good guy
Su,that is a good guy
they are good boys

When we use for When looping, we need to pay attention to indentation , We can use tab Indent , If we forget what we can reach python Unable to run , Of course, if you make extra indentation , It will not work .

The most important thing in the cycle is :, When you finish typing a sentence for Remember to add... After the cycle :, To tell python The next line is the first line of the loop . I often forget , Sometimes, after looking for the problem for a long time, I find it when I rewrite it , Turned out to be : Forget the ,: It's not easy to find out that you forget .


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