Python is an interpreted programming language oriented to easy-readable coding, unlike compiled languages like C/C++ and Fortran, where the syntax usually does not favor the readability. This feature makes Python very interesting when we want to focus on something different than the program structure itself, e.g. on Computational Methods, thereby allowing to optimize our time, to debug syntax errors easily, etc.
print('Hello World!')
Hello World!
And also allows scripting: (This code should be copied on a file 'hello.py')
#! /usr/bin/python
#This is a comment
print('Hello World!')
Hello World!
5.89+4.89
10.78
120*4.5
540.0
#Unless you use decimals, python does not support complete division (only integer division)
#This only applies for Python 2.X
100/3
33
100/3.
33.333333333333336
2**6
64
10%2
0
20%3
2
(1.0e24/3. + 2.9e23)/1e-2
6.233333333333333e+25
Lists are useful when you want to store and manipulate a set of elements (even of different types).
#A list is declared using [] and may content different type of objects
lista = ["abc", 42, 3.1415]
print lista
['abc', 42, 3.1415]
#First element of the list
lista[0]
'abc'
#Last element of the list
lista[-1]
3.1415
#Adding a new element (boolean element)
lista.append(True)
print lista
['abc', 42, 3.1415, True]
#Inserting a new second element
lista.insert(1, "I am second :)")
print lista
['abc', 'I am second :)', 42, 3.1415, True]
#Deleting the third element of the list
del lista[3]
print lista
['abc', 'I am second :)', 42, True]
#Reassign the first element of the list
lista[0] = "xyz"
print lista
['xyz', 'I am second :)', 42, True]
#Showing the elements from 0 to 2
lista[0:3]
['xyz', 'I am second :)', 42]
#Showing elements two by two
lista[::2]
['xyz', 42]
#It is possible to embed a list
embedded_list = [lista, [True, 42L]]
print embedded_list
[['xyz', 42, 3.1415], [True, 42L]]
#Second element of the first list
embedded_list[0][1]
42
#A matrix as a list of embedded lists
A = [ [1,2], [3,4] ]
print A
[[1, 2], [3, 4]]
#When two list are added, the result is a new concatenated list
[1,2,"ab",True,[1,2]] + [3.1415,"Pi","circle"]
[1, 2, 'ab', True, [1, 2], 3.1415, 'Pi', 'circle']
A tuple is almost equal to a list, except that once declared its elements, it is not possible to modify them. Therefore, tuples are useful when you only want to store some elements but not modify them.
#A tuple is declared using ()
tupla = ("abc", 42, 3.1415)
print tupla
#It is not possible to add more elements
tupla.append("xy")
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-65-dd567ac24edd> in <module>() 1 #It is not possible to add more elements ----> 2 tupla.append("xy") AttributeError: 'tuple' object has no attribute 'append'
#It is not possible to delete an element
del tupla[0]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-66-17ab9d47366f> in <module>() 1 #It is not possible to delete an element ----> 2 del tupla[0] TypeError: 'tuple' object doesn't support item deletion
#It is not possible to modify an existing element
tupla[0] = "xy"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-67-87de1a05f9b3> in <module>() 1 #It is not possible to modify an existing element ----> 2 tupla[0] = "xy" TypeError: 'tuple' object does not support item assignment
Dictionaries are extremely useful when manipulating complex data.
#A dictionary is declared using {}, and specifying the name of the component, then the character : followed by the element to store.
dictionary = { "Colombia":"Bogota", "Argentina":"Buenos Aires", "Bolivia":"La Paz", "Francia":"Paris", "Alemania":"Berlin" }
print dictionary
#Note the order in a dictionary does not matter as one identifies a single element through a string, not a number
{'Francia': 'Paris', 'Argentina': 'Buenos Aires', 'Bolivia': 'La Paz', 'Alemania': 'Berlin', 'Colombia': 'Bogota'}
#Instead of a number, an element of a dictionary is accessed with the name of the component
print dictionary["Colombia"]
print dictionary["Alemania"]
Bogota Berlin
#The elements of the dictionary may be of any type
dictionary2 = { "Enteros":[1,2,3,4,5], "Ciudad":"Medellin", "Cedula":1128400433, "Colores":["Amarillo", "Azul", "Rojo"] }
print dictionary2["Colores"][1]
Azul
#The elements of the dictionary can be modified only by changing directly such an element
dictionary2["Ciudad"] = "Bogota"
print dictionary2
{'Ciudad': 'Bogota', 'Colores': ['Amarillo', 'Azul', 'Rojo'], 'Cedula': 1128400433, 'Enteros': [1, 2, 3, 4, 5]}
#Adding a new element is possible by only defining the new component
dictionary2["Pais"] = "Colombia"
print dictionary2
{'Pais': 'Colombia', 'Ciudad': 'Bogota', 'Colores': ['Amarillo', 'Azul', 'Rojo'], 'Cedula': 1128400433, 'Enteros': [1, 2, 3, 4, 5]}
#The command del can be also used for deleting an element, as a list
del dictionary2["Colores"]
print dictionary2
{'Pais': 'Colombia', 'Ciudad': 'Bogota', 'Cedula': 1128400433, 'Enteros': [1, 2, 3, 4, 5]}
Conditionals are useful when we want to check some condition.
The statements elif
and else
can be used when more than one condition is possible or when there is something to do when condition is not fulfilled.
x = 10
y = 2
if x > 5 and y==2:
print "True"
True
x = 4
y = 3
if x>5 or y<2:
print "True 1"
elif x==4:
print "True 2"
else:
print "False"
True 2
For
cycles are specially useful when we want to sweep a set of elements with a known size.
for i in xrange(0,5,1):
print i, i**2
0 0 1 1 2 4 3 9 4 16
suma = 0
for i in xrange(0,10,1):
suma += i**2
print "The result is %d"%(suma)
The result is 285
for language in ['Python', 'C', 'C++', 'Ruby', 'Java']:
print language
Python C C++ Ruby Java
serie = [ i**2 for i in xrange(1,10) ]
print( serie )
[1, 4, 9, 16, 25, 36, 49, 64, 81]
While
cycles are specially useful when we want to sweep a set of elements with an unknown size.
#! /usr/bin/python
number = int(input("Write a positive number: "))
while numero < 0:
print("You wrote a negative number. Do it again")
numero = int(input("Write a positive number: "))
print("Thank you!")
Write a positive number: -10 You wrote a negative number. Do it again Write a positive number: -5 You wrote a negative number. Do it again Write a positive number: -2 You wrote a negative number. Do it again Write a positive number: 2 Thank you!
from numpy.random import random
x = 0
while x<0.9:
x = random()
print x
print "The selected number was", x
0.276865731891 0.548376718376 0.777814240976 0.102083005032 0.441029966753 0.986556748219 The selected number was 0.986556748219
def f(x,y):
return x*y
f(3,2)
6
#It is possible to assign default arguments
def f(x,y=2):
return x*y
#When evaluating, we can omit the default argument
f(3)
6
#It is possible to specify explicitly the order of the arguments
def f(x,y):
return x**y
print 'f(1,2)=',f(1,2)
print 'f(2,1)=',f(y=1,x=2)
f(1,2)= 1 f(2,1)= 2
Implicit functions are usdeful when we want to use a function once.
f = lambda x,y: x**y
f(3,2)
9
#It is possible to pass functions as arguments of other function
def f2( f, x ):
return f(x)**2
#We can define a new function explicitly
def f(x):
return x+2
print "Explicit: f(2)^2 =", f2(f,2)
#Or define the function implicitly
print "Implicit: f(2)^2 =", f2(lambda x:x+2,2)
Explicit: f(2)^2 = 16 Implicit: f(2)^2 = 16