In this Python for beginners tutorial we are going to learn the following:
How to create a for loop to iterate through the items of a list.
How to create a for loop to run a piece of code a specific number of times.
We will also solve a simple exercise.
One of the main things that make computers so powerful is that they can quickly do the same tasks or calculations over and over again. One way to tell a computer to do this is by using loops. A loop is a kind of programming expression that lets you run a section of code over and over again. Python has two types of main loops, just like other programming languages, for loops and while loops. For loops are the subject of today's video.
A FOR loop is a type of loop used to repeat a block of code a specific number of times. In most cases, we use for loops with LISTS when we know how many times, we need to repeat a piece of code.
For example, I have created a list of 5 delicious fruits and for every fruit, in the list, I want to print the fruit name and that is a delicious fruit like this:
Apple is a delicious fruit.
Plum is a delicious fruit.
And so on.
One way to do this is to use 5 print commands like this and use the list index to get every item from the list. That works for short lists, but what if my list has 1,000 items? I'd need two days to type all of the print commands. This is where the for loop comes in.
I delete all the print commands and I simply type:
for (that’s a word that tells the computer that we want to create a loop) fruit (that’s a variable we can call anything we want but since we work with a list of fruits, the name fruit is a descriptive name) in fruits (that’s the list we want to work with): colon
Смотрите видео For Loop - Python for Absolute Beginners Course онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Programming With Nick 10 Май 2022, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 322 раз и оно понравилось 14 людям.