Python Basics
- Introduction to Python
- Installing Python in Windows
- Python Values, Variables and Types
- Python Variable Names and Keywords
- Python Statements
- Python Operators and Expressions
- Take input from User in Python
- Python Comments
- Python Conditional Execution
- Python Functions
- Python Loops
- Python Strings
- Python Lists
- Python Dictionaries
Python Loops
Python While Loop:
Iteration is very common in any programming language. Python provides several features to make it easier. One form of iteration in Python is the while statement.
Flow of execution for a while statement:
1. Evaluate the condition is True or False.
2. If the condition is false, exit the while statement and continue execution atthe next statement.
3. If the condition is true, execute the body and then go back to step 1.
Here is a simple program:
# To take input from the user. # n = int(input("Enter n: "))n = 10while n <15 : print(n) n = n + 1 print('STOP!!!')
For the above loop, we would say, “It had five iterations”, which means that the body of the loop was executed five times.
Try it Yourself
The body of the loop should change the value of one or more variables so that the condition becomes false and the loop terminates. The variable which helps to finish the loop is called iteration variable. If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop.
Python “Infinite loops” and break:
You can write an infinite loop on purpose and then use the break statement to jump out of the loop.
n = 10 while True : print(n) n = n + 1 print('STOP!!!')
If you mistakenly run the above code then you will see that it will run forever. While this is a dysfunctional infinite loop, we can still use this pattern to build useful loops as long as we carefully add code to the body of the loop to explicitly exit the loop using break when we have reached the exit condition. For example, suppose you want to take input from the user until they type done.
You could write:
while True: line = input('Enter "STOP" to stop the loop\n') if line == 'STOP': break print(line) print('STOP!')
Here, the loop condition is True, which is always true, so the loop runs repeatedly until it hits the break statement.
Try it Yourself
Finishing iterations with continue in Python:
Sometimes you are in an iteration of a loop and want to finish the current iteration and immediately jump to the next iteration. In that case you can use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration.
Here is an example of a loop that copies its input until the user types “STOP”, but treats lines that start with the hash character as lines not to be printed (kind of like Python comments).
while True: line = input('> ') if line[0] == '#': continue if line == 'done': break print(line) print('Done!')
Example 2:
for i in "Make Me Analyst": if i == "M": continue print(i) print("STOP")
Try it Yourself
Python for Loop:
Sometimes You want to loop through a set of things such as a list of words, the lines in a file, or a list of numbers. When you have a list of things to loop through, you can construct a definite loop using a for statement. You call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set. The syntax of a for loop is similar to the while loop in that there is a for statement and a loop body:
emp = ['Seba', 'Kattula', 'Mohan'] for e in emp: print('Hello:', e) print('Done!')
Example 2:
arr=[1,2,3,4,5] for i in arr: print(i)
Try it Yourself
The range() function in Python:
You can generate a sequence of numbers using range() function. range(5) will generate numbers from 0 to 4 (5 numbers). You can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if not provided. You can use this function in a list() to output all the items in it.
# Program to iterate through a list using indexing arr = [1,2,3,4,5] # iterate over the list using index for i in range(len(arr)): print(arr[i])
Example 2:
# Program to iterate through a list using indexing arr = ["A","B","C","D"] # iterate over the list using index for i in range(len(arr)): print(arr[i])
Try it Yourself
Bonus Example: Counting and summing loops
count = 0 for i in [1,2,3,4,5]: count = count + 1 print('Count: ', count)
Try it Yourself
Bonus Example: Maximum and minimum loops
largest = None print('Before:', largest) for i in [3, 4, 12, 90, 44, 150]: if largest is None or i > largest : largest = i print('Loop:', i, largest) print('Largest:', largest)
smallest = None print('Before:', smallest) for i in [3, 4, 12, 90, 44, 150]: if smallest is None or i < smallest : smallest = i print('Loop:', i, smallest) print('Largest:', smallest)
Try it Yourself