2. Objectives
For loop statement with range
While with is and is not
If with for statements
Break and continue
3. For loop with range
As we saw at last video we can use range function with for loop and we
take an example for it
Today we will take another examples:
First example is the average of numbers from 1 to 10
Second example is factor of number n!
4. Average for 1 to 10
s=0
for i in range(1,11):
s=s+i
su=s/10
print(su)
5. Factor of number (n!)
s=1
for i in range(1,6):
s=s*i
print(s)
6. While with is and is not:
As a Boolean operation we have the following operation in python
is & not is
We use is to make sure that two objects are same
We use not is to make sure that two objects are not same
We can use (int – string – float) as an objects
Examples:
7. >>> x=5
>>> y=5
>>> x is y
True
>>> x is not y
False
>>> a="ali"
>>> b="Ali"
>>> a is b
False
>>> a is not b
True
>>> c=3.5
>>> d=3.4999999
>>> c is d
False
>>> c is not d
True
8. While with is and is not:
To understood the usage of is and not is we will take the same example of
average of number and factor of number (n!) using while and (is) and (is
not)
The program is written as following:
9. Average program
s=1
s1=11
su=0
while (s is not s1):
su=s+su
s+=1
su=su/10
print(su)
10. Factor of number (n!)
s=1
s1=6
su=1
while (s is not s1):
su=su*s
s+=1
print(su)
11. If with for statements
Also we can use if…else statement in for loop
For example we can be sure that some number is in some range so we do
some thing for that
Example:
s="t"
s1="python"
for i in s1:
if s in s1:
print("ok")
else:
print("some thing")
12. Break and continue
The result for previous example is:
ok
ok
ok
ok
ok
ok
That mean the (t) is in word (python) and repeat the result 6 times (length
of python world)
13. Break and continue
What should we do to stop the loop when the program found (t)
We must use break keyword
break: stop the execution of loop for some reason
The previous example will be like:
s="t"
s1="python"
for i in s1:
if s in s1:
print("ok")
break
else:
print("some thing")
And the result is:
ok
14. Break and continue
If we don’t want to print any thing if (t) in python what should we do
We can use continue keyword
Continue: to stop for a condition and continue after that
Example: if we want to print 1 2 4 5 without 3
We write:
for i in range(1,6):
if i==3:
continue
print(i)
15. Break vs continue
In the previous example if we use break instead of continue the result will
be like:
1
2
Because break end all of loop but continue stop for condition and
continue over the loop