当前位置:   article > 正文

Learn the basics of Python 3-Chapter 4:Loops

Learn the basics of Python 3-Chapter 4:Loops

1.What are Loops?

Loops In programming, this process of using an initialization, repetitions, and an ending condition is called a loop.In a loop, we perform a process of iteration (repeating tasks).

 2.Why Loops?

If we only use print(), our program might look like this:

Using 10 print() statements, print out: "This can be so much easier with loops!".

  1. #Write 10 print() statements below!
  2. print("This can be so much easier with loops!")
  3. print("This can be so much easier with loops!")
  4. print("This can be so much easier with loops!")
  5. print("This can be so much easier with loops!")
  6. print("This can be so much easier with loops!")
  7. print("This can be so much easier with loops!")
  8. print("This can be so much easier with loops!")
  9. print("This can be so much easier with loops!")
  10. print("This can be so much easier with loops!")
  11. print("This can be so much easier with loops!")

 3.For Loops: Introduction

let’s start with your first type of loop, a for loop, a type of definite iteration.

In a for loop, we will know in advance how many times the loop will need to iterate because we will be working on a collection with a predefined length. 

Before we work with any collection, let’s examine the general structure of a for loop:

for <temporary variable> in <collection>:
  <action>

Let’s break down each of these components:

  1. A for keyword indicates the start of a for loop.

  2. A <temporary variable> that is used to represent the value of the element in the collection the loop is currently on.

  3. An in keyword separates the temporary variable from the collection used for iteration.

  4. A <collection> to loop over. In our examples, we will be using a list.

  5. An <action> to do anything on each iteration of the loop.

  1. #Write a for loop that prints each sport in the list sport_games.
  2. board_games = ["Settlers of Catan", "Carcassone", "Power Grid", "Agricola", "Scrabble"]
  3. sport_games = ["football", "hockey", "baseball", "cricket"]
  4. for game in board_games:
  5. print(game)
  6. for game in sport_games:
  7. print(game)

4.For Loops: Using Range

To create arbitrary collections of any length, we can pair our for loops with the trusty Python built-in function range().

  1. promise = "I will finish the python loops module!"
  2. for temp in range(5):
  3. print(promise)

 5.While Loops: Introduction

A while loop performs a set of instructions as long as a given condition is true.

  1. # While Loop Walkthrough
  2. count = 0
  3. print("Starting While Loop")
  4. while count <= 3:
  5. # Loop Body
  6. # Print if the condition is still true
  7. print("Loop Iteration - count <= 3 is still true")
  8. # Print the current value of count
  9. print("Count is currently " + str(count))
  10. # Increment count
  11. count += 1
  12. print(" ----- ")
  13. print("While Loop ended")
  14. # Your code below:
  15. countdown = 10
  16. while countdown >= 0:
  17. print(countdown)
  18. countdown -= 1
  19. print("We have liftoff!")

 6.While Loops: Lists

A while loop isn’t only good for counting! Similar to how we saw for loops working with lists, we can use while loops to iterate through a list as well.

  1. python_topics = ["variables", "control flow", "loops", "modules", "classes"]
  2. length = len(python_topics)
  3. index = 0
  4. while index < length:
  5. print("I am learning about " + python_topics[index])
  6. index += 1

 7.Infinite Loops

A loop that never terminates is called an infinite loop. These are very dangerous for our code because they will make our program run forever and thus consume all of your computer’s resources.

  1. students_period_A = ["Alex", "Briana", "Cheri", "Daniele"]
  2. students_period_B = ["Dora", "Minerva", "Alexa", "Obie"]
  3. for student in students_period_A:
  4. students_period_A.append(student)
  5. print(student)

 8.Loop Control: Break

When the program hits a break statement it immediately terminates a loop. 

  1. dog_breeds_available_for_adoption = ["french_bulldog", "dalmatian", "shihtzu", "poodle", "collie"]
  2. dog_breed_I_want = "dalmatian"
  3. for dog_breed in dog_breeds_available_for_adoption:
  4. print(dog_breed)
  5. if dog_breed == dog_breed_I_want:
  6. print("They have the dog I want!")
  7. break

9.Loop Control: Continue

What if we want to print out all of the numbers in a list, but only if they are positive integers. We can use another common loop control statement called continue

  1. ages = [12, 38, 34, 26, 21, 19, 67, 41, 17]
  2. for age in ages:
  3. if age < 21:
  4. continue
  5. print(age)

 10.Nested Loops

Loops can be nested in Python, as they can with other programming languages. We will find certain situations that require nested loops.

  1. sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]
  2. scoops_sold = 0
  3. for location in sales_data:
  4. for data in location:
  5. scoops_sold += data
  6. print(scoops_sold)

11.List Comprehensions: Introduction

 new_list = [<expression> for <element> in <collection>]

  1. grades = [90, 88, 62, 76, 74, 89, 48, 57]
  2. scaled_grades = [grade + 10 for grade in grades]
  3. print(scaled_grades)

12.List Comprehensions: Conditionals

numbers = [2, -1, 79, 33, -45]
no_if   = [num * 2 for num in numbers]
if_only = [num * 2 for num in numbers if num < 0]
if_else = [num * 2 if num < 0 else num * 3 for num in numbers]

  1. heights = [161, 164, 156, 144, 158, 170, 163, 163, 157]
  2. can_ride_coaster = [ height for height in heights if height > 161]
  3. print(can_ride_coaster)

Learn the basics of Python 3-Code Challenges:Loops
Learn the basics of Python 3-Code Challenges:Loops(Advanced)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43122
推荐阅读
相关标签
  

闽ICP备14008679号