0% found this document useful (0 votes)
2 views

Python Tutorial_ While Loops

The document provides an overview of loops in Python, detailing three types: count-controlled, condition-controlled, and collection-controlled loops. It explains the structure and function of while and for loops, including their use in reading standard input and handling conditions. Additionally, it discusses the optional else part of while loops and the use of break and continue statements for loop control.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Tutorial_ While Loops

The document provides an overview of loops in Python, detailing three types: count-controlled, condition-controlled, and collection-controlled loops. It explains the structure and function of while and for loops, including their use in reading standard input and handling conditions. Additionally, it discusses the optional else part of while loops and the use of break and continue statements for loop control.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Conditional Statements


Next Chapter: For Loops

Loops

General Structure of a Loop


Follow Bernd Klein,
the author of this
Many algorithms make it necessary for a programming language to have a construct which makes it
website, at Google+:
possible to carry out a sequence of statements repeatedly. The code within the loop, i.e. the code
Bernd Klein on
carried out repeatedly, is called the body of the loop.
Google
Python 3 Essentially, there are three different kinds of loops:
Bernd Klein on
Tutorial Facebook
Count-controlled loops
The Origins of A construction for repeating a loop a certain number of times. An example of this kind of loop is
Python the for-loop of the programming language C:
for (i=0; i <= n; i++) Search this website:
Starting with
Python doesn't know this kind of loop.
Python: The
Condition-controlled loop Go
Interactive Shell
A loop will be repeated until a given condition changes, i.e. changes from True to False or from
Executing a False to True, depending on the kind of loop. There are while loops and do while loops with this This topic in German
Script behaviour. / Deutsche
Indentation Collection-controlled loop Übersetzung:
Data Types and This is a special construct which allow looping through the elements of a "collection", which can Schleifen
Variables be an array, list or other ordered sequence. Like the for loop of the bash shell (e.g. for i in *, do
Operators echo $i; done) or the foreach loop of Perl. Python 3
Sequential Data
Types: Lists and Python supplies two different kinds of loops: the while This is a tutorial in
Strings loop and the for loop, which correspond to the Python3, but this
List condition-controlled loop and collection-controlled loop. chapter of our course
Manipulations is available in a
Most loops contain a counter or more generally version for Python
Shallow and
variables, which change their values in the course of 2.x as well: While
Deep Copy
calculation. These variables have to be initialized before Loops in Python 2.x
Dictionaries
the loop is started. The counter or other variables,
Sets and Frozen
which can be altered in the body of the loop, are Training Classes
Sets contained in the condition. Before the body of the loop
An Extensive is executed, the condition is evaluated. If it evaluates to This website aims at
Example Using False, the while loop is finished. This means that the providing you with
Sets program flow will continue with the first statement after educational material
input via the the while statement, i.e. on the same indentation level suitable for self-
keyboard as the while loop. If the condition is evaluated to True, the body, - the indented block below the line learning.
Conditional with "while" - gets executed. After the body is finished, the condition will be evaluated again. The Nevertheless, it is
body of the loop will be executed as long as the condition yields True. faster and more
Statements
efficient to attend a
Loops, while
"real" Python course
Loop
in a classroom, with
For Loops A Simple Example with a While Loop an experienced
Difference trainer. So why not
between It's best to illustrate the operating principle of a loop with a simple Python example. The following attend one of the live
interators und small script calculates the sum of the numbers from 1 to 100. We will later introduce a more elegant Python courses
Iterables way to do it.
Output with Print
#!/usr/bin/env python3
Formatted output
with string n = 100
modulo and the
format method s = 0
counter = 1
Functions
while counter <= n:
Recursion and s = s + counter
Recursive counter += 1
Functions
print("Sum of 1 until %d: %d" % (n,s))
Parameter
Passing in in Strasbourg, Paris,
Functions London, Berlin,
Namespaces Munich, Hamburg,
Using a while Loop for Reading Standard Input
Global and Local Frankfurt, or Lake
Constance by Bernd
Variables Before we go on with the while loop, we want to introduce some fundamental things on standard input and standard output. Normally, the keyboard serves as the standard input. The standard output is usually the Klein, the author of
Decorators terminal or console where the script had been started, which prints the output. A script is supposed to send its error messages to the standard error. this tutorial?
Memoization with Python has these three channels as well:
Decorators
standard input
Read and Write In-house
standard output
Files Training
standard error
Modular Courses
Programming They are contained in the module sys. Their names are:
and Modules If you like it, we will
sys.stdin
Packages in come to your
sys.stdout
Python company or institute
sys.stderror
Regular and provide a special
Expressions . training for your
employees, as we've
Regular
The following script shows how to read with a while loop character by character from standard input (keyboard). done it many times in
Expressions,
Amsterdam (The
Advanced import sys Netherlands), Berlin
Lambda (Germany), Bern
Operator, Filter, text = "" (Switzerland), Basel
Reduce and Map while 1: (Switzerland), Zurich
c = sys.stdin.read(1)
List (Switzerland),
text = text + c
Comprehension if c == '\n': Frankfurt (Germany),
break Locarno
Iterators and
(Switzerland), Den
Generators
print("Input: %s" % text) Haag (The Hague),
Exception Hamburg, Munich
Handling Though it's possible to read input like this, usually the function input() is used. (Germany),
Tests, DocTests, Bucharest (Romania),
UnitTests >>> name = input("What's your name?\n") Toronto (Canada),
What's your name?
Object Oriented Edmonton (Canada),
Tux
Programming >>> print(name) and many other
Class and Tux cities. We do training
>>> courses in England,
Instance
Switzerland,
Attributes
Liechtenstein,
Properties vs. The else Part Austria, Germany,
getters and France, Belgium, the
setters Similar to the if statement, the while loop of Python has also an optional else part. This is an unfamiliar construct for many programmers of traditional programming Netherlands,
Inheritance languages. Luxembourg,
Multiple The statements in the else part are executed, when the condition is not fulfilled anymore. Some might ask themselves now, where the possible benefit of this extra Romania, UK, Italy,
branch is. If the statements of the additional else part were placed right after the while loop without an else, they would have been executed anyway, wouldn't they. Spain and other
Inheritance
We need to understand a new language construct, i.e. the break statement, to obtain a benefit from the additional else branch of the while loop. locations in Europe
Magic Methods
The general syntax of a while loop looks like this: and in Canada.
and Operator
Overloading This way you will get
OOP, Inheritance while condition: a perfect training up
Example statement_1 to your needs and it
...
Slots will be extremely cost
statement_n
Classes and else: efficient as well.
Class Creation statement_1
Road to ... Contact us so we can
statement_n find the ideal course
Metaclasses
to meet your needs.
Metaclasses
Metaclass Use Premature Termination of a while Loop
Case: Count
Skilled Python
Function Calls So far, a while loop only ends, if the condition in the loop head is fulfilled. With the help of a break statement a while
loop can be left prematurely, i.e. as soon as the control flow of the program comes to a break inside of a while loop
Programmers
Abstract Classes
(or other loops) the loop will be immediately left. "break" shouldn't be confused with the continue statement.
"continue" stops the current iteration of the loop and starts the next iteration by checking the condition. You are looking for
Now comes the crucial point: If a loop is left by break, the else part is not executed. experienced Python
Endless Loops developers or
This behaviour will be illustrated in the following example, a little guessing number game. A human player has to programmers? We
guess a number between a range of 1 to n. The player inputs his guess. The program informs the player, if this can help you, please
number is larger, smaller or equal to the secret number, i.e. the number which the program has randomly created. If contact us.
the player wants to gives up, he or she can input a 0 or a negative number.
Hint: The program needs to create a random number. Therefore it's necessary to include the module "random". Quote of the
Day:
import random
An infinite loop, or a
n = 20
continuous loop, is a "If programmers
to_be_guessed = int(n * random.random()) + 1
sequence of guess = 0 deserve to be
statements in a while guess != to_be_guessed: rewarded for creating
computer program guess = int(input("New number: ")) innovative programs,
which loops if guess > 0: by the same token
endlessly. if guess > to_be_guessed: they deserve to be
print("Number too large") punished if they
elif guess < to_be_guessed: restrict the use of
print("Number too small")
these programs. "
Loops in Music else:
print("Sorry that you're giving up!") (Richard Stallmann)
break
In electronic music, a
else:
loop is a sample print("Congratulation. You made it!")
which is repeated
continuously. Loops
may be created by The output of a game session might look like this: Data Protection
using tape loops,
Declaration
delay effects, $ python3 number_game.py
sampling, a sampler New number: 12
or special computer Number too small Data Protection
software. New number: 15 Declaration
Number too small
New number: 18
Number too large
This website is New number: 17
supported by: Congratulation. You made it!
$
Linux and Python
Courses and Previous Chapter: Conditional Statements
Seminars Next Chapter: For Loops

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like