Wednesday, December 24, 2014

Conditional statements

We will write some common programs to get you with the conditional statements


num=input()
num = int(num)
if num>3:
    print "number greater than 3"
else:
    print "number less than or equal to 3"

input:
4
Output:
number greater than 3

The above example seems simple but note the alignment after if and else statement that alignment should me maintained.

Now consider next example:

num=input()
num = int(num)
if num>3:
    print "number greater than 3"
    print "the number is: " + num
    if num>7:
        print "number is also greater than 7"
else:
    print "number less than or equal to 3"

input:
4
output:
number greater than 3
the number is: 4

input:
8
output:
number greater than 3
the number is: 8
number is also greater than 7

input:
2
output:
number less than or equal to 3

From the above example its quite clear from how alignment works for if else conditions.

we will see some more examples in next post.

Tuples

TUPLES:

In many ways, tuples are similar to the lists.

Difference between tuples and List:
1. Tuples are immutable while List are mutables.
    Immutable means that we can not modify the tuples like appending an element, inserting an item         an item at a particular position or deleting one or more elements. These are the operations which         can be done on lists.
2. Tuples are heterogeneous data structure while lists are homogeneous sequence.
    It means tuples are sequence of different kind of items while lists are sequence of same kind of           items.

>>>a=1,2,3,4,5,6
>>>a
(1,2,3,4,5,6)
>>>

however a.append(5) or a[3]=5 kind of statements will give you errors because as mentioned tuples are immutable that is they can not be modified.

but the printing of elements of tuples are similar as printing method of lists.

>>>print a[0]
1
>>>print a[:3]
(1,2,3)
>>>print a[::-1]
(6,5,4,3,2,1)