Python -Loops

Basic IF
More complicated IF
while loop
else loop
multiple else
For line in
For line -count number of instances

for more what operators to use i.e == see comparison and operators

Basic IF

the_world_is_flat = 1
if the_world_is_flat:
print "be careful no to fall off"

For an is equal test see the bottom of is equal

More complicated IF

#!/usr/bin/python
v=5
if v == 5:
print "true"
else:
print "false"

./more_complicated_if

true

while loop

#!/usr/bin/python
# note you need indentation
a = 0
while a < 10:
 a = a + 1
 print a

else loop

#!/usr/bin/python
a = 1
if a > 5:
 print "this shouldn't happen"
else:
 print "this should happen"

# ./else
this should happen

multiple else

if {conditions}:
{run this code}
elif {conditions}:
{run this code}
elif {conditions}:
{run this code}
else:
{run this code}

example

#!/usr/bin/python
# note == is equal to and != is not equal to
# This is because the single equal sign is already used for assignment in Python, so it is not available for tests.
choice = input("please enter a number:")
print choice

if choice == 0:
print "zero"
elif choice == 1:
print "one"
else:
print "well its not zero or one"

For line in

Loop through an input and then ....

cat file
123
test
123jabba
test
123cent

cat searchme.py
for line in open("file"):
if "123" in line:
print line

python searchme.py
123

123jabba

123cent

For line -count number of instances

cat file
123
test
123jabba
test
123cent

cat searchme.py
instances=0
for line in open("file"):
if "123" in line:
instances=instances+1
print instances

python searchme.py
3