Python Fundamentals – Flow of Control
CONTROL STATEMENTS
Control statements define the direction or flow in which execution of a program should take place. Control statements also implement decisions and repetitions in programs.
Control statements are of the following two types:
- Conditional branching
- Looping
Conditional brandling, a program is to decide whether or not to execute the next statement(s) based on the resultant value of the current expression. For example, go to IInd year, if you pass Ist year exams, else repeat Ist year (See Figure 12.1).
Looping, the program performs a set of steps or operations repeatedly till a given condition is obtained. Looping for example, add 1 to number x till current value of x becomes 100 is also called iteration. Iteration is a process of executing a statement or a set of statements repeatedly, until some specific condition is specified (See Figure 12.2). All the control structures are further explained in the following sections:
CONDITIONAL STATEMENTS
Many a times in real-life applications, you will need to change the sequence of action based on the specified conditions.
Sometimes you need to use a simple condition like:
"If it is cold then put your coat on."
In this statement, the resultant action is taken if the condition is evaluated true (in our case, the weather is cold).
The conditions could be multiple, as in the following conversation:
"Ok then, if I come back early from work. I'll see you tonight; else if it is too late I'll make it tomorrow; else if my brother arrives tomorrow we can get together on Tuesday; else if Tuesday is a holiday then let it be Wednesday; else I'll call you to arrange for the next meeting!"
Python programs can easily handle such chained or nested conditions as long as you write the adequate code. In Python, there are many control structures that are used to handle conditions and the resultant decisions. In this Chapter, you will be introduced to more powerful tools namely, the if. .else, while, and for constructs.
if Statement
The statement if tests a particular condition. Whenever that condition evaluates to true, an action or a set of actions are executed. Otherwise, the actions are ignored. The syn¬tactic form ofstatement is the following:
if (expression): statement
The expression must be enclosed within parentheses. If it evaluates to a non-zero value, the condition is considered as true and the statement is executed.
Example 1
In the following program, shown as Figure 12.3 a credit card limit is tested for a certain purchase. The value of the variable amount is received from the keyboard, then tested using the if statement. When the condition is true (i.e., the “amount” is less than or equal to 1000), the message “Your charge is accepted” is displayed. If the condition is false, the program ends with a message “The amount exceeds your credit limit”.
# Credit card Program amount = input ( "Enter the amount :11) if (amount <= 1000) ; print "Your charge is accepted." if (amount > 1000): print "The amount exceeds your credit limit." RUN ››› Enter the amount : 1000 Your charge is accepted. ›››
if…else Statements
The statement if also allows to answer for the kind of either-or condition by using an else clause. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a false value. The else statement is an optional statement, if provided, in any situation, one of the two blocks get executed not both.
The syntactic form of if-else statement is as follows:
if (expression): statements BLOCK 1 else: statements BLOCK 2
When the expression evaluates to a non-zero value, the condition is considered to be true and statements BLOCK 1 is executed; otherwise, statements BLOCK 2 is executed. Blocks can have multiple lines. As long as they are all indented with the same amount of spaces, they constitute one block. Figure 12.4 shows the flow diagram of if-else statement.
A common use of if-else statement is to test the validity of data as given in Example 2.
Example 2
Suppose, you want to write a program that accepts a value of a variable from the user and prints the whether the number is positive or negative. Now write a program using the if-else statement.
The program is shown in Figure 12.5.
# Demo of if-else statement num = input("Enter a number :") if (num < 0): print "Number is negative." else: print "Number is positive." RUN ››› Enter a number : 5 Number is positive. ›››
Figure 12.5 Demo of if-else statement
Example 3
In the program shown in Figure 12.6, the if statement rearranges any two values stored in x and y so that the smaller number will always be in x and the larger number always in y. If the two numbers are already in the proper order, the compound statement will not be executed.
You will always get the larger value first and then the smaller value.
# Print larger number using swap x=y=0 x=int(raw_input("Enter the first number: ")) y=int(raw_input("Enter the second number: ")) if(x>y): x,y=y,x # swap (interchange) values print "The larger number is : ",y print "The smaller number is : ",x else: print "The larger number is : ",y print "The smaller number is : ",x RUN ››› Enter the first number: 5 Enter the second number: 7 The larger number is : 7 The smaller number is : 5 ››› ››› Enter the first number: 7 Enter the second number: 5 The larger number is : 7 The smaller number is : 5 ›››
Figure 12.6 Program using if statement for arranging two numbers
Program to print number is even or odd.
# Program to print no. is even or odd num=int(rawinput("Enter a number: ")) if num % 2 = = 0: print num, "is an even number." else: print num, "is an odd number."RUN ››› Enter a number: 6 6 is an even number. ››› ››› Enter a number: 7 7 is an odd number. ›››
Figure 12.7 Program to print no. is even or odd
Example 5
Program to display menu to calculate sum or product of entered numbers.
# Program to display menu to calculate sum or product of entered numbers numl = int(rawinput("Enter first number : ")) num2 = int(rawinput("Enter second number : ")) num3 = int(rawinput("Enter third number : ")) print "1. Calculate sum" print "2. Calculate product" choice = int(raw_input("Enter your choice (1 or 2): ")) if choice == 1: sum = numl+num2 +num3 print "Sum of three numbers are sum else: product = numl*num2 *num3 print "Product of three numbers are : ", product RUN ››› Enter first number : 2 Enter second number : 5 Enter third number : 3 1. Calculate sum 2. Calculate product * Enter your choice (1 or 2): 1 Sum of three numbers are : 10 ››› ››› Enter first number : 2 , Enter s'econd number : 5 Enter third number : 3 1. Calculate sum 2. Calculate product Enter your choice (1 or 2): 2 Product of three numbers are : 30 ›››
Figure 12.8 Program to display menu to calculate sum or product of entered numbers
Using //Statement with Compound Tasks
In the if statement studied so far, the statement following the condition or the keyword else is a single executable statement, such as an assignment statement. If multiple tasks are to be performed dependent on a condition, then they can be grouped ^together within block to form a single compound statement. Thus, you can use more than one statement as a result of one condition by embedding the statements in a block. In any compound statement, there is no limit on how many statements can appear inside the body, but there has to be at least one. Indentation level is used to tell Python which statement (s) belongs to which block.
If you want to check for several conditions, you can use elif, which is short for “else if”. It is a combination of an if clause and an else clause. Like the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if. The syntax of the if…elif statement is as follows:
if expressionl: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)
Example 6
# Demo of if ...elif... else statement num = input('Enter a number: ') if num > 0: print 'The number is positive' elif num < 0: print 'The number is negative' else: print 'The number is zero' RUN Enter a"number: 5 The number is positive ======================== RESTART =========================== ››› Enter a number: -6 The number is negative >>> ======================== RESTART =========================== ››› Enter a number: 0 The number is zero ›››
Figure 12.9 Demo of if…elif…else statement
Nested if Statements
There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct. In a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.
Example 7
Suppose that you want to test the ASCII code of a received character to check if it is an alphabetic character. If it is so, you would like to further check if it is in lower case or
upper case. Knowing that the ASCII codes for the upper case letters are in the range 65-90, and those for lower case letters are in the range 97-122. Program shown in Figure 12.9 establishes this logic.
LOOPS
Many jobs that are required to be done with the help of a computer are repetitive in nature. For example, calculation of salary of different workers in a factory is given by the(No. of hours worked) x (wage rate). This calculation will be performed by an accountant for each worker every month. Such types of repetitive calculations can easily be done using a program that has a loop built into the solution of the problem. Figure 12.11 shows the flow diagram of loop statement.
What is a Loop?
A loop is defined as a block of processing steps repeated a certain number of times. Figure 12.12 illustrates a flowchart showing the concept of looping. It shows a flowchart for printing values 1,2, 3…, 20.
In Step 5 of Figure 12.12, the current value of A is compared with 21. If the current value of A is less than 21, steps 3 and 4 are repeated. As soon as the current value of A is not less than 21, the path corresponding to “NO” is followed and the repetition process stops.
The while Statement
The while loop is used to repeat a set of statements as long as a condition is true. In Python, an indefinite loop is implemented using a while statement. An indefinite loop keeps iterating until certain conditions are met. The syntax of while statement is as follows:
while <condition>: <body>
Here condition is a Boolean expression. The body of the loop executes repeatedly as long as the condition remains true. When the condition is false, the loop terminates. Notice that the condition is always tested at the top of the loop, before the loop body is executed. This kind of structure is called a pretest loop. If the loop condition is initially false, the loop body will not execute at all. Here is an example of a simple while loop that counts from 0 to 10:
1 = 0 while i <= 10: print i i = i + 1
Above program will produce the following output:
1
2
3
4
5
6
7
8
9
10
Figure 12.13 shows the flow of control for a while statement. So long as x is less than y, the program continues to execute the while loop. With each pass through the loop, however, x is incremented by one. When it is no longer less than y, control flows to the next statement.
Example 8
Program in Figure 12.14 displays the string “Hello World” five times using the while loop.
# Demostration of while loop count = 0 while(count <=4) : print"\nHello World" count= count + 1 print "\nDone" RUN ››› Hello World Hello World Hello World Hello World Hello World Done ›››
Figure 12.14 Program to show ‘Hello World’ five times
Example 9
The program segment shown as Figure 12.15 computes and displays gross pay for seven employees. The loop body (the steps that are repeated) is the compound statement that starts on the seventh line, i.e., after the statement while (count_emp < 7):. The loop body gets an employee’s payroll data and computes and displays pay. After seventh pay amounts are displayed, the last statement “All employees processed” message will be displayed.
# Demostration of while loop countemp = 0 *. while(countemp <7): hours = input("\n Hours :") rate = input("\n Rate :") pay = hours * rate print "\nPay is Rs. ", pay countemp = countemp +1 print "\n All employees processed"
Figure 12.15 Computing and display gross pay for 7 employees
In Figure 12.16, the while loop is used to calculate the factorial of a number in this pro-gram, the number is received from the keyboard using the input function and is assigned to the variable “number”.
# Calculation of factorial factorial = 1 number = input("Enter the number : ") while(number > 1): factorial = factorial * number number = number -1 print "\nThe factorial is ", factorial RUN ››› Enter the number : 5 The factorial is 120 ›››
Figure 12.16 Program to calculate factorial of a number using while loop
Example 11
Write a program to print numbers 1 to 10 using while loop.
# Print numbers 1 to 10 using while loop count = 0 while(count <=10): print count count= count + 1 print "\nDone" RUN 0 1 2 3 4 5 6 7 8 9 10 Done
Figure 12.17 Print numbers 1 to 10 using while loop
Example 12
Write a program to print numbers 1 to 10 using while loop. Note that output are in the same line. # Print numbers 1 to 10 using while loop count = 0 while(count <=10): print count, count= count + 1 print "\nDone" RUN ››› 0123456789 10 Done ›››
Figure 12.18 Print numbers 1 to 10 using while loop
Example 13
Write a program to print even numbers series using while loop.
# print even numbers using while loop count = 0 while(count <=20) : print count, counts count + 2 print "\nDone" RUN ››› 0 2 4 6 8 10 12 14 16 18 20 Done ›››
Example 14
Write a program to print odd numbers series using while loop.
# print odd numbers using while loop count = 1 while(count < 20): print count, count= count + 2 print "\nDone" RUN ››› 1 3 5 7 9 11 13 15 17 19 Done ›››
Figure 12.20 Print odd number series using while loop
Example 15
Write a program to print the following pattern:
1
12
123
1234
12345
# Nested loop to print the given pattern i = 1 while(i<=5) : j = l while(j < = i): print j, j = j+1 print i = i +1 RUN ››› 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 ›››
Example 16
Write a program to print * in the following pattern:
*
**
***
****
*****
# Nested loop to print * in given pattern i = 1 while (i< = 5) : j=l while(j < = i): print "*", j = j+1 print i = i +1 RUN ››› * ** *** **** ***** ›››
Figure 12.22 Nested loop to print * in the given pattern
for Statement
Python provides for statement as another form for accomplishing control using loops. The for loop statement is used to repeat a statement or a block of statements a specified number of times. *•
A Python for loop has this general form.
for <var> in <sequence>: <body>
The body of the loop can be any sequence of Python statements. The start and end of the body is indicated by its indentation under the loop heading. The variable after the key¬word for is called the loop index. It takes on each successive value in the sequence, and the statements in the body are executed once for each value.
Usually, the sequence portion is a list of values. You can build a simple list by placing a sequence of expressions in square brackets. Some interactive examples help to illustrate the point:
>>> for i in [0,1,2,3]: print i 0 1 2 3 ››› for odd in [1, 3, 5, 7, 9]: print odd * odd 1 9 25 49 81 This example takes each item in little_list one at a time and prints it. ›››littlelist = ['the', 'quick', 'brown', 'fox'] ›››for the_item in little_list: ... print the_item, ""*",
the * quick * brown * fox *
The for loop specification ends with a colon, and after the colon (:) comes a block of statements which does something useful with the current element. Each statement in the block must be indented.
Operation of the for Loop
First the initialization expression is executed, then the test condition is examined. If the test expression is false to begin with, the statements in the body of the loop will not be executed at all. If the condition is true, the statements in the body of the loop are executed and, following that, the increment expression is executed. That is why the first number printed by the program is 0 and not 1. Printing takes place before the number is incremented by increment (++) operator. Finally the loop recycles and the test expres¬sion is queried again. This will continue until the test expression becomes false-number becomes 10 in this case —at which time the loop will end.
The rangeO Function
If you do need to iterate over a sequence of numbers, the built-in function range() is used. It generates lists containing arithmetic progressions:
›››range (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given end point is never part of the generated list; range(lO) generates a list of 10 values, the legal indices for items of a sequence of length 10.
It is possible to let the range start at another number, or to specify a different increment (even negative) called the step:
››› range(5, 10) [5, 6, 7, 8, 9] ››› range (0, 10, 3) [0, 3, 6, 9] ›››range(-10, -100, -30) [-10, -40, -70]
The for Loop and the range() Built-in Function
The for statement acts more like a traditional loop, in other words, a numerical counting loop.
››› for eachNum in [0, 1, 2, 3, 4, 5]: print eachNum RUN 0 1 2 3 4 5
Within our loop, eachNum contains the integer value that we are displaying and can use it in any numerical calculation we wish. Because our range of numbers may differ, Python provides the range() built-in function to generate such a list for us. It does exactly what we want, taking a range of numbers and generating a list.
›››for eachNum in range(6): print eachNum 0 1 2 3 4 5
Note that range(n) generates integers 0,1, 2,…, n-1. For example,
›››range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(start/ stop, step) generates a sequence if integers start,start+step, start+2*step, and so on up to, but not including, stop. For example, range(2, 8, 3) returns 2 and 5 (and not 8), while range(l, 11, 2) returns 1,3, 5, 7, 9.
range(start, stop) is the same as range(start, stop, 1).
A for loop over integers are written as:
for i in range(start, stop, step):
The following program writes the numbers from 1 to 100:
for number in range(1,101,1): print number
An integer to add to the current number to generate the next number. (This is called a step.) If left out, it defaults to 1. So above program will be written as:
for number in range(1,101): print number
Example 17
Program to print values 1 to 10 using for loop.
# A loop to print value 1 to 10 for i in range (1,1.1,1) : print i, RUN ››› 123456789 10 ›››
Figure 12.23 Program to print numbers 1 to 10
Example 18
Program to print even number series up to 20
Example 19
Program to print sum of even number series up to 10.
# Print sum of even number series up to 10 sum=0 for i in range(0,11,2): sum +=i print "Sum of even numbers <= ", i, "is", sum RUN ››› Sum of even numbers < = 0 is 0 Sum of even numbers < = 2 is 2 Sum of even numbers < = 4 is 6 Sum of even numbers < = 6 is 12 Sum of even numbers < = 8 is 20 Sum of even numbers < = 10 is 30 ›››
Figure 12.25 Program to print sum of even numbers
Example 20
Program to generate of multiplication table.
# Generation of Multiplication Table num =int(raw input("Enter number for which you want table : ")) for i in ranged,11): print num, 'X', i,'=', num * i RUN ››› Enter number for which you want table : 7 7X1 = 7 7 X 2 = 14 7 X 3 = 21 7 X 4 = 28 7 X 5 = 35 7 X 6 = 42 7 X 7 = 49 7 X 8 = 56 7 X 9 = 63 7 X 10 = 70 ›››
Figure 12.26 Program to print table of desired number
Example 21
Program to print letters of word
# Printing letters of word letter = raw_input("Enter word : ") for word in letter: print word RUN Enter word : Computer C o m P u t e r
Figure 12.27 Program to print letters of entered word
Example 22
Program to print ASCII code for entered message.
NESTED LOOPS
A loop may also contain another loop within its body. This form of a loop inside a loop is called nested loop. In a nested loop construction, the inner loop must terminate before the outer loop can be ended.
Example 23
Write a program to print following pyramid using for loop:
* *
* * *
* * * *
* * * * *
# Nested for loop n = int(raw_input("Enter a number to form pyramid :")) for i in range(l,n): for j in range(l,i): print , # comma (,) is used to print on the same line print # print without comma!,) is used to print in next line RUN ››› Enter a number to form pyramid :7 * * * * * * * * * * * * * * * ›››
Figure 12.29 Nested loop
The print statement by default automatically add a Newline character at the end of every line. This can be suppressed by terminating the print statement with a comma (,).
JUMP STATEMENTS
Those statements which transfer the program control, unconditionally with in the pro¬gram, from one place to another are called jump statements. These statements include the following statements: ,
(a) break Statement
(b) continue Statement
(c) pass Statement
break Statement
The break statement causes an immediate exit from the innermost loop structure. The break statement transfers control out of a while or for, statement. Break is mostly required, when due to some external condition, we need to exit from a loop.
If you need to come out of a running program immediately without letting it to perform any further operation in a loop, then you can use break statement. The break statement exits out of the current loop (for or while) and transfers control to the statement immediately following the control structure.
Figure 12.30 shows the use of break statement.
Example 24
# Demo of using break statement count = 1 while(count > 0): print "Count count count += 1 #Breaks out of the while loop when count >5 if(count>5): break print "End of Program" RUN ››› Count : 1 Count : 2 Count : 3 Count : 4 Count : 5 End of Program ›››
Figure 12.30 Demo of using break statement
Note that in the following example break statement causes Python to immediately exit the loop so it will print COMP.
Example 25
# Demo of using break statement for ch in 'COMPUTER': if ch == 'U': break print ch ››› C O M P ›››
Figure 12.31 Demo of using break statement
continue Statement
The continue statement forces the next iteration of the loop to take place, skipping any statement(s) following the continue statement in the body of the loop, i.e., continue statement jumps back to the top of the loop.
The syntax of the continue statement is :
continue
The statement continue can be considered as the opposite of break statement, continue statements used to skip the rest of the body of the loop and the next iteration after the loop begin immediately.
Figure 12.32 shows the use of continue statement. At the top of the loop, the while con-dition is tested and loop is entered again, if it’s true. So, when count is equal to 5, the program does not get to the print count statement. The number 5 is skipped with a continue statement and loop ends through a break statement.
Example 26
# Demo of continue statement count=0 while True: counts count +1 # End loop if count is greater than 10 if count > 10: break # Skip 5 if count == 5: continue print count RUN ››› 1 2 3 3 6 7 8 9 7 ›››
Figure 12.32 Demonstration of using continue statement
Example 27
# Demo of using continue statement for ch in 'COMPUTER': if ch == 'U': continue print ch ››› C 0 M P T E R ›››
Figure 12.33 Demonstration of using continue statement Note that U is skipped in the above program due to use of continue statement.
Difference between break and continue statement
The continue statement skips the remainder of the statements in the body of a loop and starts immediately at the top of the loop again.
A break statement in the body of a loop terminates the loop. It exits from the immedi¬ately containing loop.
break and continue can be used in both for and while statements.
pass Statement
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet. For example,
if condition: pass
It can be useful as a placeholder while you are writing code. For example, you may have written an if statement and you want to try it, but you lack the code for one of your blocks. Consider the following:
if name == 'Ram': print 'Welcome!' elif name == 'Ramesh': # Not finished yet... elif name == 'Rohan': print 'Access Denied'
This code won’t run because an empty block is illegal in Python. To fix this, simply add a pass statement to the middle block:
if name == 'Ram': print 'Welcome!' elif name == 'Ramesh': # Not finished yet... pass elif name = = 'Rohan': print 'Access Denied'
Solved Exercise
Question 1.
What is conditional branching?
Answer:
Conditional branching, a program is to decide whether or not to execute the next statement(s) based on the resultant value of the current expression. For example, go to IInd year, if you pass Ist year exams, else repeat Ist year.
Question 2.
What is looping?
Answer:
Looping, the program performs a set of steps or operations repeatedly till a given condition is obtained. Looping for example, add 1 to number x till current value of x becomes 100 is also called iteration. Iteration is a process of executing a statement or a set of statements repeatedly, until some specific condition is specified.
Question 3.
Explain if statement.
Answer:
The statement if tests a particular condition. Whenever that condition evaluates to true, an action or a set of actions are executed. Otherwise, the actions are ignored.
Question 4.
Explain range() function with an example.
Answer:
If you do need to iterate over a sequence of numbers, the built-in function range() is used. It generates lists containing arithmetic progressions:
››› range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given end point is never part of the generated list; range(lO) generates a list of 10 values, the legal indices for items of a sequence of length 10.
Question 5.
What is the similarity and difference between break and continue statements. Similarity: Both break and continue are jump statements.
Answer:
Difference: The break statement terminates the entire loop execution where as con¬tinue statement is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a continue statement is encountered. Rather, the remaining loop statements are skipped and the computation proceeds directly to the next pass through the loop.
Question 6.
What is the function of break statement in a while or for loop?
Answer:
If a break statement is included in a while, or for loop, then control will immediately be transferred out of the loop when the break statement is encountered. This provides a convenient way to terminate the loop if an error or other irregular condition is detected.
Question 7.
Write a program to print the first few terms in a Fibonacci series.
Answer:
# Generation of Fibonacci series number =int(rawinput("Enter number up to which you want fabonacci series : ")) numl=0 num2 = 1 print numl print num2 for i in range(1,number): num3 = numl+num2 print num3 numl,num2 = num2, num3 RUN ››› Enter number up to which you want fabonacci series : 10 0 1 1 2 3 5 8 13 21 34 55 ›››
Figure 1 Program for Q7
Question 8.
Give the output of the following programs:
(a)
x=2 if x == 3: print "X equals 3." elif x == 2: print "X equals 2." else: print "X equals something else." print "This is outside the 'if '."
(b)
x = 3 while x < 10: if x > 7: x += 2 continue x = x + 1 print "Still in the loop." if x == 8: break print "Outside of the loop."
(c)
for x in range(10): if x > 7: x += 2 continue x = x + 1 print "Still in the loop, if x == 8: break print "Outside of the loop."
The output of the (a), (b) and (c) are as follows:
Answer:
››› X equals 2. This is outside the 'if' . ›››
Figure 2 Output for Q8(a)
Answer:
››› Still in the loop. Still in the loop. Still in the loop. Still in the loop. Still in the loop. Outside of the loop. ›››
Figure 3 Output for Q8(b)
Answer:
››› Still in the loop. Still in the loop. Still in the loop. Still in the loop. Still in the loop. Still in the loop. Still in the loop. Still in the loop. Outside of the loop. ›››
Figure 2 Output for Q8(c)
Question 9.
Write a program using while loop that asks the user for a number, and prints a countdown from that number to zero. Note: Decide what your program will do, if user enters a negative number.
Answer:
# Program to print count down of entered number up 0 count = 0 number = int(rawinput("Enter the number : ")) if(number < 0): print "Number entered below 0. Aborting!" while(number >= 0): count = count +1 print "\nThe number is ", number number = number - 1 RUN >>> Enter the number : 5 The number is 5 The number is 4 The number is 3 The number is 2 The number is 1 The number is 0 ======================== RESTART =========================== Enter the number : -5 Number entered below 0. Aborting! ›››
Figure 5 Program for Q9
Question 10.
Print all multiples of 13 that are smaller than 100. Use the range function in the fol-lowing manner: range (start, end, step) where “start” is the starting value of the counter, “end” is the end value and “step” is the amount by which the counter is increased each time.
Answer:
# Program to print multiples of 13 smaller than 100 print "Multiples of 13 are : " for i in range(13,100,13): print i, RUN ››› Multiples of 13 are : 13 26 39 52 65 78 91 ›››
Figure 6 Program for Q10
Question 11.
Write a program to enter a digit from the keyboard and then print the sum of the values of the digits of the number. It also reverses the number.
Answer:
#Program to print reverse and sum of digits sum = 0 rev = 0 number=int(rawinput("Enter a number: ")) n = number while number: digit = number % 10 sum += digit; rev = rev * 10 + digit number /= 10 print "Reverse of number is : ",rev print "Sum of digits of the number is : ",sum RUN ››› Enter a number: 674 Reverse of number is : 476 Sum of digits of the number is : 17 ›››
Figure 7 Program for Qll
Question 12.
What do you mean by flow-of-control statements.
Answer:
Statements that are executed one after the other or the statements that are executed sequentially is the normal flow-of-control statements in a program
Question 13.
What do you mean by selection statements?
Answer:
In some programs, you may need to change the sequence of execution of instructions according to specified conditions is called selection statements.
Question 14.
What is the minimum number of iteration that while loop could make?
Answer:
while loop could make 0 iteration.
Question 15.
What is the difference between entry controlled loop and exit controlled loop?
Answer:
In an entry controlled loop, the loop control condition is evaluated at the entry point of the loop. However, in an exit controlled loop, the loop control condition is evalu¬ated at the exit point of the loop.
If the loop control condition is false in the beginning, the entry control loop is never executed. However, the exit control loop would be executed at least once.
Question 16.
What are jump statements?
Answer:
Jump statements are statements that allow you to transfer control to another part of your program.
Question 17.
What is Iteration?
Answer:
It is a process of executing a statement or a set of statements repeatedly, until some specific condition is specified.
Multiple Choice questions
Question 1.
The operator & is used for:
(a) Bitwise AND
(b) Bitwise OR
(c) Logical AND
(d) Logical OR
Answer: (a)
Question 2.
A “Python” expression contains relational, assignment and arithmetic operators. There are no parentheses used. They will be evaluated in which of the following
order:
(a) Assignment Relational Arithmetic
(b) Arithmetic Relational Assignment
(c) Relational Arithmetic Assignment
(d) Assignment Arithmetic Relational
Answer: (b)
Question 3.
We can go back to the start of the loop by using:
(a) break
(b) continue
(c) pass
(d) None of these
Answer: (b)
Question 4.
The && and | | operators:
(a) Compare two numeric values
(b) Combine two numeric values
(c) Compare two boolean values
(d) None of the above
Answer: (c)
Question 5.
The condition on which the execution or exit of the loop depends is called :
(a) exit condition
(b) test condition
(c) Both (a) and (b)
(d)None of these
Answer: (c)