-
Notifications
You must be signed in to change notification settings - Fork 4
loops in python
Amin Zamani edited this page Feb 27, 2024
·
6 revisions
- There are two types of loops in Python:
while
andfor
:
- the
while
loop executes a statement or a set of statements as long as a specified boolean condition is true, e.g.:
# Example 1
while True:
print("Stuck in an infinite loop.")
# Example 2
counter = 5
while counter > 2:
print(counter)
counter -= 1
-
If you notice some similarities to the
if
instruction, that's quite all right. Indeed, the syntactic difference is only one: you use the wordwhile
instead of the wordif
. The semantic difference is more important: when the condition is met,if
performs its statements only once;while
repeats the execution as long as the condition evaluates toTrue
. -
the
for
loop executes a set of statements many times; it's used to iterate over a sequence (e.g., a list, a dictionary, a tuple, or a set - you will learn about them soon) or other objects that are iterable (e.g., strings). You can use thefor
loop to iterate over a sequence of numbers using the built-inrange
function. Look at the examples below:
# Example 1
word = "Python"
for letter in word:
print(letter, end="*")
# Example 2
for i in range(1, 10):
if i % 2 == 0:
print(i)
- any variable after the
for
keyword is thecontrol variable
of the loop; it counts the loop's turns, and does it automatically; - the
in
keyword introduces a syntax element describing the range of possible values being assigned to thecontrol variable
;
- You can use the
break
andcontinue
statements to change the flow of a loop:
- You use
break
to exit a loop, e.g.:
text = "OpenEDG Python Institute"
for letter in text:
if letter == "P":
break
print(letter, end="")
- You use
continue
to skip the current iteration, and continue with the next iteration, e.g.:
text = "pyxpyxpyx"
for letter in text:
if letter == "x":
continue
print(letter, end="")
- The
while
andfor
loops can also have anelse
clause in Python. Theelse
clause executes after the loop finishes its execution as long as it has not been terminated bybreak
, e.g.:
n = 0
while n != 3:
print(n)
n += 1
else:
print(n, "else")
print()
for i in range(0, 3):
print(i)
else:
print(i, "else")
- The
range()
function generates a sequence of numbers. (we can even say that it will feed the loop with) It accepts integers and returns range objects. The syntax ofrange()
looks as follows:range(start, stop, step)
, where:
-
start
is an optional parameter specifying the starting number of the sequence (0 by default) -
stop
is an optional parameter specifying the end of the sequence generated (it is not included), - and
step
is an optional parameter specifying the difference between the numbers in the sequence (1 by default.)
Example code:
for i in range(3):
print(i, end=" ") # Outputs: 0 1 2
for i in range(6, 1, -2):
print(i, end=" ") # Outputs: 6, 4, 2
- Introduction
- Variables
- Data Types
- Numbers
- Casting
- Strings
- Booleans
- Operators
- Lists
- Tuple
- Sets
- Dictionaries
- Conditionals
- Loops
- Functions
- Lambda
- Classes
- Inheritance
- Iterators
- Multi‐Processing
- Multi‐Threading
- I/O Operations
- How can I check all the installed Python versions on Windows?
- Hello, world!
- Python literals
- Arithmetic operators and the hierarchy of priorities
- Variables
- Comments
- The input() function and string operators
Boolean values, conditional execution, loops, lists and list processing, logical and bitwise operations
- Comparison operators and conditional execution
- Loops
- [Logic and bit operations in Python]
- [Lists]
- [Sorting simple lists]
- [List processing]
- [Multidimensional arrays]
- Introduction
- Sorting Algorithms
- Search Algorithms
- Pattern-matching Algorithm
- Graph Algorithms
- Machine Learning Algorithms
- Encryption Algorithms
- Compression Algorithms
- Start a New Django Project
- Migration
- Start Server
- Requirements
- Other Commands
- Project Config
- Create Data Model
- Admin Panel
- Routing
- Views (Function Based)
- Views (Class Based)
- Django Template
- Model Managers and Querysets
- Form
- User model
- Authentification
- Send Email
- Flash messages
- Seed
- Organize Logic
- Django's Business Logic Services and Managers
- TestCase
- ASGI and WSGI
- Celery Framework
- Redis and Django
- Django Local Network Access
- Introduction
- API development
- API architecture
- lifecycle of APIs
- API Designing
- Implementing APIs
- Defining the API specification
- API Testing Tools
- API documentation
- API version
- REST APIs
- REST API URI naming rules
- Automated vs. Manual Testing
- Unit Tests vs. Integration Tests
- Choosing a Test Runner
- Writing Your First Test
- Executing Your First Test
- Testing for Django
- More Advanced Testing Scenarios
- Automating the Execution of Your Tests
- End-to-end
- Scenario
- Python Syntax
- Python OOP
- Python Developer position
- Python backend developer
- Clean Code
- Data Structures
- Algorithms
- Database
- PostgreSQL
- Redis
- Celery
- RabbitMQ
- Unit testing
- Web API
- REST API
- API documentation
- Django
- Django Advance
- Django ORM
- Django Models
- Django Views
- Django Rest Framework
- Django Rest Framework serializers
- Django Rest Framework views
- Django Rest Framework viewsets