Python loops, judgments and functions

Source: Internet
Author: User

    • py for loop in Thon
  
 
  1. #for循环格式(类似Java中的foreach):for 标识符 in 列表名称 :
  2. >>> movies = ["movie1","movie2","movie3"]
  3. >>> for item in movies :
  4. print(item)
  5. movie1
  6. movie2
  7. movie3
The For loop in Python is similar to a foreach loop in Java, with a fixed format in comments where: for indicates the start of the loop, to appear before the identifier, and in the list to be looped separated from the identifier;: placed after the list name, indicating that the processing list code starts; The list processing code must be placed below the FOR loop and indented!!! When the For loop starts, Python assigns each value in the list to an identifier, which also means that the value of each loop identifier is different; The loop iterates until all the data in the list is processed.
    • A while loop in Python
  
 
  1. #while循环格式:while 循环条件 :
  2. >>> while count < len(movies) :
  3. print(movies[count])
  4. count = count + 1
  5. movie1
  6. movie2
  7. movie3
While loop has more conditional-judged statements than a for loop, you can customize the condition of the loop end
    • Python's judgment
If-else format
 
   
  
  1. if 满足某个条件 :
  2. 执行某些语句
  3. else :
  4. 执行某些语句
NOTE: The IF statement and the Else statement are finally added: and the code to be executed after if and else is indented
    • Functions of Python
  
 
  1. >>> new_movies = ["movie1","movie2","movie3",["movie4_1","movie4_2",["movie_4_3_1","movie_4_3_2"]],"movie5"]
  2. >>> def listItems(items) :
  3. for item in items :
  4. if isinstance(item,list) :
  5. listItems(item)
  6. else :
  7. print(item)
  8. >>> listItems(new_movies)
  9. movie1
  10. movie2
  11. movie3
  12. movie4_1
  13. movie4_2
  14. movie_4_3_1
  15. movie_4_3_2
  16. movie5



From for notes (Wiz)

Python loops, judgments and functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.