Tag: Python

Starting up with Python – Part9

Part 9 of this Python fiesta on TheTunnelix is going to be more fun. I will now focus on And and Or operators. Here is a recap where we have reached if you are not following the Python blog posts since the beginning.

20. And and Or operators

To check if 2 conditions are true, we can also use the conditions called ‘And‘. The code below will output the answer ‘number1 is between 3 and 2o’ Same could be achieved by using the if and else statement.

#! /usr/bin/env python
number1 = 5
if number1 > 3 and number1 < 10:
 print 'number1 is between 3 and 10'

However, we would also notice that in an And statement, if only one part of the statement is true, nothing would be printed. See example below where we would notice number1 < 4 which is fake. This would never print anything on the screen.

#! /usr/bin/env python
number1 = 5
if number1 > 3 and number1 < 4:
 print 'number1 is between 3 and 10'

In this case, we can use an Or operator to output what we really want. See example below 

#! /usr/bin/env python
number1 = 5
if number1 > 3 or number1 < 4:
 print 'this works fine'

As we have seen in the And statement if a part is not true it will not print anything on the screen compared to the Or statement either both are true just one part is true. If any part of the Or statement is false, it won’t work.

Starting up with Python – Part8

I am now at part 8 of my one of my objective to refresh myself with the basics of Python. This part will be dedicated to Nesting and Comparison statements in Python. Here are the topics discussed earlier on this blog about python:

18.Nesting statements

Let’s see this simple if statement which will output “We are Mauritius hackers group”

#! /usr/bin/env python
hackers = "mauritius"
mauritius = "country"
if hackers == "mauritius":
    print 'we are mauritius hackers group'
else:
    print 'Country is not in our record'

At this point, we are going to create a nested if statement. It’s first going to test the first if statement and since hackers are equal to “toto”, the main or first if statement, when run, will redirect to the last else statement by giving the output “country is not in our record”

#! /usr/bin/env python
hackers = "toto"
mauritius = "country"
if hackers == "mauritius":
     if mauritius =="country":
          print 'mauritius is a country'
     else:
          print 'wrong country name'
else:
     print 'Country is not in our record'

19. Comparisons Operators

In python, by default, it output the “True” or “False” statement if certain values are entered. For examples

>> 9 >2
True
>>> 3 >10
False
>>> 9!=0
True
>>> 9!=9
False

You can also create an array of numbers. For example

>> toto = [22,23,24]
>>> titi = [25,26,27]
>>> toto == titi
False
>>> toto != titi
True

You can also ask for a certain number within the array :

>> toto is 22
True
>>> toto is 29
False

When there are same values in both arrays, an if-else statement together with loops can be used to check which is true or false.

Starting up with Python – Part7

If statement checks if a condition is true to execute a certain block of code and if its false, it not going to execute the block of code. You can also you use it to skip certain condition. So, let’s see some previous articles on the project “starting up with python.”

16.If statement

A simple start is to create a file as follows:

#! /usr/bin/env python2
hackers="mauritius"
if hackers=="mauritius":
    print 'this is mauritius'

What it means is to pass the value ‘mauritius’ to the variable hackers. It will check if its same value and will eventually print what it is told to that is ‘this is mauritius’. The line #! /usr/bin/env python2 is to told the file to execute from the python environment otherwise be default it will run on bash which will give an error. Indentation is also important at line 4.

However, if the variable hackers=”worldwide” and you run the script, it will run and give u a blank output since hackers==”mauritius”

17. Else and elif statement

Now, we are going to see if the ‘if statement’ is false what do we want it to executes. In this code, since if hackers==”worldwide”,  the output is based on the else statement. Let’s see this code

#! /usr/bin/env python2
hackers="mauritius"
if hackers=="worldwide":
    print 'this is mauritius'
else:
    print 'this is worldwide'

We can also use several elif statement to keep on testing the variables until the answer is received. You can change the values of the variables to play around with the code. If the value “mauritius” is not found under any of the if and elif variables, it will then return the value from the else statement.

#! /usr/bin/env python2
hackers="mauritius"
if hackers=="worldwide":
    print 'this is worldwide'
elif hackers=="Mars":
    print 'this is Mars'
elif hackers=="mauritius":
    print 'this is mauritius'
else: 
    print 'file corrupted'

Starting up with Python – Part6

Day 3 – Moving on to the next level with Sorts and Tuples & String and Stuffs, Strings Methods and Dictionary are surely interesting. Let’s see the last articles on Python:

12.Sort and Tuples

A list can be sorted using the sort function

>> list1 = ['1','4','7','5']
>>> list1.sort()
>>> list1
['1', '4', '5', '7']

Strings can also be sorted. The capital letter will come first

>> sorted('Hackers')
['H', 'a', 'c', 'e', 'k', 'r', 's']

If some numbers are types followed by a comma, a tuple will be created automatically

>> 71,34,23,54,2
(71, 34, 23, 54, 2)

