#21 Python Tutorial for Beginners | For Loop in Python
Introduction to For Loops
In this video, Ivan Vetti introduces the concept of for loops in Python. He explains how for loops differ from while loops and how they work with sequences such as lists, tuples, and strings.
For Loop Basics
- While loops have a set number of iterations based on a condition, but for loops work with sequences.
- To print values from a list one by one using a for loop, use the syntax
for i in x:whereirepresents each element of the list.
- Use proper indentation when writing code within a for loop.
- Unlike while loops, for loops do not require variables or conditions to be specified.
Using For Loops with Different Sequences
- For loops can be used with different types of sequences such as strings and tuples.
- When using a string in a for loop, each character is treated as an element of the sequence.
- Instead of using a separate variable to store the list values, you can specify the list directly within the for loop syntax.
- The
range()function can be used within a for loop to print values from 1 to 10.
Range and For Loop
In this section, the speaker explains how to use range and for loop in Python.
Using Range Function
- To generate a sequence of numbers, we can use the
range()function.
- The
range()function takes three arguments: starting point, ending point, and iteration.
- We can specify the gap between two numbers by setting the iteration value. If not specified, it defaults to 1.
- To print values in reverse order, we need to set the iteration value as -1.
Using For Loop
- We can use a for loop to iterate over a sequence of values generated by the
range()function.
- We can add an if condition inside the for loop to print only certain values that meet specific criteria.
- To skip printing values that are divisible by 5, we can add an if condition with modulo operator
%.
Conclusion
In this section, the speaker concludes this video and invites viewers to leave comments and like the video.
Conclusion
- The speaker thanks viewers for watching and invites them to leave comments in the comment section below.
- Viewers are also encouraged to hit the like button if they enjoyed watching this video.