Control Structers - Loops
Control Structers - Loops
Introduction to
Programming
Control Structures in Python:
Loops
LOOPS
• Loops are repetition statements in programming
languages
• They are used for iterative calculations
• Why do we need them?
LOOPS
• They actually take a crucial role in programming
• In real life problems and programs, it is rare to make
just one calculation with a single program
LOOPS
• Most of the programs are written for calculations on
complex and huge amount of data
• In order to search, sort, and analyze them we need to
use loops
LOOPS
• Furthermore, when we want to do the same process
for more than one entity, instead of typing the same
code for many entities, we just write it once and run it
multiple times in a loop
LOOPS
• Loops generally contain three
parts in themselves:
• a counter / a conditional variable
initialization,
• conditions
• counter incrementation /
conditional variable calculation
LOOPS
• There are two types of loops in Python:
1. While
2. For
• We will learn both of these types of loops in this
class
While
• The general structure of while in Python is as
following
• Here, the loop continues as long as the
condition is true!
While
Example 1: Let us print the integer numbers from 1
to 10 in Python.
While
Example 2: Let us write a Python program that asks user to
enter 5 different integer numbers and calculates the sum
of these numbers.
While
Example 3: Let us write a Python program that calculates
n! , where .
While
Example 4: Let us write a Python program that calculates
until its value is less than or equal to 0.01
for
While
Example 5: Let us write a Python program that loops until
the user enter the word "stop".
While
• As in if statements, we can use multiple
conditions in while, as well.