파이썬 루프 1

PHPz
풀어 주다: 2024-07-17 08:54:00
원래의
420명이 탐색했습니다.

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 < len(grades):
    sum += grades[index]
    index += 1

average = sum / len(grades)

print(average)

로그인 후 복사

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.

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.

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

Summary:

  • 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!

위 내용은 파이썬 루프 1의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!