Category: Scripts and codes

Starting up with Python – Part10

This part will be dedicated to For and While loops in python as well as Infinite loops and Break. Loops allow us to execute a certain block of codes multiple times without really typing it multiple time. Below is a list of topics we have already gone through:

 Starting up with Python - Part10 1

21. The While loop

To make a basic loop, we will need a variable. The code below shows a which is assigned to 1. Then in the second line, it says while 1 is less or equal to 10, let’s print a by adding 1 to it. This will keeps on adding 1 until a is less or equal to 10. If the fourth line is not used, a will be equal to 1 for the whole time because it does not know when a will end.

#! /usr/bin/env python
a = 1
    while a <=10:
print a
 a +=1

22. The For loop

The code below shows a list where the variable country is assigned with values. At line 2 when the for loop starts, it puts every country’s name in the value called a. The code simply said for a in country each time several times by grabbing all values (countries) assigned to country.  So, the output is done by assigning the value of each time to the line it’s printing.

#! /usr/bin/env python
country=['mauritius','usa','france','uk']
for a in country:
    print 'i want to go to ' + a

23. The Infinite loop

The loop here is going to print the country together with the temperature value.

#! /usr/bin/env python

temperature={‘mauritius’:42,’usa’:1,’france’:12}
for a in temperature:
print a, temperature[a]

24. Break a loop

What is most interesting is to break a loop by keeping the prompt until the right answer is found. Here is an example. As you can see the while 1 is a test to keep on looping forever. To stop the unlimited look, we use a break statement at line 2. The variable name is used to test the break statement. So each time a name is going to be inserted, it’s going to store it in raw_input. What is going to happen is that it’s going to loop forever until the name ‘nitin‘ is found.

>>> while 1:
... name = raw_input('My name is: ')
... if name == 'nitin': break
... 
My name is: tim
My name is: what?
My name is: nitin

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.

Starting up with Python - Part9 2

Starting up with Python - Part9 3

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:

Starting up with Python - Part8 4

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.”

Starting up with Python – Part7 5

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:

Starting up with Python – Part6 6

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