Guide for learning bacic programming concepts with Python. Excercises were taken from learn Python the hard way. To learn some previous basic concepts you can visit About Programming
We recently found out that this tutorials are no longer free. We are working for an alternative.
The following tutorial was made for a workshop, it was intended to be
completed with a teacher, not to be done alone.
Open a terminal and execute Python
. That will open a Python interpreter. Type
the following lines one by one a see the output of each of them.
print "Hello world"
variable_to_print = "Hello world 2"
print variable_to_print
a=2
b=3
c=a+b
print c
print 2**100
Now to exit type:
exit()
We are now going to clone the material that we are going to be using
git clone https://github.com/degv364/capacitaciones_python.git
We are going to create our first program. Go to the directory where you want to
have your program and create a file ending in .py
. Then open the file with
your favourite editor (emacs, gedit, vscode...)
emacs fibonacci.py
Now write the following program:
#!/usr/bin/env python
# print the first 100 non-trivial fibonacci numbers
def main():
#creamos la variable inicial
finonacci_last=1
fibonacci_last_last=1
for i in range(100):
#creamos el nuevo termino de laserie
fibonacci_current=fibonacci_last+fibonacci_last_last
#hacemos update de los 'last'
fibonacci_last=fibonacci_current
fibonacci_last_last=fibonacci_last
#imprimir el resultado
print fibonacci_current
if __name__=="__main__":
main()
You can execute the program with:
python fibonacci.py
As a challenge, write the program such that every term can be stored in a list.
Don't program your code on your global area, make a main function and to stuff there. To execute this main function when you run your python program use:
__name__="__main__":
main()
To catch signals:
import signal
def signal_handler(sig, frame):
print "Terminating ", __file__
stop=True
stop=False
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
and later you can use variable "stop" to close the program correctly. You could also try to do this at the signal_handler directly if you think is more appropriate.