Loops and Conditional Statements - Python: Programming Language for Beginners - Learn In A Day! (2015)

Python: Programming Language for Beginners - Learn In A Day! (2015)

Chapter 7. Loops and Conditional Statements

The main purpose of using loops is to avoid laborious work and save a lot of time and energy. Just imagine if a calculation had to be carried out 100 times. It would be really difficult to type it 100 times, so in such cases loops are beneficial.

While loop:

Ex:

a = 0

while a < 10:

a = a + 1

print a

O/p:1 2 3 4 5 6 7 8 9

While loop syntax using indentation:

while {condition for the loop to continue}:

{what to do in the loop}

{is it indented, usually four spaces}

{the code here is not looped}

{because it isn't indented}

Conditional Statements

These are used in order to check if the given condition is satisfied or not.

Ex1:

a = 1

if a > 5:

print "This shouldn't happen."

else:

print "This should happen."

O/p: This should happen

Ex2:

z = 4

if z > 70:

print "Very Wrong"

elif z < 7:

print "This is normal"

O/p: This is normal

It is to be noted that the else if is shortened to elif in python. We can use multiple elif’s but only one else statement. End of every sentence should have a colon. Even indentation sometimes helps to differentiate the statements that are in the conditional statements or not.

Ex:

a = 10

while a > 0:

print a

if a > 5:

print "Big number!"

elif a % 2 != 0:

print "The number is odd”

print "Not greater than 5”

else:

print "Smaller than 5”

print "nor is it odd"

print "feeling special?"

a = a - 1

print "we just made 'a' value lesser”

print "and unless a!>0 loop again”

print "well, it seems as if 'a'>0”

print “loop is now over”

For loop

It is used to access the items in the list.

SYNTAX: for iterating_var in sequence:

statements(s)Example:

#!/usr/bin/python

for letter in 'Acting': # First Example

print 'Current Letter :', letter

fruits = ['grape', 'pineapple', 'orange']

for fruit in fruits: # Second Example

print 'Current fruit :', fruit

OUTPUT:

Current Letter: A

Current Letter: c

Current Letter: t

Current Letter: i

Current Letter: n

Current Letter: g

Current fruit: grape

Current fruit: pineapple

Current fruit: orange