Tuples can also be created with a given name

>> danger=(34,34,23,464,12)
>>> danger
(34, 34, 23, 464, 12)

To have the value of let’s say 34 we simply search it within the array

>> danger[1]
34

13. Strings and pieces of stuff

Here is some way to plug variables in the strings. Let’s say we have a string called name=”HackersWorldwide and Mauritius” and if we want to change this we would need a variable by using the % sign and give instructions what kind of data it is.

>> name="%s and %s"
>>> var=('hackers','mauritius')
>>> print name % var
hackers and mauritius

You can also find where the strings start

>> question="Hey there tunnelers, how are you doing?"
>>> question.find('doing')
33

14.Cool string Methods

You can also take two strings and join them together with the join function

>> sequence=[ 'hey', 'there', 'tunnelers']
>>> sequence
['hey', 'there', 'tunnelers']
>>> join='hacked'
>>> join.join(sequence)
'heyhackedtherehackedtunnelers'

Strings can also be set to Upper and lower case functions. Here is an idea with the upper case function

>> randstr="i am hungry"
>>> randstr
'i am hungry'
>>> randstr.upper()
'I AM HUNGRY'

You can also replace strings with the replace function.

>> randstr="i am hungry"
>>> randstr
'i am hungry'
>>> randstr.replace('hungry','thirsty')
'i am thirsty'

15. Dictionary

A word can be used to look for another value using a dictionary. The syntax is different compared to a typical sequence. We will need a key and a value. Let us say we have a dictionary called book. The ‘book’ has a key called ‘psy’ with value ‘sci’.

So you can type the key to have the return value

>> book={'psy':'sci','war':'his'}
>>> book
{'psy': 'sci', 'war': 'his'}
>>> book['psy']
'sci'

You can also find it by numbers

book={'psy':'1','war':'2'}
>>> book['psy']
'1'

To remove all items in a book, we use the clear function

>> book.clear()
>>> book
{}

You can also copy a dictionary to another new one.

>> book={'psy':'1','war':'2'}
>>> book
{'psy': '1', 'war': '2'}
>>> hackedbook=book.copy()
>>> hackedbook
{'psy': '1', 'war': '2'}

You also use the function has.key to verify for  a key

>> hackedbook
{'psy': '1', 'war': '2'}
>>> hackedbook.has_key('psy')
True

Starting up with Python – Part5

I am now on Day2 with my usual articles on “starting up with Python” Its now time to gets on with Methods in Python.  A Method is a Function which is a member of a class. As usual, articles which have been posted already on Python are as follows:

10. Intro to Methods

An action that is assigned to an object. Methods are built-in functions. Let’s see some examples:

So we have numbers = [0, 3, 4, 5]  and we want to append 45 to it using a method

>> numbers
 [0, 3, 4, 5]
 >>> numbers.append(45)
 >>> numbers
 [0, 3, 4, 5, 45]

The count Method will take an object and counts how many times your arguments are in the defined object.

>> name= ['HackersMauritius','HackersWorldwide']
>>> name.count('HackersMauritius')
1
>>> name.count('Hackers')
0

We can also extend a list with the extend function

>> list1 = ['1','2','3','4']
>>> list2 = ['5','6','7','8']
>>> list1
['1', '2', '3', '4']
>>> list2
['5', '6', '7', '8']
>>> list1.extend(list2)
>>> list1
['1', '2', '3', '4', '5', '6', '7', '8']
>>> list2
['5', '6', '7', '8']

11. More Methods

 The method index() returns the lowest index in the list that obj appears. The index method will search for the first occurrence of value and say where it is in the list. We can also insert a parameter in the list.

>> pets=['dog','cat','monkey','crocodile']
>>> pets
['dog', 'cat', 'monkey', 'crocodile']
>>> pets.index('monkey')
2
>>> pets.insert(4, 'bird')
>>> pets
['dog', 'cat', 'monkey', 'crocodile', 'bird']
>>> pets.insert(3, 'alligator')
>>> pets
['dog', 'cat', 'monkey', 'alligator', 'crocodile', 'bird']

We do not have only the insert function but we can also move around too with the same principle that is object.element(parameters)

>> pets
['dog', 'cat', 'monkey', 'alligator', 'crocodile', 'bird']
>>> pets.pop(3)
'alligator'
>>> pets
['dog', 'cat', 'monkey', 'crocodile', 'bird']

Let’s now delete a value from the list.

>> pets
['dog', 'cat', 'monkey', 'crocodile', 'bird']
>>> pets.remove('bird')
>>> pets
['dog', 'cat', 'monkey', 'crocodile']

You will notice that in ‘pop’ it returns a value whereas in remove it simply deletes it from the list.

We can also reverse the words. For example,

>> pets
['dog', 'cat', 'monkey', 'crocodile']
>>> pets.reverse()
>>> pets
['crocodile', 'monkey', 'cat', 'dog']