Contact Us

Loops and Branches

Day-3 of A Month in the Python's Cave

getting started with meteor
Decision Making is Integral to Programming
It's quite usual in programming to take decisions using certain conditions on variables and execute the piece of code based on what the decision turns out to be. Just for an example, while programming a light switch in Python we may have to make decisions like the following:

			if enough light -> keep lights switched off
			if light is dim -> turn on the light switch
if elif else in Python
Like many other programming languages Python offers if and else statements. We can make simple to complex decisions using a combinations of if-elif-else branching statements in Python. A prototype of what we've said is shown below.

	# Simple Decision 
	if condition1:
	# Add a Choice 
	if condition1:
	# Make it more complicated 
	if condition1:
	elif condition2:
	# Nesting Statements 
	if condition1:
		if condition2:
			if condition3:

You can build really complex algorithms using simple branching with if and else. Let's look at some of the Python code examples where we use if-else statements to take interesting decisions.
Code Example 'Colors do Speak'
Problem Statement: You get to see a saint Rang Baba in the Python's Cave and the interesting thing about Rang Baba is that he predicts personality type of a person based on what their favourite colour is. You decide to assist the saint by using your newly acquired skill of taking decisions in python. Given a color as input you'll have to output the personality of the person as follows.

		VIOLET	->	optimistic
		INDIGO	->  independent
		BLUE    ->  practical
		GREEN   ->  conservative
		YELLOW  ->  trustworthy 
		ORANGE  ->  reliable 
		RED     ->  loving
Following is the Python code which can be used to implement the solution to the above problem. You can copy the following code and save it in a file colors.py and run it from command line using command python colors.py

#! /bin/py

################### colours.py #####################

favColor = raw_input('Enter your Favourite Color: ')
favColor = favColor.lower() #change user input to lower case
personality = ''
if favColor == 'violet':
	personality = 'optimistic'
elif favColor == 'indigo':
	personality = 'independend'
elif favColor == 'blue':
	personality = 'practical'
elif favColor == 'green':
	personality = 'conservative'
elif favColor == 'yellow':
	personality = 'trustworthy'
elif favColor == 'orange':
	personality = 'reliable'
elif favColor == 'red':
	personality = 'loving'
	personality = 'unpredictable'
print 'Your personality is: ',personality
Output of the above code!

>python colors.py
Enter your Favourite Color: YellOW
Your personality is:  trustworthy
Loops in Python
Loops help us to execute a given block of code multiple number of times or in some cases we may use loops to keep the code running unless some condition turns True or False. In the following sections we'll discuss for and while loops with examples of both.
Python While Loop
while loop helps to run a block of code repeatedly unless a given condition becomes True or False. General syntax for while loop is as shown below.

			code statements
			. . . 

While Loop Code Example:

Given input N, print cubes of first N natural numbers. Also make sure that N is less than or equal to 100.
Following is the Python code snippet which solves the above problem using a while loop. You can copy the following code in a file named cubes.py and run it in order to see the results.

#! /bin/py

import sys
n = int(raw_input('Enter the value of N: '))
if n > 100:
	print 'N too large, program exiting!'
	num = 1
	while num <= n:
		print 'Cube of %d is %d'%(num,num**3)
		num += 1 
Output of the above code!

> python cubes.py
Enter the value of N: 4
Cube of 1 is 1
Cube of 2 is 8
Cube of 3 is 27
Cube of 4 is 64
Python For Loop
Python for loop can be used to repeat the block of a code a given number of times. It's quite useful when performing operations on sequence of data. In Python, we use built-in function range() to decide how many times to run the for loop. Following is the general syntax for the Python for loop.

		for variable in range(start,end):
			code statements
			. . . 
			. . . 

for loop Code Example:

Given 2 integers m and n such that m < n, find the numbers between m and n which are divisible by both 3 and 5.
Following Python code demonstrates how the above problem can be solved using for loops. You can copy the following code in a file factors.py and execute it on your machine.

m = int(raw_input('Enter lower bound: '))
n = int(raw_input('Enter upper bound: '))
count = 0
for i in range(m,n):
	if i % 3 == 0 and i % 5 == 0:
		count = count + 1
print 'There are %d numbers divisible by both 3 and 5 in the range %d %d'%(count,m,n)
Output of the above code!

> python factors.py
Enter lower bound: 2
Enter upper bound: 20
There are 1 numbers divisible by both 3 and 5 in the range 2 20
You've done it! You've learned how branching and looping works in Python. Now go on and start helping your code to make wise choices.
PythonCave on Github
We've created a repository on github to keep pushing new code. In case you're enthusiastic about it, following is link to that repository.

developed & nourished with by rishabh.io