Best post on looping in python (for loop)-Part 1




Looping statement in python

In programming there will be some statements or group of statements which we want to execute continuously for more than one time, this is where loops comes in the picture.
Looping allow us to continuously execute particular statement or block of statement to more than one time.
Looping will check for the condition, and will continuously execute particular statement or block of statement until the condition get false or invalid.
Repeated execution of a set of statements is called as iteration.
This statements are executed in order except when a jump statements are encountered.



Following are the types of loops in python programming.
1. for loop
2. for-else loop
3. while loop
4. while-else loop
5. Nested loop
6. Infinite loop

Looping statements in python
Looping statements in python

for loop

In python for loop is used to iterate over a sequence like list,string, tuple etc and other iterable objects.
Iterating over a sequence is called as traversal.
We can also embed conditional statements in for loop.
Syntax
Here is the simple syntax for looping statement in python : for loop−

for iterator in iterable:
    statement(s)

Here,
iterator is any variable used for traversing a sequence.
iterable is any sequence like string, list, tuple etc.




for loop in python (itvoyagers.in)
for loop in python (itvoyagers.in)

Explanation
If the logical expression consist of a sequence for eg. list then the first element in the list is evaluated first.
The iterating variable or iterator is assigned with first element from list, after this the code block is executed.
Again same steps are repeated until end of list is reached.




The range function

Python provides many built-in functions. The range function is one of the built-in function given by python.
It produces an iterable of arithmetic series.
It returns a sequence of numbers from start to stop by step.
The range function produces an iterator which traverse through sequence of integers from 0 to n-1.
We can typecast the range() to list() to get list of values from sequence.

Syntax

range(stop) -> range object
range(start, stop[, step]) -> range object

Here,
start indicates starting value for range and it is optional
stop indicated ending value of range
step indicates the jump value for range and it is optional




Example of range()

""" Author : ITVoyagers (itvoyagers.in) 
Date :16th August 2020 
Description : Program to show use of range function """
>>> range(7)
range(0, 7)
>>> range(1,7)
range(1, 7)
>>> list(range(7))
[0, 1, 2, 3, 4, 5, 6]
>>> list(range(1,7))
[1, 2, 3, 4, 5, 6]
>>> list(range(1,7,2))
[1, 3, 5]

Example of range function

""" Author : ITVoyagers (itvoyagers.in) 
Date :16th August 2020 
Description : Program to show use of range function in for loop """

print("Output of for loop using range()")
for m in list(range(10)):
    print(m)

Output

Output of for loop using range function
Output of for loop using range function




Iterating by sequence index

One more way to iterate using for loop is through index of a sequnce.

Example of for loop with sequence index

""" Author : ITVoyagers (itvoyagers.in) 
Date :16th August 2020 
Description : Program to display multiplication table using for loop """

num=int(input("Enter number to display multiplication table"))
print("Table of",num)
for i in range(11):
    print(num,'*',i,'=',num*i)

Output

Enter number to display multiplication table 7
Table of 7
7 * 0 = 0
7 * 1 = 7
7 * 2 = 14
7 * 3 = 21
7 * 4 = 28
7 * 5 = 35
7 * 6 = 42
7 * 7 = 49
7 * 8 = 56
7 * 9 = 63
7 * 10 = 70

Example of for loop with sequence index

""" Author : ITVoyagers (itvoyagers.in) 
Date :16th August 2020 
Description : Program to show use of for loop with sequence index """

print("Output of for loop using sequence(list) index")
words=['i','am','a','code']
print("List of words", words)
for index in range(len(words)):
    print("Current word is",words[index])

Output

Output of for loop using sequence index
Output of for loop using sequence index




Example of for loop with sequence index

""" Author : ITVoyagers (itvoyagers.in) 
Date :16th August 2020 
Description : Program to show use of for loop with sequence index """

print("Output of for loop using sequence(list) index")
words=['i','am','a','code']
for m in words:
    print(m)
print("Output of for loop using sequence(tuple) index")
h=(1,5,9,3,7)
for m in h:
    print(m)

Output

Output of for loop using sequence index
Output of for loop using sequence index




Example of for loop with string

""" Author : ITVoyagers (itvoyagers.in) 
Date :16th August 2020 
Description : Program to show use of for loop with string """

print("Output of for loop using sequence(list) index")
for letter in 'itvoyagers':
    print("Current letter is",letter)

Output

Output of for loop using string
Output of for loop using string




for-else loop

Python allows us to use else statement with loop statement.
In for loop we can use else statement.
In for loop if an else statement is used then the else block will be executed only if the for loop finishes normally that means for loop do not encounter break statement.

Example of for else loop with and without break statement

""" Author : ITVoyagers (itvoyagers.in) 
Date :16th August 2020 
Description : Program to show use of for loop with string """

num=[1,3,2,5,7,9,11,13]
print("Output without break statement")
print("---------------------------------------")
for n in num:
    if n%2==0:
        print("even number is present in list \n")
else:
    print("even numbers are not present in list \n")
print("\n")
print("Output with break statement")
print("---------------------------------------")
for n in num:
    if n%2==0:
        print("even number is present in list \n")
        break
else:
    print("even numbers are not present in list \n")

Output

Output of for else loop with and without break statement
Output of for else loop with and without break statement

For other python basics related posts:

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon.......

For other advanced python related posts:

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in 're' module(Part I)- Match vs Search
Functions in 're' module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
New posts coming soon.......

Leave a Comment