2 - If While and For
2 - If While and For
• and
• if True:
• print('Hello'); a = 5
• both are valid and do the same thing. But the former
style is clearer.
• Incorrect indentation will result into Indentation Error.
• Single Statement Suites
• Python requires the block to be indented. If the block
contains just one statement, some programmers will place
it on the same line as the if; for example, the following if
statement that optionally assigns y
• if x < 10:
y=x
• could be written
if x < 10: y = x
• Here is an example of a one-line if clause −
• Example: 5
• var = 100
• if ( var == 100 ) : print "Value of expression is 100“
• print "Good bye!”
• Output is:
Value of expression is 100
Good bye!
Example 1:
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
When the above code is
executed, it produces the
following result –
1 - Got a true expression
value
100
Good bye!
Example 1a Find the quotient
The output is :
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
Example
# Get two integers from the user
dividend, divisor = eval(input('Please enter two numbers to divide: '))
# If possible, divide them and report the result
if divisor != 0:
print(dividend, '/', divisor, "=", dividend/divisor)
else:
print('Division by zero is not allowed')
Example
value = int(input("Please enter an integer value in the range 0...10: "))
if value >= 0: # First check
if value <= 10: # Second check
print(value, "is in range")
else:
print(value, "is too large")
else:
print(value, "is too small")
print("Done")
• Example nested if/else statement:
value = eval(input("Please enter an integer in the range 0...5: "))
if value < 0:
print("Too small")
else:
if value == 0:
print("zero")
else:
if value == 1:
print("one")
else:
if value == 2:
print("two")
else:
if value == 3:
print("three")
else:
if value == 4:
print("four")
else:
if value == 5:
print("five")
else:
print("Too large")
print("Done")
The elif Statement
• The elif statement allows you to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions
evaluates to TRUE.
• Similar to 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. syntax
• if expression1:
statement(s)
• elif expression2:
statement(s)
• elif expression3:
statement(s)
• else:
statement(s)
• Core Python does not provide switch or case statements as in other
languages, but we can use if..elif...statements to simulate switch case
as follows −
Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows
Example 3
var = 100
if var == 200:
print ("1 - Got a true expression value")
print (var)
elif var == 150:
print ("2 - Got a true expression value")
print (var)
elif var == 100:
print ("3 - Got a true expression value")
print (var)
else:
print ("4 - Got a false expression value")
print (var)
print ("Good bye!")
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
Example 6 c
n=1
stop = int(input('feed the value stop = '))
while n <= stop:
print(n)
n += 1
Using else Statement with Loops
• Python supports to else statement associated with a loop statement.
• If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.
• The following example illustrates the combination of an else
statement with a while statement that prints a number as long as it is
less than 5, otherwise else statement gets executed
• Example 7
• count = 0
• while count < 5:
• print (count, " is less than 5“)
• count = count + 1
• else:
• print (count, "is not less than 5“)
• Single Statement Suites
• Similar to the if statement syntax, if
your while clause consists only of a single
statement, it may be placed on the same line as
the while header.
• Syntax and example of a one-line while clause
• flag = 1
while (flag): print 'Given flag is really true!‘
print "Good bye!"
• It is better not try above example because it goes
into infinite loop and you need to press CTRL+C
keys to exit.
Parameters for ‘for’ loop
range() Parameters
• range() takes mainly three arguments having the same use
in both definitions:
• start - integer starting from which the sequence of integers
is to be returned
• stop - integer before which the sequence of integers is to
be returned.
The range of integers end at stop - 1.
• step (Optional) - integer value which determines the
increment between each integer in the sequence
• return value from range()
• range() returns an immutable sequence object of numbers
depending upon the definitions used:
• range(stop)
• Returns a sequence of numbers starting from 0 to stop - 1
• Returns an empty sequence if stop is negative or 0.
• range(start, stop[, step])
• The return value is calculated by the following
formula with the given constraints:
• r[n] = start + step*n (for both positive and negative
step) where, n >=0 and r[n] < stop (for positive step)
where, n >= 0 and r[n] > stop (for negative step)(If
no step) Step defaults to 1.
• Returns a sequence of numbers starting
from start and ending at stop - 1.
• (if step is zero) Raises a ValueError exception
• (if step is non-zero) Checks if the value constraint is
met and returns a sequence according to the formula
If it doesn't meet the value constraint,
• Empty sequence is returned.
Example : How range works in Python?
# empty range
print(list(range(0)))
# using range(stop)
print(list(range(10)))
When you run the program, the output will be:
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Example:
# using range(start, stop)
start = 2
stop = 14
step = 2
print(list(range(start, stop, step)))
When you run the program, the output will be:
[2, 4, 6, 8, 10, 12]
• The for Statement
• The while loop is ideal for indefinite loops.
• programmer cannot always predict how many times a
while loop will execute. We have used a while loop
to implement a definite loop, as in
• n=1
• while n <= 10:
• print(n)
• n += 1
• The print statement in this code executes exactly 10
times every time this code runs. This code requires
• three crucial pieces to manage the loop:
• • initialization: n = 1
• • check: n <= 10
• • update: n += 1
Python range() function
• Python provides a more convenient way to express a
definite loop. The for statement iterates over a range of
values. These values can be a numeric range, or, as we
shall, elements of a data structure like a string, list, or
tuple. The above while loop can be rewritten
• for n in range(1, 11):
• print(n)
• The expression range(1, 11) creates an object known as
an iterable that allows the for loop to assign to the
variable n the values 1, 2, . . . , 10. During the first
iteration of the loop, n’s value is 1 within the block.
• In the loop’s second iteration, n has the value of 2. The general
form of the range function call is
• range( begin,end,step )
• Where begin is the first value in the range; if omitted, the default
value is 0; the end value may not be omitted, change is the
amount to increment or decrement; if the change parameter is
omitted, it defaults to 1 (counts up by ones)
• begin, end, and step must all be integer values; floating-point
values and other types are not allowed.
• The range function is very flexible. Consider the following loop
that counts down from 21 to 3 by threes:
• for n in range(21, 0, -3):
print(n, '', end='')
• It prints
• 21 18 15 12 9 6 3
Python len()
• The len() function returns the number of items (length)
of an object.
• The syntax of len() is:
• len(s)
• len() Parameters
• s is a sequence (string, bytes, tuple, list, or range)
• Return Value from len()
The len() function returns the number of items of an
object.
Failing to pass an argument or passing an invalid
argument will raise a TypeError exception
Example 8
# use of string for ‘for’ statement
for letter in 'Python':
print 'Current Letter :', letter
# use of list for ‘for’ statement
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('Current fruit :', fruit)
print ("Good bye!“)
#Example.12
# First Example
for letter in 'Python':
if letter == 'h':
break
print ('Current Letter :', letter )
Output:
• Current Letter : P
• Current Letter : y
• Current Letter : t
# Second Example
var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!”)
*
***
*****
*******
*********
***********
*************
if i < j:
if j < k:
i=j
else:
j=k
else:
if j > k:
j=i
else:
i=k
print("i =", i, " j =", j, " k =", k)
What will the code print if the variables i, j, and k have the
following values?
(a) i is 3, j is 5, and k is 7
(b) i is 3, j is 7, and k is 5
(c) i is 5, j is 3, and k is 7
(d) i is 5, j is 7, and k is 3
(e) i is 7, j is 3, and k is 5
(f) i is 7, j is 5, and k is 3
5. Consider the following Python program that prints one line of text:
val = eval(input())
if val < 10:
if val != 5:
print("wow ", end='')
else:
val += 1
else:
if val == 17:
val += 10
else:
print("whoa ", end='')
print(val)
What will the program print if the user provides the following input?
(a) 3
(b) 21
(c) 5
(d) 17
(e) -5
6. Write a Python program that requests five integer values from the
user. It then prints the maximum and minimum values entered. If the
user enters the values 3, 2, 5, 0, and 1, the program would indicate
that 5 is the maximum and 0 is the minimum. Your program should
handle ties properly;
for example, if the user enters 2, 4 2, 3 and 3, the program should
report 2 as the minimum and 4 as maximum.
7. Write a Python program that requests five integer values from the
user. It then prints one of two things: if any of the values entered are
duplicates, it prints "DUPLICATES"; otherwise, it prints
"ALL UNIQUE".
8. How many asterisks does the following code fragment print?
a=0
while a < 10:
print('*', end='')
a += 1
print()
11. How many asterisks does the following code fragment print?
a=0
while a < 10:
b = 0;
while b < 5:
print('*', end='')
b += 1
print()
a += 1
12. How many asterisks does the following code fragment print?
a=0
while a < 10:
if a % 5 == 0:
print('*', end='')
a += 1
print()
13. How many asterisks does the following code fragment print?
a=0
while a < 10:
b=0
while b < 10:
if (a + b) % 2 == 0:
print('*', end='')
b += 1
print()
a += 1
10. How many asterisks does the following code fragment print?
a=0
while a < 5:
b=0
while b < 2:
c=0
while c < 2:
print('*', end='')
c += 1
b += 1
a += 1
print()
11. How many asterisks does the following code fragment print?
for a in range(100):
print('*', end='')
print()
15. How many asterisks does the following code fragment print?
for a in range(20, 100, 5):
print('*', end='')
print()
16. How many asterisks does the following code fragment print?
for a in range(100, 0, -2):
print('*', end='')
print()
17. How many asterisks does the following code fragment print?
for a in range(1, 1):
print('*', end='')
print()
18. How many asterisks does the following code fragment print?
for a in range(-100, 100):
print('*', end='')
print()
19. How many asterisks does the following code fragment print?
for a in range(-100, 100, 10):
print('*', end='')
print()
20. Rewrite the code in the previous question so it uses a while instead of
a for. Your code should behave identically.
21. How many asterisks does the following code fragment print?
for a in range(-10, 10, -1):
print('*', end='')
print()
22. How many asterisks does the following code fragment print?
for a in range(10, -10, 1):
print('*', end='')
print()
23. How many asterisks does the following code fragment print?
for a in range(10, -10, -1):
print('*', end='')
print()
24. What is printed by the following code fragment?
a=0
while a < 10:
print(a)
a += 1
print()
25. Rewrite the code in the previous question so it uses a for instead of a
while. Your code should behave identically.