Jump to content
Sign in to follow this  
Smoon

Python 2.7 - rápida introdução

Recommended Posts

Smoon

Olá a todos,

eu escrevi um documento com exemplos de código em python, que pretende ser uma rápida introdução em python 2.7 ou inferior.

Inicialmente, eu considerava que o meu público alvo seria uma pessoa que já soubesse outra(s) linguagen(s) de programação e que quisese aprender python "num instante", porque eu escrevi isto para um estrangeiro mt ocupado que me pediu se eu lhe podia indicar alguns manuais de python para aprender rapidamente e ele já sabia outras linguagens.

Aqui mostro um programa hello world, exemplos curtos das estruturas de controlo, refiro quais as funções nativas do python mais úteis e para que servem, etc.

Os comentários estão todos em inglês (se alguém achar conveniente uma tradução avisem-me). O pdf ao todo só tem 3 páginas, vai directo ao que é importante, sem detalhes.

Em termos de lógica de programação são exemplos muito simples (excepto o último em "examples_source.rar", que não consta do texto), portanto acho que isto também pode ser bastante útil como um complemento para alguém que esteja a dar os primeiros passos em python.

Espero que alguem ache isso útil,

os links actuais para download do pdf e código fonte desta rápida introdução a python são:

http://dl.dropbox.com/u/619101/guides_python/python_fast_introduction.pdf

http://dl.dropbox.com/u/619101/guides_python/examples_source.rar

Share this post


Link to post
Share on other sites
Smoon

por uma questão de permitir a leitura sem download, passo a deixar aqui o que se encontra no meu pdf:

fast introduction to

Python programming language (release 2.7)

  • hello world

# this program says hello to the world 
print 'hello world!' 

  • greet the user

# this script asks some info
name=raw_input('what is your name? ') 
age=int(raw_input('and your age? ')) 

# and then greets the user
print 'hello '+name+', you are '+str(age)+' years old!' 

  • control structures

if

# if statement
answer=raw_input("are you happy, today? ") 
if answer=="yes": 
    print "very well!" 
elif answer=="no": 
    print "oh, that is disappointing..." 
else:
    print "sorry, i don't understand your answer, i'm a program!"

while

# while statement
answer=""
while answer!="yes":
    answer=raw_input("are you happy, today? ")
    if answer=="yes":
        print "good answer!"

for

# for statement
for count in range(10):
      print count,

  • using math module

    to import a module, add a line in the beginning of your file containig the module's name:

    from math import *

(or

    import math

)

    see also numpy module for standard scientific tools and scipy module for even more functions; use pylab module to plot graphics.

  • some operators and functions for strings

    my_string='hello'      #create a string

    my_string[n]          #access the character in the index n

    len(my_string)        #get the number of characters in that string

    text=x+y              #concatenate [i.e. join] strings x and y, forming the variable text

  • some logical and comparison operators

    and, or, not, ==, !=, >, <...

  • functions

    an example:

# defining a simple function
def calculate_value(x_in, y_in): 
    total = x_in+y_in
    return total

# calling the previous function and print its returned value
x=input('insert x: ')
y=input('insert y: ')
result = calculate_value(x, y) 
print result

  • list objects

my_list = []                  #create an empty list

my_list.insert(n, element)    #insert an element in position n

my_list.append(element)      #insert an element at end of the list

del my_list[n]                #delete an element by index number

my_list.remove(element)      #delete an element by value

my_list[n]=element            #change an element

max(my_list)                  #alphabetically last or largest element

min(my_list)                  #alphabetically first or smallest element

my_list.reverse()            #change the list to reverse order

my_list.sort()                #order the list

  • dictionary objects

my_dict = {}            #create an empty dictionary

my_dict.keys()          #return the list with keys of my_dict

my_dict.values()        #return the list with values of my_dict

my_dict.items()        #return the list of pairs of key and value

  • file handling

file = open("my_file.txt", <mode>)    #open file, the mode can be: 'r' for reading, 'w' for writting or 'a' for adding

file.close()                          #close file

text = file.read()                    #read all file content to a string called 'text'

file.write(text)                      #write text to file

(you can search code examples with lists, dictionaries or files in the web...)

  • plot a graph

if the mudule pylab is not already installed in you computer, you must install it to run this code:

from pylab import * 

#define the function and its limits 
x=arange(0, 10, 0.01) 
function='sin(x)' 
y=eval(function) 

#plot the graph, title and axis labels 
plot(x, y) 
ylabel('y axis...') 
xlabel('x axis...') 
title('plotting y='+function) 
show()


  • Vote 1

Share this post


Link to post
Share on other sites
SirDave

Parece-me bem...


Be nice to see your eyes, blink them from time to time to relax your retina when using the computer. Blink now!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.