OCJP

Control Structure and Loops in Python

As we earlier learned how variables are declared and printed in Basics of Python. Now we will use control structure like ‘if’ and loops like for and while.

x=input("Enter X :") # here value will be string
y=int(x) #converted to integer
if(y>0):
    print("positive No")
    print("\nIts Valid")
else:
    printf("Neg No")
print("Thank you")

Here input() is used to get the data from user. It will always return string even you enter numeric value. So we converted x into Integer by using function int(). Then if is applied. In python no { and } are used for block. It is specified by Indent (tab). after if (condition): there are two lines are in true part of if in our example. Then else part (false part) : One line is in false part. Thank you is printed outside the block so it will be printed always either y>0 or not.

i=1
while(i<=10):
    print(" ",i)
    i+=2
print("End of Loop")
  1
  3
  5
  7
  9
End of Loop

For loop is different then it is in C,C++ or Java.

for i in range(10):
    print(i)
print("Decreasing For Loop")
for i in range(100,50,-5):
    print(i)

print("Array/List using For Loop") 
data=[11,22,44,55,33,66,77]
for x in data:
    print(x)
0
1
2
3
4
5
6
7
8
9
Decreasing For Loop
100
95
90
85
80
75
70
65
60
55
Array/List using For Loop
11
22
44
55
33
66
77

Breaking the Loop. break will end up the block.

i=1
for i in range(100):
    print(i)
    if(i>10):
        break
0
1
2
3
4
5
6
7
8
9
10
11

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?