# Mini-python [1]

Continuação

Arnaldo Russo

github.com/arnaldorusso
ciclotux.org

## Função

Escreva a função para calcular a velocidade das ondas.

for
while
if
elif
else

```#!/usr/bin/python

for num in range(10,20):  #to iterate between 10 to 20
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0:      #to determine the first factor
j=num/i          #to calculate the second factor
print '%d equals %d * %d' % (num,i,j)
break #to move to the next number, the #first FOR
else:                  # else part of the loop
print num, 'is a prime number'```

## contraldores

http://www.pythontutor.com/visualize.html

```#!/usr/bin/python

count = 0
while (count < 9):
print 'The count is:', count
count = count + 1

print "Good bye!"```

## for

```#!/usr/bin/python

for letter in 'Python':     # First Example
print 'Current Letter :', letter

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second Example
print 'Current fruit :', fruit

print "Good bye!"```

```#!/usr/bin/python

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]

print "Good bye!"```

## if elif

```#!/usr/bin/python

var = 100
if var == 200:
print "1 - Got a true expression value"
print varelif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var

print "Good bye!"```

## Módulos

"glob"
``import glob``glob.glob('*.txt')``
"os"
``import os``os.listdir('.')``# podem ser criados diretorios, apagar arquivos, mudar dir, etc...``

Input / Output

txt
csv
nc
hdf5 / hdf4

open

np.genfromtxt

scipy.io

pandas

pupynere

pyhdf

## open

````a = open('teste.txt')``ll = []````for l in a.readlines():
ll.append(l.split())````ll````

## numpy

``np.genfromtxt("data.csv", delimiter=",", dtype=None, names=True, usemask=True)``

## Pandas

``import pandas as pd``a = pd.read_csv('data.csv')``
``df = pd.read_csv('data.csv', index_col=['date_time'], parse_dates=True, na_values=['-99999.9'])``df.head()``df['salinity (psu)']``

## scipy

``import scipy.io as io``f = io.netcdf_file('file.nc')``f.variables``

## Datas

````\$ info date``/Date input````28 Date input formats
*********************

First, a quote:

Our units of temporal measurement, from seconds on up to months,
are so complicated, asymmetrical and disjunctive so as to make
coherent mental reckoning in time all but impossible.  Indeed, had
some tyrannical god contrived to enslave our minds to time, to
make it all but impossible for us to escape subjection to sodden
routines and unpleasant surprises, he could hardly have done
better than handing down our present system.  It is like a set of
trapezoidal building blocks, with no vertical or horizontal
surfaces, like a language in which the simplest thought demands
ornate constructions, useless particles and lengthy
circumlocutions.  Unlike the more successful patterns of language
and science, which enable us to face experience boldly or at least
level-headedly, our system of temporal calculation silently and
persistently encourages our terror of time.

...  It is as though architects had to measure length in feet,
width in meters and height in ells; as though basic instruction
manuals demanded a knowledge of five different languages.  It is
no wonder then that we often look into our own immediate past or
future, last Tuesday or a week from Sunday, with feelings of
helpless confusion.  ...

-- Robert Grudin, `Time and the Art of Living'.

This section describes the textual date representations that GNU
programs accept.  These are the strings you, as a user, can supply as
arguments to the various programs.  The C interface (via the
`parse_datetime' function) is not described here. ``````

## Acessando datas

````f = np.genfromtxt("data.csv", delimiter=",", dtype=None, names=True, usemask=True)``f['date_time']``from datetime import datetime``dates = []````for i in f['date_time']:
dates.append(datetime.strptime(i, "%Y-%m-%dT%H:%M:%SZ"))``````

Mais algumas pequenas dicas e utilidades:

### EXemplo - acesso remoto.

````import pydap.client``dataset = pydap.client.open_url(``'http://opendap.ccst.inpe.br/Climatologies/OISST/sst.mnmean.nc')``dataset.keys()``dataset.keys['sst'].dimensions``print dataset.sst.dimensions``sst = dataset.sst[:,:,:]``sst = dataset.sst[:,````    (dataset.sst.lat > -50) & (dataset.sst.lat < 0),
dataset.sst.lon > 300,]````print sst.shape``print sst.lat.shape``print sst.lat[:]``print dataset.time.units````

## Title

``from datetime import datetime, timedelta``# digamos que queira saber qual a data do sst.time[0]``print dataset.time.units``print sst.time[0]``dia_zero = datetime(1800,1,1,0,0,0) + timedelta(days = sst.time[0])``

Ipython Notebook

## Plots

``import matplotlib.pyplot as plt``# desse modo, cada funçao de plot deve ser``# chamada com o prefixo``plt.plot( tal, coisa)``plt.show()``
Ja o modo interativo:
ipython --pylab
habilita os plots diretos e sem a necessidade
de pedir para mostrar.

## Matplotlib

Notebook explicativo