Monday, November 30, 2015

Python Looping Statements

Python For Loop:

           If a sequence contains an expression list, it is evaluated first. Then, the first item 
in the sequence is assigned to the iterating variable iterating_var. Next, the statements 
block is executed. Each item in the list is assigned to iterating_var, and the statement(s) 
block is executed until the entire sequence is exhausted.



for iterating_var in sequence:
   statements(s)
Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
n=input("Enter the value:")
for i in range(n):
    print "i:",i

str1=raw_input("Enter the String:")
for i in str1:
    print "i:",i
    
n=input("Enter the value:")
l=[]
for i in range(n):
 en=raw_input("Enter the String:")
 l.append(en)
Prime Numbers:
1
2
3
4
5
6
for num in range(10,20): #[10,11,12,12,....19]
    for i in range(2,num):
        if num%i == 0:
            break
    else:#else for
        print "prim Num",num
Fibonac Series :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def fib_gen(n):
#fib 0,1,1,2,3,5...
    l=[0,1]
    for i in range(2,n):
        fib=l[i-1]+l[i-2]
        l.append(fib)
    return l

n=input("Enter Number")
l=fib_gen(n)
print "Fib List:",l

While Statements :
            Statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.
while expression:
   statement(s)
Example:
1
2
3
4
a=1
while a<10:
   print a
   a=a+1
Prime Number using while:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
a=10
n=200
b=1
while a< n:
 c=2
 while c<a-1:
  if a%c==0:
   break
  c=c+1 
 else:
     print "Prime:",a
     
 if b==10:
  print ">>",b
  break
 else:
     b+=1
 a=a+1#a+=1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
c=1
l=[]
p="="*30
n=raw_input("Enter number how many std ")
while c<int(n):
    name=raw_input("Enter Name")
    age=raw_input("Enter Age")
    l.append({'Name':name,"Age":age})
    c=c+1
    
print p
print "        Std Details      "
print p
for i in l:
    print i['Name']
    print i['Age']

No comments:

Post a Comment