Python Tutorial @ Home

# Python Looping Techniques 2

Loop with condition in the middle

This kind of loop can be implemented using an infinite loop along with a conditional break in between the body of the loop.

Write a python script to take input for numbers calculate and print sum of even and odd entered number, the program should get terminated when 0 is entered.

```s=0
n=0
while True:
n=int(input("Enter any no, enter -999 to end "))
if(n==-999):
break
s=s+n
print("Sum  = ",s)
```

Output:

Enter any no, enter -999 to end 2
Enter any no, enter -999 to end 6
Enter any no, enter -999 to end 3
Enter any no, enter -999 to end 5
Enter any no, enter -999 to end -999
Sum = 16
>>>

## Loop with condition at the bottom

This kind of loop ensures that the body of the loop is executed at least once. It can be implemented using an infinite loop along with a conditional break at the end. This is similar to the do…while loop in C.

Q. Write a python script to take input for a number calculate and print its square, add the continue condition?

```n=0
s=0
while True:
n=int(input("Enter any no "))
s=n*n
print("Square = ",s)

ch=input("lke to cont ... (y/n) ")
if (ch=='y' or ch=='Y'):
continue
else:
break
```

Output:

Enter any no 2
Square = 4
lke to cont … (y/n) y
Enter any no 3
Square = 9
lke to cont … (y/n) y
Enter any no 4
Square = 16
lke to cont … (y/n) n
>>>

Important Pages Visitor Counter       