Conditional constructs and looping - Python Programming Made Easy (2016)

Python Programming Made Easy (2016)

Chapter 4: Conditional constructs and looping

Control structures change the order that statements are executed or decide if a certain statement will be run.

Conditional constructs

When a program has more than one choice of actions depending on a variable's value it uses a conditional construct. Decision making structures require that the programmer specifies condition(s) which if determined to be true a set of statements are executed and if evaluated to falseanother set of statements are executed.

Construct

Syntax

Description

If

if condition :

Statements

If the condition is true, then do the indented statements. If the condition is not true, then skip the indented statements.

if – else

if expression:

statement(s)

else:

statement(s)

In an if-else statement exactly one of two possible indented blocks is executed.

if –elif-else

if expression1:

statement(s)

elif expression2:

statement(s)

elif expression3:

statement(s)

else:

statement(s)

Only if the preceding if statement is false, the next if statement is executed.

Example 4.1: Write a program to accept electricity bill details (i.e) customer number , customer name , previous month meter reading and current month reading and then find no.of units consumed by the customer and amount payable to electricity department by performing following checks :-

First 100 units cost per unit is Rs.4.00

Next 500 units cost per unit is Rs.5.00

Beyond 500 units cost per unit is Rs.6.00

Step 1: First line of a program is a comment detailing the purpose of the program

# Program to calculate electricity bill

Step 2: We need to get the required input from the user.

name = raw_input("Enter customer's name:-")

prev = float(raw_input("\nEnter the previous month's reading:-"))

curr = float(raw_input("\nEnter the current month's reading:-"))

Step 3: Calculating the number of units of electricity consumed

#Consumed units is current meter reading - previous meter reading

units = curr prev

Step 4: Deciding on the formula for amount calculation

if units <= 100:

bill=units*4.00;

elif units >100 and units < 500:

bill=400 + (units-100)*5.00;

else:

bill = 400+ 2000+ (units-500)*6.00;

Step 5: Displaying the output

print "No. of units consumed= ",units

print "Amount payable to the electricity department= Rs", bill

Output:

Iteration structures

Loops are used to repeatedly execute the same code in a program. Python has 2 loops

è for

è while

for

The general syntax for “for” loop is

for item in sequence:

statement(s )

(or)

for var in range([start,] finish):

statement(s)

The range function uses two arguments like this range(start,finish). start is the first number that is produced. finish is one larger than the last number.

Example 4.2: Write a program to print numbers from 0 to 10.

for a in range(0, 10):

print (a)

The output is

0 1 2 3 4 5 6 7 8 9

The break statement breaks out of the smallest enclosing for or while loop. It can be used to unconditionally jump out of the loop. It terminates the execution of the loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This can be explained with Example 3.

Example 4.3: Write a program to print all prime numbers from 2 to 50 using for loop.

We need to divide each number by all numbers starting from 2 to itself. So, if we take 7, we need to divide 7 by 2, 3, 4, 5 and 6 and if it’s not divisible by any of these numbers, then we conclude that it’s a prime number and we print it on the output screen.

for n in range(2, 50):

x_range = range(2, n)

for x in x_range:

if n % x == 0:

break

else:

# loop fell through without finding a factor

print(n)

Program flow:

Let’s take n=9

x_range = range(2, 9)

for x in x_range:

if 9 % x == 0:

break

else:

# loop fell through without finding a factor

print(9)

When x =2

If 9%2 ==0è false so continue the for loop

If 9%3 ==0è true so break out of the loop no need to check other factors. 9 is not a prime number.

while

The syntax of the while loop is given below

while condition:

statement(s)

The while loop is used in cases when the start or end of an iteration is not known.

Example 4.4: Write a program for printing Fibonacci series.

# Fibonacci series:

# the sum of two elements defines the next number

a, b = 0, 1

while b < 10:

... print b

... a, b = b, a+b

1

1

2

3

5

8

• The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

• The while loop executes as long as the condition (here: b < 10) remains true. In Python any nonzero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison.

• The body of the loop is indented: indentation is Python’s way of grouping statements.

· A trailing comma avoids the newline after the output.

a, b = 0, 1

while b < 100:

