Conditionals In Python

Conditionals are a key part of applying logic within your code and understanding conditionals starts with understanding the if statement. Conditionals is use to check the variable wheather it's true or false and then apply spesific action with that result.

Let's see the example of conditional using if
>>> hostname='Batam'
>>> if hostname=='Batam':
...    print 'The hostname is Batam'
...
The hostname is Batam

In the example above we only examine only one variable, Now we try to examine more then one condition.
>>> hostname='btm-rtr1'
>>> if hostname=='btm-rtr1':
...    print 'This is router btm-rtr1'
... elif hostname=='btm-rtr2':
...    print 'This is router btm-rtr2'
... elif hostname=='btm-rtr3':
...    print 'This is router btm-rtr3'
... else:
...    print 'Router is unknown'
...
This is router btm-rtr1

We can use 'in' to check wheter the element exist in list or not? see the example below
>>> vendor=['cisco','juniper','tellabs','ciena','arista']
>>> 'arista' in vendor
True
>>> 'f5' in vendor
False
>>>
>>> if 'arista' in vendor:
...    print 'arista is deployed...'
...
arista is deployed...


Tulis komentar anda... Conversion Conversion Emoticon Emoticon

Thanks for your comment