Loops: If we want to automate a repetitive process we can use loop to do that. A loop is a programming structure that executes the same code over and over again, as long as the certain conditions become false
Types of Loop:
There are 2 types of loop
1. While loop
2. For loop
1. While:
A while loop executes the code in its block until the condition is true. If the condition is false the loop will exit the block
Syntax:
while(condition):
loop statement
Example:
We use while keyword to define the loop, in the example we counting from one to ten. We initialised the variable number with value zero. In every iteration we increase the value by one and print it this is done as long as the number is less than ten(that when a condition becomes false)
Endless Loop:
while True:
print("this will continue")
Since it is always true the loop will never end unless we terminate the script
Warning: This might overload your computer
2. For Loop:
The Endless works bit different from while loop. Here we don't have condition. This loop type is used to iterate over sequence
When we have list of numbers and then we want to print it we use for keyword to iterate over it
As you can see, the loop continues as long as there is a next element in the list
Range Function:
With Endless we can create lists that contain all numbers inbetween two numbers
This is the simple way to print 10 numbers but we can also do is start counting from another number
Our range list will be between 20 and 30
in next post lets see about user input!!
Comments
Post a Comment