Как зациклить мой супер python код?
Всем привет.
как можно это зациклить? помогите плес;(
что бы каждый раз когда когда пользователь отвечает n/N его возвращало к строке then
и так по кругу, пока не будет ответ да.
не могу понять вообще, я смотрел примеры, но логику не улавливаю.
1 number = input(«Type your number here:»)
2 print(«your number is:»+ str(number))
3 yournumber = input(«Right number? (Y/N): «)
4 then = input(«Type your number again: «)
- Вопрос задан более года назад
- 3861 просмотр
- Вконтакте

- Вконтакте
Спасибо!:)
Видно мне нужно еще много почитать, потому что не понимаю как правильно применять команды и строить логику.
Потому что, в тот день как я написал пост об этом.
Я сделал такой вот код, он работает.
Случайно пришел к этому:)
И на вид он наверно слишком перегружен, не такой читаемый как ваш.
number = input(«Введите число: «)
print («Ваше число?» + str(number))
answer = input(«Ваше число верное?(Y/N): «)
while not answer == «Y»:
then = input(«Введите число еще раз:»)
print («Ваше число?» + then)
answer = input(«Ваше число верное?(Y/N): «)
if answer == «Y» or «y»:
print(«Программа закончена»)
# Loops
As one of the most basic functions in programming, loops are an important piece to nearly every programming language. Loops enable developers to set certain portions of their code to repeat through a number of loops which are referred to as iterations. This topic covers using multiple types of loops and applications of loops in Python.
# Break and Continue in Loops
# break statement
When a break statement executes inside a loop, control flow "breaks" out of the loop immediately:
The loop conditional will not be evaluated after the break statement is executed. Note that break statements are only allowed inside loops, syntactically. A break statement inside a function cannot be used to terminate loops that called that function.
Executing the following prints every digit until number 4 when the break statement is met and the loop stops:
break statements can also be used inside for loops, the other looping construct provided by Python:
Executing this loop now prints:
Note that 3 and 4 are not printed since the loop has ended.
(opens new window) , it does not execute when the loop is terminated through a break statement.
# continue statement
A continue statement will skip to the next iteration of the loop bypassing the rest of the current block but continuing the loop. As with break , continue can only appear inside loops:
Note that 2 and 4 aren’t printed, this is because continue goes to the next iteration instead of continuing on to print(i) when i == 2 or i == 4 .
# Nested Loops
break and continue only operate on a single level of loop. The following example will only break out of the inner for loop, not the outer while loop:
Python doesn’t have the ability to break out of multiple levels of loop at once — if this behavior is desired, refactoring one or more loops into a function and replacing break with return may be the way to go.
# Use return from within a function as a break
(opens new window) exits from a function, without executing the code that comes after it.
If you have a loop inside a function, using return from inside that loop is equivalent to having a break as the rest of the code of the loop is not executed (note that any code after the loop is not executed either):
If you have nested loops, the return statement will break all loops:
# For loops
for loops iterate over a collection of items, such as list or dict , and run a block of code with each element from the collection.
The above for loop iterates over a list of numbers.
Each iteration sets the value of i to the next element of the list. So first it will be 0 , then 1 , then 2 , etc. The output will be as follow:
range is a function that returns a series of numbers under an iterable form, thus it can be used in for loops:
gives the exact same result as the first for loop. Note that 5 is not printed as the range here is the first five numbers counting from 0 .
# Iterable objects and iterators
for loop can iterate on any iterable object which is an object which defines a __getitem__ or a __iter__ function. The __iter__ function returns an iterator, which is an object with a next function that is used to access the next element of the iterable.
# Iterating over lists
To iterate through a list you can use for :
This will print out the elements of the list:
The range function generates numbers which are also often used in a for loop.
The result will be a special range sequence type
(opens new window) in python >=3 and a list in python <=2. Both can be looped through using the for loop.
If you want to loop though both the elements of a list and have an index for the elements as well, you can use Python’s enumerate function:
enumerate will generate tuples, which are unpacked into index (an integer) and item (the actual value from the list). The above loop will print
Iterate over a list with value manipulation using map and lambda , i.e. apply lambda function on each element in the list:
NB: in Python 3.x map returns an iterator instead of a list so you in case you need a list you have to cast the result print(list(x)) (see http://stackoverflow.com/documentation/python/809/incompatibilities-between-python-2-and-python-3/8186/map)
# Loops with an "else" clause
The for and while compound statements (loops) can optionally have an else clause (in practice, this usage is fairly rare).
The else clause only executes after a for loop terminates by iterating to completion, or after a while loop terminates by its conditional expression becoming false.
The else clause does not execute if the loop terminates some other way (through a break statement or by raising an exception):
Most other programming languages lack this optional else clause of loops. The use of the keyword else in particular is often considered confusing.
The original concept for such a clause dates back to Donald Knuth and the meaning of the else keyword becomes clear if we rewrite a loop in terms of if statements and goto statements from earlier days before structured programming or from a lower-level assembly language.
is equivalent to:
These remain equivalent if we attach an else clause to each of them.
is equivalent to:
A for loop with an else clause can be understood the same way. Conceptually, there is a loop condition that remains True as long as the iterable object or sequence still has some remaining elements.
# Why would one use this strange construct?
The main use case for the for. else construct is a concise implementation of search as for instance:
To make the else in this construct less confusing one can think of it as "if not break" or "if not found".
Some discussions on this can be found in [Python-ideas] Summary of for. else threads
# Iterating over dictionaries
Considering the following dictionary:
To iterate through its keys, you can use:
This is equivalent to:
To iterate through its values, use:
To iterate through its keys and values, use:
Note that in Python 2, .keys() , .values() and .items() return a list object. If you simply need to iterate trough the result, you can use the equivalent .iterkeys() , .itervalues() and .iteritems() .
The difference between .keys() and .iterkeys() , .values() and .itervalues() , .items() and .iteritems() is that the iter* methods are generators. Thus, the elements within the dictionary are yielded one by one as they are evaluated. When a list object is returned, all of the elements are packed into a list and then returned for further evaluation.
Note also that in Python 3, Order of items printed in the above manner does not follow any order.
# The Pass Statement
pass is a null statement for when a statement is required by Python syntax (such as within the body of a for or while loop), but no action is required or desired by the programmer. This can be useful as a placeholder for code that is yet to be written.
In this example, nothing will happen. The for loop will complete without error, but no commands or code will be actioned. pass allows us to run our code successfully without having all commands and action fully implemented.
Similarly, pass can be used in while loops, as well as in selections and function definitions etc.
# While Loop
A while loop will cause the loop statements to be executed until the loop condition is falsey
(opens new window) . The following code will execute the loop statements a total of 4 times.
While the above loop can easily be translated into a more elegant for loop, while loops are useful for checking if some condition has been met. The following loop will continue to execute until myObject is ready.
while loops can also run without a condition by using numbers (complex or real) or True :
If the condition is always true the while loop will run forever (infinite loop) if it is not terminated by a break or return statement or an exception.
# Iterating different portion of a list with different step size
Suppose you have a long list of elements and you are only interested in every other element of the list. Perhaps you only want to examine the first or last elements, or a specific range of entries in your list. Python has strong indexing built-in capabilities. Here are some examples of how to achieve these scenarios.
Here’s a simple list that will be used throughout the examples:
# Iteration over the whole list
To iterate over each element in the list, a for loop like below can be used:
The for loop assigns s for each element of lst . This will print:
Often you need both the element and the index of that element. The enumerate keyword performs that task.
The index idx will start with zero and increment for each iteration, while the s will contain the element being processed. The previous snippet will output:
# Iterate over sub-list
If we want to iterate over a range (remembering that Python uses zero-based indexing), use the range keyword.
This would output:
The list may also be sliced. The following slice notation goes from element at index 1 to the end with a step of 2. The two for loops give the same result.
The above snippet outputs:
(opens new window) is a topic of its own.
# The "half loop" do-while
Unlike other languages, Python doesn’t have a do-until or a do-while construct (this will allow code to be executed once before the condition is tested). However, you can combine a while True with a break
(opens new window) to achieve the same purpose.
This will print:
# Looping and Unpacking
If you want to loop over a list of tuples for example:
instead of doing something like this:
or something like this:
You can simply do this:
This will also work for most types of iterables, not just tuples.
Цикл while в Python
Циклы используются для повторения выполнения определенного блока кода. Например, если нам нужно показать определенное сообщение 100 раз, то мы можем использовать цикл. Это простой пример, но с помощью циклов мы можем сделать многое.
На предыдущем уроке мы рассматривали цикл for в Python. Теперь мы узнаем о цикле while.
Цикл while в Python
Цикл while используется для выполнения блока кода до тех пор, пока не будет достигнуто определенное условие.
Синтаксис цикла while:
Сначала цикл while обрабатывает условие .
Если условие вычисляется как True , то выполняется код внутри цикла while.
Затем условие повторно обрабатывается. Этот процесс продолжается до тех пор, пока условие не станет False .
Как зациклить программу в питоне
Введение в Python
Часто возникают ситуации, в которых вам необходимо выполнить блок кода несколько раз. Как правило, команды выполняются одна вслед за другой, но существуют способы зациклить код. Во многих языках программирования для этой цели используются инструкции циклов. В Python существуют следующют два типа цикличных выражений:
- Цикл while
- Цикл for
Цикл while в Python:
Инструкция while в Python повторяет указанный блок кода до тех пор, пока указанное в цикле условие будет оставаться истинным.
Цикл while в Python записывается следующим образом:
При этом выражением может быть как одна так и несколько инструкций. Условием может быть любое истинное или ненулевое значение. Выражение будет повторяться, пока условие будет истинным.
Когда условие становится ложным интерпретатор переводит выполнение программы на строку, следующую за циклом. Рассмотрим следующий пример цикла while в Python:
Запустив код, вы увидите следующий результат:

Бесконечный цикл:
Цикл while становится бесконечным в случае, когда условие цикла никогда не становится ложным. Примером задачи для реализации которой необходим бесконечный цикл может быть, например, создание программы «Часы», которая бесконечно будет обновлять и отображать время. Однако, часто бесконечный цикл является ошибкой начинающего программиста, который забыл добавить изменение условия цикла. Например:
Не спешите запускать данный цикл, иначе ваша программа начнет бесконечное выполнение. Чтобы остановить выполнение такого скрипта — в shell нужно нажать Ctrl+C .
Цикл for в Python:
Цикл for в Python обладает способностью переберать элементы любого комплексного типа данных (например, строки или списка). В Python цикл for обладает следующим синтаксисом:
Переменной item присваивается значение первого элемента sequence, после чего выполняется statement. Затем переменной item присваивается следующее по порядку значение и так далее до тех пор, пока не будут перебраны все элементы sequence. Например:
Запустив код выше получим:

Перебор комплексных типов данных по индексам:
Другой способ прохода циклом for по комплексным типам данных является проход по индексам. Как вы помните, любой элемент последовательности можно получить по его индексу. Для генерации списка индексов воспользуемся встроенной функцией range(). Например:
В результате программа напечатает перечень дней недели.
Команда break в Python:
Команда break в Python прекращает выполнение цикла и переводит выполнение программы на строку следующую после цикла.
Команда break работает как в цикле while та и в цикле for. Например: