Skip to main content

Python while and for Loop Statments






Loops are indeed very powerful as it allows us to do a repetitive task that is to execute statement or group of statements multiple times. Python provides following types of loops to handle repetitive tasks: for and while loops.

The semantics of the while loop:

while condition:
    body containing (statment/s)

The semantics of the for loop:

for item in list:
     statement/s

Example 1 (for):

#Program to print each character in a string (which is a sequence of characters)

string = "Python"

#for each charachter in a string do this: print(char,end = '')

for char in string:
    print(char,end = '') #Output:Python

Example 2 (for):

#Program to print the first 5 positive even numbers
#Note:loops runs from 0-9 increment by 1

for number in range(0,10):
    #even if evenly divisible by 2
    if( number%2 == 0):
        print(number,' is even')

#Alternative way, the range function also takes "step" as a parameter
#from 0-9 increment by 2

for number in range(0,10,2):
        print(number,' is even')


Output:
0  is even
2  is even
4  is even
6  is even
8  is even
0  is even
2  is even
4  is even
6  is even
8  is even

Example 3 (nested-for ):

#nested for loop

#Program to print number pattern such as this
#1
#12
#123
#1234
#12345
#123456
#1234567

for outer in range(1,8):
    for inner in range(1,outer+1):
        print(inner,end ='')
    print()

Output:
1
12
123
1234
12345
123456
1234567 

Example 1 (while):

#program to add the first 100 positive numbers

limit = 100
count = 1
sum =0

while count<=limit:
    sum+=count
    count+=1 #increment count by 1, there is no ++ operator in python :(

print(sum) #Output:5050


Example 2 (while):

#Countdown program

count  = 10
limit = 0

while count>=limit:
    print(count, end='-> ')
    count-=1; #decrement count by 1
    
print('Go!')

Output:
10-> 9-> 8-> 7-> 6-> 5-> 4-> 3-> 2-> 1-> 0-> Go!


Example 3 (nested while ):

#Program to print number pattern such as this
#1
#12
#123
#1234
#12345
#123456
#1234567

end = 7
start = 1

while start<=end:
    inner_start = 1
    inner_end = start
    while inner_start<=inner_end:
         print(inner_start,end ='')
         inner_start+=1
    start+=1
    print()


Output:
1
12
123
1234
12345
123456
1234567 

NOTE: there is no do-while loop in Python. However, it is possible to emulate the do-while loop as shown below.Use the while-True form shown below with an inner if-break when a do-while loop would have been appropriate.
Enhanced while-loop semantics:

while True:
    <setup code>
    if not <condition>:
        break
    <loop body>

Comments

Popular posts from this blog

Non-decreasing Array - LeetCode

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array.   Example 2: Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element. Note: The n belongs to [1, 10,000]. Source: LeetCode At first glance, it looks like an easy and straightforward problem, but believe me it's greedy problem. In the problem, you are allowed to make atmost "one" modification to make a non-decreasing array. Nondecreasing means that every element is greater than or equal to the one before it e.g. [1,3,4,4,5,6,9]. For example, [2,2,3,2,4] can this become non-decreasing? Yes, by replacing 3 with 2 =>[2,2,2,2,4]. What about this:

RLE Encoding and Decoding in C++

Given an input string, write a regular recursive function that returns the decoded (uncompresseed form) Run Length Encoded   (is a simple form of data compression where repeated character are replaced by count followed by the character repeated) string for the input string. Below are some examples: decode("*") =>* decode("3+") =>+++ decode("11*") =>*********** decode("101+") =>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ decode("abcde10+10*10+10x") =>abcde++++++++++**********++++++++++xxxxxxxxxx decode("\\") =>\ decode("\1\2\3") =>123 decode("13\7x") =>7777777777777x decode("5\\") =>\\\\\ decode("4\12\23\3") =>111122333 decode("4\\2\3") =>\\\\33 NOTE: To represent a single backslash, it’s necessary to place double backslashes (\\) in the input string to obtain the desired in

Merge Two Binary Trees

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7    Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7   Note: The merging process must start from the root nodes of both trees.  Source: LeetCode Solution: We traverse both trees in a preorder fashion. In