Как работает цикл for в python

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in «if statements» and loops.

An «if statement» is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:  print(«b is greater than a»)

In this example we use two variables, a and b,
which are used as part of the if statement to test whether b is greater than a.
As a is 33, and b is 200,
we know that 200 is greater than 33, and so we print to screen that «b is greater than a».

The History of Python’s range() Function#

Although in Python 2 and in Python 3 may share a name, they are entirely different animals. In fact, in Python 3 is just a renamed version of a function that is called in Python 2.

Originally, both and produced numbers that could be iterated over with for-loops, but the former generated a list of those numbers all at once while the latter produced numbers lazily, meaning numbers were returned one at a time as they were needed.

Having huge lists hang around takes up memory, so it’s no surprise that replaced , name and all. You can read more about this decision and the vs background in PEP 3100.

Note: PEP stands for Python Enhancement Proposal. PEPs are documents that can cover a wide range of topics, including proposed new features, style, governance, and philosophy.

There are a ton of them. PEP 1 explains how they work and is a great place to start.

For the rest of this article, you’ll be using the function as it exists in Python 3.

Итерируемые объекты

Как было уже сказано, большинство контейнеров являются итерируемыми. Но в то же время множество других типов данных являются итерируемыми, например, файлы, сокеты и тому подобные. В то время как контейнеры обычно содержат конечное количество элементов, просто итерируемый объект может представлять источник бесконечных данных.

Итерируемым объектом является любой объект, который может предоставить итератор, который, в свою очередь, и возвращает отдельные элементы

На первый взгляд это звучит немного странновато, но тем не менее очень важно понимать разницу между интерируемым объектом и итератором. Рассмотрим пример:

Здесть — это итерируемый объект, в то время как и два отдельных экземпляра итератора, производящего значения из итерируемого объекта . Как видим, и сохраняют состояние между вызовами . В данном примере в качестве источника данных для итератора используется список, но это не является обязательным условием.

Часто, чтобы сократить объем кода, классы итерируемых объектов имплементируют сразу оба метода: и , при этом возвращает . Таким образом класс одновременно является и итерируемым и итератором самого себя. Однако, лучшей практикой всё же считается в качестве итератора возвращать отдельный объект.

Итак, когда выполняется следующий код:

вот что на самом деле происходит:

Если диассемблировать код, представленный выше, мы обнаружим вызов , который по сути является следствием вызова . Инструкция  является эквивалентом многократного вызова до тех пор, пока не будет возвращён последний элемент. Этого, правда, не видно в байт-коде из-за оптимизаций, вносимых интерпретатором.

Let’s Loop#

Before we dive into seeing how works, we need to take a look at how looping works. Looping is a . If you want to be a good programmer, mastering loops is among the first steps you need to take.

Here’s an example of a for-loop in Python:

The output looks like this:

As you can see, a for-loop enables you to execute a specific block of code however many times you want. In this case, we looped through a list of captains and printed each of their names.

Although Star Trek is great and everything, you may want to do more than simply loop through a list of captains. Sometimes, you just want to execute a block of code a specific number of times. Loops can help you do that!

Try the following code with numbers that are divisible by three:

The output of that loop will look like this:

That’s the output we wanted, so the loop got the job done adequately, but there is another way to get the same result by using .

Note: That last code example had some string formatting. To learn more on that topic, you can check out Python String Formatting Best Practices and Python 3’s f-Strings: An Improved String Formatting Syntax (Guide).

Now that you’re more familiar with loops, let’s see how you can use to simplify your life.

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the sequence itself. Following is a simple example −

Example

#!/usr/bin/python3

fruits = 
for index in range(len(fruits)):
   print ('Current fruit :', fruits)

print ("Good bye!")

Output

When the above code is executed, it produces the following result −

Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

Here, we took the assistance of the len() built-in function, which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over.

Recursion

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself («recurse»). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.

Example

Recursion Example

def tri_recursion(k):
 
if(k > 0):
   
result = k + tri_recursion(k — 1)
   
print(result)
 
else:
   
result = 0
 
return result
print(«\n\nRecursion Example Results»)
tri_recursion(6)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector