search

Python Loops 1

Jul 17, 2024 am 08:54 AM

Python Loops 1

Hey everyone! I'm back with another new Python lesson for this week. This week we will study about loops. Loops are really important topic in any programming language. By understanding loops, you'll be able to perform tedious and long work in a matter of seconds. So you can realize how important loops are. So let's dive into it.

Why do we need loops?
Let's try to understand loop with a problem. Suppose, you're the class representative of your class and the professor has given you the responsibility of finding out the average grade in your class from the database.
Now your class has 30 students. So there are 30 grades in the database. For now, let's assume, the grades are stored in a single variable as a list. (we'll talk more about "lists" later)
Now it's surely going to take a long time to find out the average grade manually. So in this case, loops come into play. Loops will allow you to execute this tedious task in a small matter of time.

So what is loop actually?

A Python loop is a control structure that repeatedly executes a block of codes as long as a specified condition is met or for each item in a sequence.

So in simple words, loop helps us to perform repeated tasks.

Based on this definition, python loop is of two types.
1) For loop
2) While loop

For Loop:
We use for loop to iterate over each elements in a sequence(string, list, tuple, dictionary, etc.) The loop will start from index 0 of the sequence and will run until the last item of that sequence.

for items in sequence:
    repetitive work or block of statements

Let's solve the problem using for loop

#Here are our grades of 30 students
grades = [85, 92, 78, 88, 91, 76, 95, 89, 83, 77,
          90, 82, 84, 79, 87, 93, 81, 80, 86, 94,
          75, 88, 85, 92, 78, 89, 77, 84, 91, 76]


sum=0
for item in grades:
    sum=sum+item

average=sum/len(grades)

print(average)

First, we have a variable named sum, where we'll store the sum of all grades. Then we have a for loop. The loop will start from index 0 item until the last item. In each iteration, it's going to add each item to the sum. Outside of this for loop's block, we will count the average by dividing the sum with no of grades(len function tells us how many items are in the list-more about this later).

While loop

In while loop, as long as the condition is true, the loop is going to iterate the block of codes. The moment, the condition is false, the loop is going to stop.

while condition is true:
    do something repeatedly

Let's solve the same problem using while loop:

grades = [85, 92, 78, 88, 91, 76, 95, 89, 83, 77,
          90, 82, 84, 79, 87, 93, 81, 80, 86, 94,
          75, 88, 85, 92, 78, 89, 77, 84, 91, 76]

sum = 0
index = 0

while index 



<p>Note: Here in this solution, you may notice some functions that we have not explained before. We'll talk more about those briefly in list lesson.</p>

<p>So here in this solution, we've declared a new variable index alongside sum. Index variable help us to access the items of the grades list which gets incremented in each loop(index +=1). In while loop, the condition is as long as the index is less than the number of items in grades list, the loop will run and calculate the sum. grades[index] allow us access to the items of the list which is called indexing. The rest of the code is similar to for loop's solution.</p>

<p>This will be the end of part 1 of Python loops. In the next part, we'll discuss more about loops.</p>

<p><strong>Summary:</strong></p>

  • Python loop is a structure that helps with repeated tasks
  • For loop will iterate over each elements in a sequence(string,list,tuple,dictionary etc.)
  • While loop will iterate as long as the condition is true.

Practice Problem
Here's a list of 20 numbers:
num_list=[100, 82, 96, 4, 44, 27, 13, 45, 96, 21, 26, 71, 22, 19, 57, 69, 97, 34, 21, 92]

Calculate the average of all the even numbers of the given list.

Solve this problem for both For and While loop and share your answer in the comments. Happy Coding!

The above is the detailed content of Python Loops 1. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?How to improve the accuracy of jieba word segmentation in scenic spot comment analysis?Apr 02, 2025 am 07:09 AM

How to solve the problem of Jieba word segmentation in scenic spot comment analysis? When we are conducting scenic spot comments and analysis, we often use the jieba word segmentation tool to process the text...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version