Wednesday, January 9, 2013

Python Fundamentals (Conditional Statements)

I am pretty familiar with writing conditional statements, so this section will be a bit brief.  I just wanted to supply some examples for later reference.

If statement example:

#!/usr/bin/python

name = raw_input("What is your Name? ")
print "Your name is " + name

if name == "chris":
        print "You are chris"
        print "The computer admin"
elif name == "john":
        print "You are John"
        print "A regular user"
else :
        print "Unknown user"

While loop statement example:
#!/usr/bin/python

age = 0
while age < 5:
        print age, " is less than 5"
        age = age + 1
else :
        print age, " is equal to 5"

For loop statement example:
#!/usr/bin/python

for num in range(10,20):
        for i in range(2,num):
                if num%i == 0:
                        j=num/i
                        print '%d equals %d * %d' % (num,i,j)
                        break
        else:
                print num, 'is a prime number'


Use range in Python:
range(lower, upper, step) creates a list
range(n) - [0, ......, n-1]


>>> range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
>>> range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9,10]
>>>
>>> range(1,11,2)
[1, 3, 5, 7, 9]
>>>
>>> for item in range(1,11,2) :
...     print item
...
1
3
5
7
9
>>>

No comments:

Post a Comment