0% found this document useful (0 votes)
60 views14 pages

Unit - 2 Complete-Conditional Statements and Loops

Uploaded by

adityapratap.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views14 pages

Unit - 2 Complete-Conditional Statements and Loops

Uploaded by

adityapratap.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

PYTHON NOTES | Rahul Virmani

UNIT-2
Conditionals: Conditional statement in Python (if-else statement, its working and execution),
Nested-if statement and Elif statement in Python, Expression Evaluation & Float Representation.

Loops: Purpose and working of loops , While loop including its working, For Loop , Nested Loops
, Break and Continue

1. Control Flow: It is the order in which the code of the program executes, the control flow
of a program is executed by
a. The conditional statements
b. The Iterative statement (Generally called loops)

1.1. The Conditional Statements- In order to write the useful programs, the ability to check the
conditions and change the behaviour of the program is important. This ability is obtained by
putting conditional statements in the program.

1.2. The if statement is one such statement commonly used even in our daily general language.

Let’s say for e.g. – In a grading system in class, the following guidelines are followed:
 Excellent – If student obtains more than 95%.
 Good – If student scores above 80% but less than 95%.
 Average -- If student scores above 60% but less than 80%.
 Below Average-- If student scores less than 60 %.

The Flowchart of the above example may be given as :-

Conditional
Statement.

1|Page
PYTHON NOTES | Rahul Virmani

Like every conditional statement, the if statement actually evaluates if the condition is TRUE or
FALSE. The statement is actuated (within the block) only if the condition expression is TRUE.

NOTE- In PYTHON, the colon (:) is used to initialize the loop or a condition and the indentation is
used to create a block of code running under a loop or a condition. (Similar to Curly Braces ( { ) in
C, C++).

The syntax of the if statement can be seen with a simple example.

Example-

Write a Program to Print “x is positive”, if x > 0

Initialization
Keyword

Indentation
Condition Statement

Statement to be executed only


if the condition is TRUE.

if Logic Flowchart.

Example -

Now, in this Example, the number entered is


even, so the condition is true; hence the code
within the block i.e. “x is even” is executed along
with the output statement outside of the if block.

2|Page
PYTHON NOTES | Rahul Virmani

Now, in this Example, the number entered is ODD


NOT even, so the condition is false; hence the
code within the block i.e., “x is even” is not
executed but the output statement outside of the
if block.

1.3. Alternative Execution – if else statement, is basically an alternative execution in which there
are two possibilities, and the condition determines that which one will get executed.
The syntax for the if else statement can be given as:

Conditional Statement

Statement 1, to be
executed when the
condition is TRUE

Statement 2, to be
Keyword
executed when the
The condition is FALSE.
if-else logic, flowchart.

Example –

If the entered number is EVEN ---


-----

If the entered number is ODD ----


---

3|Page
PYTHON NOTES | Rahul Virmani

1.4. Chained Conditionals— if…elif…else statement. Sometimes there are multiple


possibilities, and we need more than two branches. One way is to use a chained conditional.

Elif : an abbreviated form of ‘else-if’. Again, exactly one branch will be executed.

If-elif-else logic Flowchart

NOTE- There is no limit on the number of Elif statement. But If there is an else clause, it has
to be at the end. However, there is no mandate that an else statement has to be used.

Example – Lets take the initial example we took, In a grading system in class, the following
guidelines are followed:
 Excellent – If student obtains more than 95%.
 Good – If student scores above 80% but less than 95%.
 Average -- If student scores above 60% but less than 80%.
 Below Average-- If student scores less than 60 %.

1.5. Nested Conditionals: one condition can also be nested within another. We could have
written the above example like this:

4|Page
PYTHON NOTES | Rahul Virmani

Also, the flowchart of the if…elif…else statement; can be restructured for nested conditionals.

Nested Conditional Flowchart

The nested conditionals, although can be easily thought of by the user, the indentations to be used
while coding make the code readability bit tough. Hence, it’s a good idea to avoid the nested if-
else logic.

Example – Write a Program to take age as input from user and print. “You are not an adult”, if age
is less than 18. Otherwise print “You are an adult”. Also check that age cannot be 0, if so print “age
can’t be 0”.

5|Page
PYTHON NOTES | Rahul Virmani

ITERATIVE /LOOPING STATEMENT


2.1. Updating of variables
A common pattern in an assignment statement is updating of variable, where the updated value
of the variable depends on the old.
x=x+1 or x+=1
This means that the current value of x, add 1 and then update x with new value.
However, if we try to update a variable that doesn’t exist, you get an error.

So, before you update the variable, you have to initialize it using a simple assignment statement:

 Updating, the variable by adding 1 is increment, subtracting 1 is called decrement.

 Sometimes, we need to perform certain operations again and again. (A Loop)

6|Page
PYTHON NOTES | Rahul Virmani

For E.g.- Let’s take a grading assignment as already


discussed above. Suppose a teacher wants to grade a
class of 60 students, he has to consider the marks of the
students, grade it and run the process again and again
for all students, i.e. he has to do the grading again and
again till all the 60 students have been graded. This is
termed as iteration/Looping

There are four types of loops in Python namely:

 While Loop.
 Nested While Loop.
 For Loop.
 Nested For Loop.

2.2. WHILE LOOP

If a loop has to repeat the block of code till the condition is true, a WHILE loop is used.

a. Boolean Expression is checked first.


b. The loop is entered only if the condition is TRUE.
c. After one iteration, the trueness of the expression is checked again.
d. The process continues till the expression evaluates FALSE

Example – While n is greater than 0, display the value of n and reduce the value by 1. Print
“Blast Off”, when you get 0.

Now, this loop ran 5 times , this WHILE loop is said to be


‘counter-controlled’ statement and the iteration variable acts
as a counter and Blast Off was printed when the condition was
false as 1-1=0

7|Page
PYTHON NOTES | Rahul Virmani

The variable that changes its value every time, is called iteration variable. If there is no iteration
variable then loop will run infinitely, resulting in an infinite loop.

 Example of an infinite loop:

DON’T RUN THIS

 Now, in this case the condition is always true so the loop will run infinitely.

Key points of While Loop

a) Firstly, the Boolean expression is checked.


