3rd LESSON (ANKUR - PROSCHOOL) - CONTROL FLOW & LOOPS - HTML PDF
3rd LESSON (ANKUR - PROSCHOOL) - CONTROL FLOW & LOOPS - HTML PDF
When you run code in Python, each statement is executed in the order in which they appear.
Programming languages like Python let you change the order in which code executes, allowing
you to skip statements or run certain statements over and over again. Programming constructs
that let you alter the order in which code executes are known as control flow statements.
IF STATEMENT
The most basic control flow statement in Python is the "if" statement. An if statement checks
whether some logical expression evaluates to true or false and then executes a code block if the
expression is true.
In Python, an if statement starts with if, followed by a logical expression and a colon. The code to
execute if the logical expression is true appears on the next line, indented from the if statement
above it by 4 spaces:
In this example we use two variables, x and y, which are used as part of the if statement to test
whether x is greater than y. As x is 10, and y is 5, we know that 10 is greater than 5, and so we
print to screen that "x is greater than y".
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Example 1: If the number is positive, print an appropriate message
In [ ]: num = 3
if num>0:
print(num, "is a positive number.")
INDENTATION
Python relies on indentation, using whitespace, to define scope in the code. If statement, without
indentation will throw an error.
ELSE STATEMENT
If statements are often accompanied by else statements. Else statements come after if
statements and execute code in the event that logical expression checked by an if statement is
false:
Example 2: Take an input from the user to check how many days are
there in a leap year. Print a congratulatory message if the answer is
correct
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
test else send a message that he has passed the test. In either case
print a Thanks message too!
ELIF STATEMENT
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".
In [ ]: x=33
y=33
if x>y:
print("x is greater than y")
elif x==y:
print("x and y are equal")
else:
print("x is less than y")
In this example x is equal to y, so the first condition is not true, but the elif condition is true, so we
print to screen that "x and y are equal".
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
In [ ]: response=input("Which python datatype is an ordered sequence?").lower()
print("You entered: ", response)
if response=="list":
print("You have cleared the test.")
elif response=="tuple":
print("You have cleared the test.")
else:
print("Your input is wrong. Please try again!")
NESTED IF STATEMENTS
Some programs may have a code block under an “if” clause which subsequently has another
conditional block as the first statement.
In such a case, Python allows nesting of an if-else or if-elif-else inside another conditional clause.
Python doesn’t limit the level of nested conditions in a program. Given below is the syntax of a
multi-level nested if-elif-else statement.
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
EXAMPLE 6:
In [ ]: response = int(input("How many days are there in a leap year? "))
print("You entered:", response)
if response == 366 :
print("You have cleared the first level.")
response = input("What month has an extra day in leap year?? ").low
er()
if response == "february" :
print("You have cleared the test.")
else:
print("You have failed the test.")
else:
print("Your input is wrong, please try again.")
Question 2: Take two int values from user and print greatest among
them
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
and year of service and print the net bonus amount.
ANSWER 1:
breadth=int(input("Enter Breadth:"))
if length==breadth:
print("Yes, it is a square")
else:
print("No, it is a rectangle")
ANSWER 2:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
if first>second:
print("first number is greater,", first)
elif first<second:
print("second number is greater,", second)
else:
print("both are equal")
ANSWER 3:
ANSWER 4:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
else:
print("No Bonus")
ANSWER 5:
ANSWER 6:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
In [ ]: classesheld=int(input("Enter number of classes held: "))
classesattended=int(input("Enter number of classes attended: "))
atten=(classesattended/classesheld)*100
satten=str(atten)
print("Attendance is", satten,"%")
if atten>=75.0:
print("You are allowed to sit in the exam")
else:
print("Please attend more classes")
RANGE
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
0
1
2
3
4
5
The range() function defaults to increment the sequence by 1, however it is possible to specify
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
the increment value by adding a third parameter: range(2, 30, 3):
2
12
22
32
42
52
62
72
82
92
Current Letter: l
Current Letter: l
FOR LOOP
For loops are a programming construct that let you go through each item in a sequence and then
perform some operation on each one. For instance, you could use a for loop to go through all the
values in a list, tuple, dictionary or series and check whether each conforms to some logical
expression or print the value to the console.
In [8]: # Example 1:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
cars=["Maruti", "Honda", "Toyota"]
for x in cars:
print(x)
Maruti
Honda
Toyota
In [9]: # Example 2:
for x in "banana":
print(x)
b
a
n
a
n
a
In [13]: # Example 3:
mysequence=tuple(range(0,101,10))
for number in mysequence:
print(number+100)
100
110
120
130
140
150
160
170
180
190
200
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
Practice Questions
Question 1: Using For Loop, Write a program which will find all such
numbers which are divisible by 7 but are not a multiple of 5, between
2000 and 3200 (both included). The numbers obtained should be
printed in a comma-separated sequence on a single line.
Then, the output should be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
and write a program that prints out all the elements of the list that are less than 5.
Answer 1:
In [14]: a=range(2000,3201)
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
z=[]
for a1 in a:
if a1%7==0 and a1%5==0:
a1+=1
elif a1%7==0:
z.append(a1)
a1+=1
print(z)
[2002, 2009, 2016, 2023, 2037, 2044, 2051, 2058, 2072, 2079, 2086, 209
3, 2107, 2114, 2121, 2128, 2142, 2149, 2156, 2163, 2177, 2184, 2191, 21
98, 2212, 2219, 2226, 2233, 2247, 2254, 2261, 2268, 2282, 2289, 2296, 2
303, 2317, 2324, 2331, 2338, 2352, 2359, 2366, 2373, 2387, 2394, 2401,
2408, 2422, 2429, 2436, 2443, 2457, 2464, 2471, 2478, 2492, 2499, 2506,
2513, 2527, 2534, 2541, 2548, 2562, 2569, 2576, 2583, 2597, 2604, 2611,
2618, 2632, 2639, 2646, 2653, 2667, 2674, 2681, 2688, 2702, 2709, 2716,
2723, 2737, 2744, 2751, 2758, 2772, 2779, 2786, 2793, 2807, 2814, 2821,
2828, 2842, 2849, 2856, 2863, 2877, 2884, 2891, 2898, 2912, 2919, 2926,
2933, 2947, 2954, 2961, 2968, 2982, 2989, 2996, 3003, 3017, 3024, 3031,
3038, 3052, 3059, 3066, 3073, 3087, 3094, 3101, 3108, 3122, 3129, 3136,
3143, 3157, 3164, 3171, 3178, 3192, 3199]
Answer 2:
Answer 3:
In [17]: w=[]
st = 'Print every word in this sentence that has an even number of lett
ers'
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
z=st.split()
for i in z:
if len(i)%2==0:
w.append(i)
#else:
#w.append("Odd")
print(w)
In [16]: z
Out[16]: ['Print',
'every',
'word',
'in',
'this',
'sentence',
'that',
'has',
'an',
'even',
'number',
'of',
'letters']
Answer 4:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
this value of this index is less than 5 and it is 3
this value of this index is less than 5 and it is 5
WHILE LOOP
While loops are similar to for loops in that they allow you to execute code over and over again.
For loops execute their contents, at most, a number of iterations equal to the length of the
sequence you are looping over. While loops, on the other hand, keep executing their contents as
long as a logical expression you supply remains true:
In [19]: # Example 1:
x=5
i=0
while i<x: #print as long as the iteration(i) is less than x
print ("India")
i=i+1 #incrementing the iteration by 1 each time the loop executes
India
India
India
India
India
QUESTION 2: Using While Loop, Write a program which will find all
such numbers which are divisible by 7 but are not a multiple of 5,
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
between 2000 and 3200 (both included). The numbers obtained should
be printed in a comma-separated sequence on a single line.
SOLUTIONS
ANSWER 1:
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
else:
t+=1
While loops can get you into trouble because they keep executing until the logical statement
provided is false. If you supply a logical statement that will never become false and don't provide
a way to break out of the while loop, it will run forever. For instance, if the while loop above didn't
include the statement incrementing the value of iters by 1, the logical statement would never
become false and the code would run forever. Infinite while loops are a common cause of
program crashes.
The CONTINUE AND BREAK STATEMENTS work inside while loops just like they do in for
loops. You can use the break statement to escape a while loop even if the logical expression you
supplied is true. Consider the following while loop:
Enjoy
In [22]: x = 100
while x < 110:
print(x)
if x==103:
break
x=x+1
100
101
102
103
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
if letter == "l":
break
print('Current Letter:',letter)
Current Letter: W
Current Letter: e
With the continue statement we can stop the current iteration, and continue with the next:
In [24]: x = 100
while x < 110:
x=x+1
if 104<=x<=107:
continue
print(x)
101
102
103
108
109
110
In the above example, the iteration is stopped for values of x: 104,105,106 and then continues
for the remaining values till x<110
Current Letter: W
Current Letter: e
Current Letter: c
Current Letter: o
Current Letter: m
Current Letter: e
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
In [26]: for letter in 'Python':
if letter == 'h':
pass
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
PASS
You can consider python pass statement as no operation statement. The difference between
Python comments and pass statement is; comments are being eliminated while interpreting the
program but pass statement does not. It consumes execution cycle like a valid statement. For
example, for printing only the odd numbers from a list, our program flow will be
List <- a list of number for each number in the list: if the number is even, then, do nothing else print odd number
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD
3
5
7
9
Create PDF in your applications with the Pdfcrowd HTML to PDF API PDFCROWD