Docsity
Docsity

Prepara tus exámenes
Prepara tus exámenes

Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity


Consigue puntos base para descargar
Consigue puntos base para descargar

Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium


Orientación Universidad
Orientación Universidad


Funcions s'informatica, Apuntes de Ingeniería Química

Asignatura: Fonaments d'informàtica, Profesor: Vicenç Gonzalez(l'avi), Carrera: Enginyeria Química, Universidad: UPC

Tipo: Apuntes

2013/2014

Subido el 19/11/2014

salhjas
salhjas 🇪🇸

4.3

(6)

7 documentos

1 / 10

Toggle sidebar

Esta página no es visible en la vista previa

¡No te pierdas las partes importantes!

bg1
7 Functions
October 12, 2014
Figure 1: BY-SA
1 Functions
A function is a sequence of statements that work together, and receives a descriptive name.
1.1 Function definition
The syntax to define a function is:
def Name(Parameters):
Statements
The Name can be any word or group of words. The only restriction is that it cannot be a Python reserved
words.
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
There can be any number of statements inside the function, but they have to be indented from the def
statement. The usual number of spaces to indent is 4, as recommended in the PEP 8.
In [1]: def myFunction(s):
print("My string: {}".format(s))
myFunction("Hello")
My string: Hello
For example, we want to draw a square with a turtle:
In [2]: import turtle
def drawSquare():
wn =turtle.Screen()
1
pf3
pf4
pf5
pf8
pf9
pfa

Vista previa parcial del texto

¡Descarga Funcions s'informatica y más Apuntes en PDF de Ingeniería Química solo en Docsity!

7 Functions

October 12, 2014

Figure 1: BY-SA

1 Functions

A function is a sequence of statements that work together, and receives a descriptive name.

1.1 Function definition

The syntax to define a function is:

def Name(Parameters): Statements

The Name can be any word or group of words. The only restriction is that it cannot be a Python reserved words.

identifier ::= (letter|"") (letter | digit | "")* letter ::= lowercase | uppercase lowercase ::= "a"..."z" uppercase ::= "A"..."Z" digit ::= "0"..."9"

There can be any number of statements inside the function, but they have to be indented from the def statement. The usual number of spaces to indent is 4, as recommended in the PEP 8.

In [1]: def myFunction(s): print("My string: {}".format(s))

myFunction("Hello")

My string: Hello

For example, we want to draw a square with a turtle:

In [2]: import turtle

def drawSquare(): wn = turtle.Screen()

alex = turtle.Turtle()

alex.forward(50) alex.right(90) alex.forward(50) alex.right(90) alex.forward(50) alex.right(90) alex.forward(50) alex.right(90)

drawSquare()

turtle.mainloop()

We have draw an square, but we happens if we want to draw a square, and afterwards do a new action. In this case, we can pass the turtle as a parameter:

In [3]: import turtle

def drawSquare(t): t.forward(50) t.right(90) t.forward(50) t.right(90) t.forward(50) t.right(90) t.forward(50) t.right(90)

In [4]: wn = turtle.Screen() alex = turtle.Turtle()

drawSquare(alex)

turtle.mainloop()

Now we can create a new geometric figure:

In [5]: wn = turtle.Screen() alex = turtle.Turtle()

drawSquare(alex) alex.right(45) drawSquare(alex) alex.right(45) drawSquare(alex) alex.right(45) drawSquare(alex) alex.right(45) drawSquare(alex) alex.right(45) drawSquare(alex) alex.right(45) drawSquare(alex)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(alex, squareSize) alex.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(alex, squareSize) alex.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(alex, squareSize) alex.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(alex, squareSize) alex.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(alex, squareSize) alex.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(alex, squareSize) alex.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(alex, squareSize) alex.right(45)

turtle.mainloop()

It is important to notice that the definition of the function must be done before it is used. If not, it cannot be used:

In [8]: helloWorld()

def helloWorld(): print("Hello World!!!")

NameError Traceback (most recent call last)

in () ----> 1 helloWorld() 2 3 def helloWorld(): 4 print("Hello World!!!")