b) If the expression is ‘False’ the WHILE loop is not initiated, and the program directly jumps
to next line after the loop.
c) If the expression is ‘TRUE’ the WHILE loop is initiated and one cycle of the entire loop is
run, this cycle is termed as iteration.
d) After one iteration, the expression on the loop is tested again if TRUE then WHILE loop is
run again. This process continues till the WHILE loop condition becomes FALSE.
e) If the expression never become FALSE, an infinite loop will run.
f) The beginning of the while loop is marked by a level of indentation and the end of the loop
is marked by first unindented line.

NOTE: - You can combine the WHILE with and ELSE


statement, which will be executed if the test condition
(Boolean expression) is False. For E.g. – the above example
can also be written as

8|Page
PYTHON NOTES | Rahul Virmani

Example - Write a Program to find the square of the number from 1 to 10.

Range function- range () is a built-in function, which gives a sequence of numbers.

By default,

If only a single value in the range function is given. Only the Stop value is given then It has a
default start value of 0, with a step of 1.

9|Page
PYTHON NOTES | Rahul Virmani

If only two values in the range function are given. The Start and Stop value are given in order,
with a step of 1(default).

If a Range function has three arguments, then start value, stop value and the step value are all
given. For e.g.

Example- Write a Program to print the even numbers between 1 and 100.

 Note- Here mentioning List is a typecasting, it can be set or a tuple as well.

2.3. FOR LOOP

Unlike while loops, the for loop is used when we need to repeat the block of the code for fixed
number of times. In Python, the for loop is repeated for all the members of a sequence as in set,
list or tuple in order, executing the block of code every time, till no element is left in the sequence.
Unlike the while loop in which the condition is tested for every iteration.

10 | P a g e
PYTHON NOTES | Rahul Virmani

Example- Write a Program to add all numbers in a list.

Example- Determine the output of following program if a=10.

Example- Table of 5 using for loop.

2.4. NESTED WHILE LOOP

When a while loop is used inside a while loop, it’s


called nested while loop. Any number of while
loop can be used in a while loop. The outer loop
is called Main while loop while the nested one is
referred as inner loop.

11 | P a g e
PYTHON NOTES | Rahul Virmani

Example- The nested while loop can be easily understood by the following example.

Question- What should be the values of num1 and num2 in the given code snippet, if the expected
output is 4?
a. 16,6
num1=
num2= b. 12,5
while (num1>=2): c. 8,2
if (num1>num2):
d. 16,2
num1=num1/2
else:
print(num1)

2.5. NESTED FOR LOOP

When a for loop is used inside a for loop, it’s


called a nested for loop. In python any
number of for loops can be used inside a main
for loop.

Example-

The loop for the variable ‘i will run 5


times, and the loop for variable j will run
2 times. Hence, total the program will
run for 5*2= 10 times.

The variable ‘i will have values from 1 to


5 , whereas the variable j will have
values from 1 to 2.
12 | P a g e
** Recall range() function.
PYTHON NOTES | Rahul Virmani

Question- What is the difference between the given two snippets?

VS

SUMMARY TILL NOW …(Loops and Iteration)

1. While loop is used to iterate the block of codes until the given condition is True.
2. While loop in another While loop is called nested while loop.
3. Range() function returns a sequence of numbers.
4. A for loop is used for iterating over a sequence (string, list, tuple, set, etc-).
5. Nested for loop allows us to create one loop inside the other loop.

2.5. Jump Statements


The jump statements are generally used to terminate, skip or take an early exit from the loop.
There are two common jump statements-
1. Break.
2. Continue.
2.5.1. Break Statement
In the Python programming, the loops or
iterations are used to execute a block of
code, the loop will be executed only if the
condition is true. Now, if we want to
interrupt an iteration within the loop, the
break statement is used. The break
statement if used is used to quit the
running loops immediately and the code
jumps to the next following statement.
The example is as follows:

13 | P a g e
PYTHON NOTES | Rahul Virmani

2.5.2. Continue Statement


Now as the break statement terminates the
iteration immediately and the code gets out of
the loop, but in certain cases if you need to
skip a particular iteration and continue to run
the loop for next iteration, from the start of the
loop the continue statement is used. The
example is:

Note that for i=2, the iteration is


skipped while all other iterations
have run.

Other than break and continue, there is another statement called pass statement; commonly known
as do-nothing statement. The continue statement skips the iteration while pass statement
continues with the loop, just wastes the execution time. The pass statement does nothing.

Summary… Jump Statements

1. Jump statement are used to alter the flow of the loop, i.e., if you wish to skip an iteration
(continue) or just exit the loop on a certain condition (break).

14 | P a g e

You might also like