Table of contents |
|
Introduction |
|
Selection |
|
Indentation in Python |
|
Repetition in Programming |
|
Break and Continue Statement |
|
Nested Loops |
|
When we write a program in Python, the computer follows the instructions exactly as they are written, one after the other, from the beginning to the end. This is similar to how a bus driver follows a specific road to reach the school, milestone by milestone. This basic way of executing instructions is called "sequence."
Program: Program to print the difference of two numbers.
#Program to print the difference of two input numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
diff = num1 - num2
print("The difference of",num1,"and",num2,"is",diff)
Output:
Enter first number 5
Enter second number 7
The difference of 5 and 7 is -2
A decision involves selecting from one of the two or more possible options. In programming, this concept of decision making or selection is implemented with the help of if..else statement.
Introduction to Selection in Programming
Example:
age = int(input("Enter your age "))
if age >= 18:
print("Eligible to vote")
A variant of if statement called if..else statement allows us to write two alternative paths and the control condition determines which path gets executed. The syntax for if..else statement is as follows.
if condition:
statement(s)
else:
statement(s)
Let us now modify the example on voting with the condition that if the age entered by the user is greater than 18, then to display that the user is eligible to vote. Otherwise display that the user is not eligible to vote.
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
Now let us use the same concept to modify program, so that it always gives a positive difference as the output. From the flow chart in Figure, it is clear that we need to decide whether num1 > num2 or not and take action accordingly.
We have to specify two blocks of statements since num1 can be greater than num2 or vice-versa as shown in program 6-2.
Many a times there are situations that require multiple conditions to be checked and it may lead to many alternatives. In such cases we can chain the conditions using if..elif (elif means else..if).
Program: Program to print the positive difference of two numbers.
Output:
Enter first number: 5
Enter second number: 6
The difference of 5 and 6 is 1
In many programming languages, code blocks are enclosed within curly brackets. However, Python adopts a different approach by using indentation to define blocks of code, including nested structures. Indentation refers to the leading whitespace (comprising spaces and tabs) at the beginning of a line. In Python, statements with the same level of indentation are grouped together into a single block of code.
The Python interpreter enforces indentation levels strictly and will raise a syntax error if the indentation is not consistent. It is common practice to use a single tab (or a consistent number of spaces) for each level of indentation.
For example, in an if-else statement, the blocks of code following the conditions are indented to the same level to indicate they belong to the respective blocks.
Example: Program to find the larger of the two pre-specified numbers.
Repetition in programming is similar to tasks we do regularly, like paying an electricity bill every month. Just as this task repeats, programming allows us to repeat a set of instructions using looping constructs.
Life Cycle of a Butterfly
Example: Printing Numbers
Initially, if asked to print the first five natural numbers, one might write:
print(1)
print(2)
print(3)
print(4)
print(5)
Output:
1
2
3
4
5
However, to print the first 100,000 natural numbers, writing 100,000 print statements would be inefficient. Instead, using a loop is a better solution.
Looping Constructs
The 'for' statement is utilized to iterate over a specified range of values or a sequence. During each iteration of the for loop, the control variable checks whether each value in the range has been traversed. When all items in the range have been exhausted, the statements within the loop are not executed, and control is transferred to the statement immediately following the for loop.
When using a for loop, the number of iterations is known in advance.
(A) Syntax of the For Loop
Program: Program to print the characters in the string ‘PYTHON’ using for loop.
#Print the characters in word PYTHON using for loop
for letter in 'PYTHON':
print(letter)
Output:
P
Y
T
H
O
N
Program: Program to print the numbers in a given sequence using for loop.
#Print the given sequence of numbers using for loop
count = [10,20,30,40,50]
for num in count:
print(num)
Output:
10
20
30
40
50
(B) The Range() Function
The range() function is a built-in function in Python. Its syntax is: range([start], stop[, step]). This function generates a sequence of integers starting from the specified start value up to, but not including, the stop value, with increments or decrements defined by the step value.
We will explore functions in the next chapter, but for now, understand that functions use parameters to perform operations. In the range() function, start, stop, and step are its parameters.
The start and step parameters are optional. If start is not provided, it defaults to 0. If step is not specified, it defaults to 1, meaning the sequence increases by 1 at each step. All parameters in the range() function must be integers. The step value can be positive or negative but cannot be zero.
Example: Using the range() Function
The function range() is often used in for loops for generating a sequence of numbers.
Program: Program to print the multiples of 10 for numbers in a given range.
#Print multiples of 10 for numbers in a given range
for num in range(5):
if num > 0:
print(num * 10)
Output:
10
20
30
40
A “while” loop in programming is used to execute a block of code repeatedly as long as a specified condition is true. Here’s a detailed explanation of how it works:
The basic syntax of a “while” loop is as follows:
while test_condition:
Program: Program to print first 5 natural numbers using while loop.
#Print first 5 natural numbers using while loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Program: Program to find the factors of a whole numberusing while loop.
Note:
Looping constructs help programmers efficiently repeat tasks. In some cases, when a specific condition is met, we may need to exit the loop permanently or skip certain statements before continuing. This can be accomplished using the break and continue statements. Python offers these statements to provide programmers with greater control over the flow of execution in a program.
Program: Program to demonstrate use of break statement.
Output:
Num has value 1
Num has value 2
Num has value 3
Num has value 4
Num has value 5
Num has value 6
Num has value 7
Encountered break!! Out of loop
Note: When the value of num reaches 8, the break statement is triggered, and the for loop ends.
Program: Find the sum of all the positive numbers entered by the user. As soon as the user enters a negative number, stop taking in any further input from the user and display the sum.
Output:
Enter numbers to find their sum, negative number ends the loop:
3
4
5
-1
Sum = 12
When a continue statement is executed, it skips the remaining code inside the loop for the current iteration and jumps back to the start of the loop for the next iteration. If the loop's condition is still true, the loop will be executed again; otherwise, the control will move to the statement following the loop.
Program: Program to demonstrate the use of continue statement.
Output:
Num has value 1
Num has value 2
Num has value 4
Num has value 5
Num has value 6
End of loop
Nested loops are loops that exist within another loop. In Python, there are no restrictions on the number of loops that can be nested within each other, nor are there restrictions on the types of loops that can be nested. For example, a for loop can be nested within a while loop, and vice versa.
Program: Program to demonstrate working of nested for loops.
Output:
Python does not impose any restriction on how many loops can be nested inside a loop or on the levels of nesting. Any type of loop (for/while) may be nested within another loop (for/while).
Program: Program to print the pattern for a number input by the user.
Output:
33 docs|11 tests
|
1. What is the importance of indentation in Python? | ![]() |
2. How do break and continue statements work in Python? | ![]() |
3. What are nested loops, and how are they used in Python? | ![]() |
4. How does selection control flow work in Python? | ![]() |
5. What are the common pitfalls to avoid with loops in Python? | ![]() |