print b,

a, b = b, a+b

Now the output would be

1 1 2 3 5 8 13 21 34 55 89

Note: Everything that can be done with for loops can also be done with while loops but for loops give an easy way to go through all the elements in a list or to do something a certain number of times.

The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop. Continue will return back the control to the beginning of the loop.

pass does nothing but may be used as a placeholder for future implementation.

Solved Programs

1. Write a program to validate password length.

Ans:

# This program gets a new password from the user validates its length and

# prints an error message if the password entered is less than 6 characters

while True:

s = raw_input('Enter new password: ')

if len(s) < 6:

print 'Input is of insufficient length'

continue

else:

print "Password changed successfully"

break

2. Write a program to add numbers arbitrarily till the user enters 0.

Ans:

a = 1

s = 0

print ('Enter Numbers to add to the sum.')

print ('Enter 0 to quit.')

while a != 0:

a = int(raw_input('Number? '))

s += a

print 'Total Sum = ',s

3. Write a program in Python to find the summation of the following series using for loops.

1+ x + x2 + x3 + … + xn

Ans:

import math

sum=0

n = int (raw_input("Enter the value of n:"))

x = int (raw_input("Enter the value of x:"))

for i in range(10):

sum=sum + pow(x,i);

print " 1 + ",x,"+ ",x,"^2 + ", x,"^3 +...",x,"^",n," =",sum,"\n";

raw_input()

4. Write a program in Python to convert a given number from Decimal to Binary.

Ans:

i=1

s=0

dec = int ( raw_input("Enter the decimal to be converted:"))

while dec>0:

rem=dec%2

s=s + (i*rem)

dec=dec/2

i=i*10

print "The binary of the given number is:",s

raw_input()

5. Write program to input any number and to print all factors of that number.

Ans.

n = input("Enter the number")

for i in range(2,n):

if n%i == 0:

print i,"is a factor of",n

6. Write a program to input any number and to check whether given number is Armstrong or not. (Armstrong 1,153,etc. 13 =1 , 13+53 +33 =153)

Ans.

n = input("Enter the number")

savedn = n

sum=0

while n > 0:

a = n%10

sum = sum + a*a*a

n = n/10

if savedn == sum:

print savedn,"is an Armstrong Number"

else:

print savedn,"is not an Armstrong Number"

7. Write a program to find all prime numbers up to given number.

Ans.

n = input("Enter the number")

i = 2

flag = 0

while(i < n):

if (n%i)==0:

flag = 1

print n,"is composite"

break

i = i+ 1

if flag ==0 : print n,"is prime"

8. Write a program to find the sum of all digits of the given number.

Ans.

n = input("Enter the number")

rev=0

while(n>0):

a=n%10

sum = sum + a

n=n/10

print "Sum of digits=",sum

9. Write a program to find the reverse of a number.

Ans.

n = input("Enter the number")

rev=0

while(n>0):

a=n%10

rev=(rev*10)+a

n=n/10

print "Reversed number=",rev

10. Write a program to print the pyramid.

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Ans.

for i in range(1,6):

for j in range(1,i+1):

print i,

print

Practice Problems

1. Write a program to find the roots of a quadratic equation.

2. Write a program to accept electricity bill details (i.e) customer number , customer name , previous month meter reading and current month reading and then find no.of units consumed by the customer and amount payable to electricity department by performing following checks :-

First 100 units cost per unit is Rs.4.00

Next 500 units cost per unit is Rs.5.00

Beyond 500 units cost per unit is Rs.6.00

3. Write a program in Python to find the summation of the following series using for loops.

1- x + x2 /2!- x3/3! + … + (-1)nxn / n!

4. Write a program to simulate a guessing number game. Generate a number from 1 to 100 and ask the user to guess it correctly within 5 tries. After each guess, the program must tell whether the number is higher than, lower than, or equal to your guess.

5. Write a program to print every integer between 1 and n divisible by m.

6. What does the following print out?

for i in range ( 1 , 10 ) :

for j in range ( 1 , 10 ) :

print i * j ,

print

7. Write a program to print the pyramid.

1

1 2

12 3

1 2 3 4

1 2 3 4 5