NameError: name ’helloWorld’ is not defined

The statements inside the function are not executed unless the function is called.

In [9]: def helloWorld(): print("Hello World!!!")

In [10]: helloWorld()

Hello World!!!

A function can also call other functions as the forward. We can also create a function to create squared spirals:

In [11]: def squaredSpiral(t, size): squareGain = math.sqrt(2)- squareSize = size

drawSquare(alex, squareSize) t.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(t, squareSize) t.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(t, squareSize) t.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(t, squareSize) t.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(t, squareSize) t.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(t, squareSize) t.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize drawSquare(t, squareSize) t.right(45)

stepSize = squareSize*squareGain squareSize = squareSize + stepSize

In [15]: myFunction?

In [16]: def displaceAndTurn(t, distance, angle): ’’’Function that based on the turtle (t) moves a distance (distance) and afterwards rotates an angle (angle). It provides no result’’’ t.forward(distance) t.left(angle)

In [17]: import turtle

wn = turtle.Screen() alex = turtle.Turtle()

displaceAndTurn(alex, 100, 90)

turtle.mainloop()

In [18]: import turtle

wn = turtle.Screen() alex = turtle.Turtle()

displaceAndTurn(alex, 100, 90)

In [19]: displaceAndTurn(alex, 30, 60)

In [20]: turtle.mainloop()

1.4 Function identification

The identification of functions is an important aspect of programming, and one of the most fuzzy tasks. In this section, we will try to define an strategy to identify the functions, to improve the coding and its readability. The propossed strategy follows a top-down-bottom-up approach. The first step is to identify the problem to solve. Usually a problem is too complex to be solved in just one step. For this reason, the problem must be divided in smaller problems until it can be solved just at once. This process is equivalent to solving a mathematical problem. If we have to find a solution of a problem, first we analyze the information provided in its statement. Based on this information we will analyze which steps/tasks are needed to solve the problem. If a step or task is too broad, we should subdivide it in smaller problems. Finally all the subproblems will be at an atomic level, meaning that they are simple enough to be solved by the tools we have at hand. This is what is called a top-down approach. Afterwards, we will start to construct the solution, solving every atomic subproblem, and providing the results to the following steps/tasks. This will allow us to find the final solution. This is a bottom-up approach, where we construct the solution from its foundations. It is important to notice that both approaches are usually not done one after the other, but they are intermixed, as sometimes a problem that seems to be atomic, has to be subdivided another time. And also, there could be libraries that provide solutions to a problem We will consider every subproblem a function. So a function can be a leaf function if it solves an atomic problem, or a node function if it solves a problem using other functions. As a result, solving a problem requires a tree of functions that interchange information to reach the desired result. An example would be drawing a dummy.

1.4.1 Problem definition

As said previosly, we want to draw a dummy. So we have to define the function dummy(). We have also to think about the arguments. As a first approach we will just put the turtle.

In [21]: import turtle

def dummy(t): ’’’dummy draws a dummy on the screen using the turtle t.’’’

TODO: draw the dummy

pass #Indicates that nothing has to be done

Now we have to think which tasks shall be done. As a first approach we will try to draw a basic dummy:

Figure 2: Simple dummy

We can see that it is composed by a head made with a circle, the body which is a line, the arms drawn with a single line, and the legs using and inverted ‘v’. We can define the corresponding functions for every part:

  • Head
  • Body
  • Arms
  • Legs

The dummy function becomes a tree: The arguments shall take into account the turtle and the size, to ensure a proper relationship:

In [22]: def head(t, size): ’’’head draws a head.’’’

TODO: draw the head

pass

def body(t, size):

For this, we can include new functions inside the head() function:

  • Eyes
  • Smile

Problem: write the functions that will allow to draw an smiling face.

Following this process, we can improve our dummy until it has the level of detail desired. We can also add the argument size to the dummy function, and calculate the sizes of the other elements proportionally. In brief, the process of solving a problem inside a computer is an iterative procedure, where the problem is solved in different steps following the top-down-bottom-up procedure to achieve the desired quality.