Programmer Notes (Object-Oriented)
Programmer Notes (Object-Oriented)
Introduction
To achieve this:
Interpret flowcharts that contain the requirements that will be translated into
algorithms.
Code instructions using a formal programming language.
Clean the code to detect errors and correct them.
Check that the program works correctly.
Document the code to facilitate its maintenance.
If you're interested:
Level 01
Lesson 01
They must be written in a predefined language (C, C++, C#, Python, PHP, Java,
Basic), for the interpretation of a computer.
There are many areas of application for programming, some of the most
common are:
Lesson 02
Identify the elements present in the structure of a program and how to start one.
in pseudocode.
To familiarize yourself with the logic of programming, you will start to develop
algorithms with pseudocode, this means that you will write instructions in Spanish but
following the structure of a formal programming language.
Data entry. In this section, variables are declared and external data is captured.
so that they are loaded into the program's memory.
Algorithm. They are the sequential instructions responsible for processing the data.
Result printing. They are responsible for displaying the processed data.
To write pseudocode, you will use software called PseInt, which provides the
environment and the necessary tools for the task.
The basis of a program with pseudocode are the reserved words, these guide the
execution and cannot be used to identify variables or other elements, since
an error would occur, to create a program in pseudocode, open the file menu of
PseInt and select the New option, then use the following syntax:
Starts with the word process, adds a space and then the identifier of the
program MyProcess, to indicate the end of the program, use the word EndProcess,
between these two lines you should write the rest of the program, that is, the
instructions that will be executed, use a semicolon to indicate the end of each
instruction.
Programming in pseudocode will allow you to develop the skills you will need.
to design complex algorithms in formal language.
Data types. The types of data that you can store in variables are:
Character. They are data that contain one or more letters or symbols that will be
processed as text, to use a character data type, you must write it
in single quotes, especially when introducing numbers, in this way, the
the program will be able to differentiate the value of its symbol.
Integer. These are data that contain whole numbers, that is, without a decimal point.
Real data are of decimal point number type.
Logical. This type of data can only have one of two values,
true or false.
Variable declaration
The declaration serves to inform the program of the number of variables that
will use, the name with which they will be identified and the type of data that will be stored, for
example, to declare a variable called 'age' that stores integer numbers,
enter the reserved word DEFINE followed by a space, then add the variable
AGE and again add a space, finally write the reserved word AS
followed by a space and the data type which in this case is INTEGER, ends with a period and
coma.
Process My_process
Define age as Integer;
FinProcess
Process My_process
age < - time;
FinProcess
The input and output instructions allow the program to interact with the user,
receiving the data you need to execute your process and display the results of your
execution.
An output instruction is one that generates a visible result on the screen, the
The instruction used in pseudocode is WRITE and its syntax is as follows:
Enter the word WRITE followed by a space, then add the text that
if you want to visualize in double quotes, you can add more phrases separated by
commas, ends with a semicolon.
Process My_process
Define age as Integer;
age<-0;
What is your age?
FinProcess
To input data into the program during execution, instructions are used
input, the instruction for pseudocode is READ and its syntax is very simple:
Enter the reserved word READ, followed by a space, then write the
identifier of the variable in which you will store the captured data, ends with a period and
coma.
Process My_process
Define age as Integer;
age<-0;
Write 'What is your age?'
Read age;
FinalProcess
When the READ instruction is used, the program stops to record in the variable
specified, the values of all the keys pressed by the user until a key is pressed
ENTER.
Finally, you must display the results on the screen so that the user can
visualize them using an output instruction, for this:
Enter the instruction WRITE again, add a space and the phrase 'The age
what you entered is”, finally add a comma and the variable AGE, whose value you will show,
finish with a semicolon.
Process My_process
First program
Define age as Integer;
age<-0;
What is your age?
Read age;
The age you entered is
FinProcess
// Add a comment, starting with two slashes on the line following the start
of the process, in this way the program will know that it is not an instruction, to
visualize the result, press Run on the toolbar, and enter the data
that the program requests, save your progress with the name 'exampledata.psc'.
Arithmetic operations
A program allows you to perform arithmetic operations that will not only be useful to you
to solve mathematical problems, but they will help you control the execution of the
same. To perform arithmetic operations with pseudocode you will use four
basic operators addition, subtraction, multiplication, and division. In addition to fixed values, a
a variable can store the result of arithmetic operations, consider that if you
operation involves the use of numbers with a decimal point, the variables must be of type real,
for example, to calculate the area of a triangle, the program must request the user
please enter the values of the base and the height to display the result of the calculation, do
the following:
Create a new file and name the process as AREA_TRIANGULO, declare three
variables, BASE, HEIGHT and AREA that will be the final result, with the instruction
WRITE, asks the user to enter the value for base and uses READ to save it
data, repeat the instructions WRITE and READ, to store the data of HEIGHT, assign
to the variable AREA, the result of the product of the base by the height divided by two, this is
it is the general formula to calculate the area of a triangle, finally, display on the screen
the value of the variable AREA as a result for the user, observe that the multiplication
it was enclosed in parentheses, in this way, the program that must carry it out beforehand
that the division, regardless of the hierarchy of the operators, saves your progress
like "ejemplotriangulo.psc".
Triangle_Area Process
Define base As Real;
Define height as Real;
Define area as real;
Modulo Operator
Within the arithmetic operators, there is also the modulo operator, its
the function is to obtain the remainder of the division of two integers, this operation is useful
for cases where it is desired to know if one number is a multiple of another, for example, if
a number entered by the user is a multiple of two, the modulus of that number between
two will be zero.
Relational Operations
Relational operators perform comparisons between two data of the same type
which can be fixed, come from the result of an operation or be the value of a
variable. The program evaluates the values of the compared data. If the proposed relationship
for the operator the comparison holds, the returned result will be true, of the
the opposite will be false.
Logical Operations
Logical operators are used to compare boolean values, that is, those
whose value can only be true or false.
AND Operator. It works similarly to connected water faucets one after another,
the water will only flow when all the involved taps are open, if any is
closed, the water will not pass until the exit. In the same way, the value of all the data,
compared in the operation is true, the result will be true, but if one or more
it is false the result will be false.
NOT operator. It inverts the value of a boolean data, for example, if it is true then
using the NOT operator the result will be false and vice versa, this would be a strange type of
key that allows the passage of water when closed and blocks it when open.
Lesson 03
Decision structures
So far you have only seen algorithms that always follow a sequence of
continuous steps, however, there are also cases in which the procedure to
to follow, depends on whether one or more specific conditions defined by the
use and combination of relational and logical operators.
In these cases, you must implement decision structures that can be of three
types: Simple, Double or Multiple.
To start, select file in the menu and choose the OPEN option, select the
file saved as "example1.psc" and press the OPEN button.
Simple Decision
Imagine that you are walking down the street on your way home and you see a person, if you know them.
you greet and continue otherwise you just keep walking. Likewise, a
simple decision serves to check the result of a logical or relational operation, which
determine if a secondary procedure is executed before continuing with it
main procedure. To write a decision structure in pseudocode:
Locate the line of code where the value of AGE is read and add a newline.
after the semicolon, enter the reserved word IF and a space, type the
relational expression whose logical result you will evaluate, in this case the condition is that the
value AGE is greater than 5, add a space and then the reserved word
THEN, add the lines of code that will be executed in case the condition
it is fulfilled, for this example it will be the print instruction on screen with the text 'The
the age you entered is greater than 5", includes the FINSI instruction to finish; save
this example with the name "exampleSI.psc", with the SAVE AS option in the menu
FILE.
Process My_process
Define age as Integer;
age<-0;
Write "How old are you?";
Read age;
If age > 5 Then
The age you entered is greater than 5
FinSi
The age you entered is:
FinProcess
Double Decision
Revisiting the previous example, imagine that this time you know the person you saw,
if it is a friend you greet him and give him a hug, if it is not a friend, you just
you greet and then continue walking, unlike the simple decision, the structure of
double decision executes one procedure if the logical condition is met and another different if
the logical condition is not met; in any case the algorithm executes a procedure
secondary and then continues with the main procedure, a double decision in
pseudocode, it is used in a similar way to the simple structure, but before finishing
with the FINSI instruction, follow these steps:
Type the reserved word ELSE, add the instructions in the following lines
that must be executed if the condition is not met, to complement the example
previously, in this part use the instruction WRITE and the text 'The age you entered NOT
is greater than 5”, finally, it ends with the FINSI instruction; save this example with the
name "exampleIfNot.psc".
Process My_process
Define age as integer;
age<-0;
What is your age?
Read age;
If age > 5 Then
The age you entered is greater than 5.
SiNo
The age you entered is NOT greater than 5.
FinSi
The age you entered is:
FinProceso
Multiple Choice
Now we are going to include in our example the time of day, again it is about a
known person, so when greeting you say good morning if the clock shows less than
twelve in the afternoon, good afternoon if the clock is between twelve and seven in the afternoon, and good
Nights if they go past seven. In multiple choice, the operation can generate
results with more than two different values and each value can generate a
different secondary procedure, the syntax for multiple decision is as follows:
Start by entering the reserved word ACCORDING to and a space, then add the
expression or the variable whose result or value is going to be evaluated, in this case AGE, add
a space and the reserved word DO, in the next line enter the first value
possible of the variable or evaluated expression followed by a colon, add the instruction
WRITE that will execute if the evaluated data matches this value, repeats both
previous steps for each value that the evaluated variable may have. Enter the
instruction IN ANOTHER WAY followed by the instructions that will be executed next
of the possible values, in this way the remaining values are covered, finally
enter the FINSEGUN instruction, to end the structure; save this example as
exampleaccording.psc
Process My_process
Define age as Integer;
age<-0;
What is your age?
Read age;
According to age Do
0:
The value is less than 3
1:
The value is less than 3;
2:
The value is less than 3
3:
The value is less than 5
4:
The value is less than 5
In another way:
The value is greater than 4;
FinSegun
The age you entered is:
FinProcess
Declaration of vectors
Vectors are useful when you want to store a set of data that have
relationship with each other, or when the same data has different values, for example, the
ages of a group of people.
Process My_process
Define age as Integer;
Age dimension (3);
age<-0;
What is your age of the person?
Use of vectors
To access the elements of a vector, you must take into account that the number of
the elements or dimension of the vector is not equal to the position or index of its elements, the
the index of the last element of a vector will be equal to the total number of elements minus
one, this is because the position starts at zero, that is, if a vector is declared
three elements their positions will be 0, 1 and 2; in pseudocode you can access the
elements of a vector in the following way:
Delete the assignment instruction for the variable AGE, start with the instruction
WRITE and the phrase “What is the age of person 1?”; use the instruction READ,
followed by the identifier of the vector AGE and a parenthesis with the position number that
if you want to use, repeat the previous step two more times to enter the two positions
remaining of the vector, use the WRITE instruction to display the data saved in it
vector with the phrase "The entered ages were:"; adds each position of the vector
AGE in an instruction WRITE with the number of the person to whom it corresponds
value; save this example as 'examplevectors.psc'
Process My_process
Define age as Integer;
Age dimension (3);
Place the cursor on the line where the size of the vector is defined, before the number 3
add the number two and a comma, add a zero and one to each instruction reading
comma before the index of the variable AGE, repeat the same for the three instructions
of writing, with this instruction you ask the program to write in each position in
the first row of the matrix AGE; save this example as 'examplematrices.psc'.
Process My_process
Define age as Integer;
Dimension age (2,3);
It is possible that in the future you will find references to matrices and vectors as
array arrangement, which are very common terms for these structures in the field
computer scientist.
Repetition structures
To get started, open the file "ejemplovectores.psc", notice that the reading of the
the value for the elements of the AGE vector consists of only two instructions that
repeat for each element, this can be simplified using a loop as you will see
continuation:
WHILE structure.
Process My_process
Define age as Integer;
Define iteration as integer;
Age dimension (3);
Iteration<-0;
While iteration<3 Do
Write “What is the person's age”, iteration+1,”?”;
Read age (iteration);
Iteration<-iteration+1,
Until the end
REPEAT Structure.
Unlike the WHILE loop, the REPEAT loop checks the condition at the end of the
execution of the instructions, that is, the instructions of the loop, will be executed by
less than once. To use a REPEAT loop, the following syntax is used:
Replace the reserved word WHILE and the condition ITERATION<3, with the
reserved word REPEAT, replaces the reserved word ENDWHILE, with the
reserved words UNTIL and THAT, separated by a space and the condition
ITERATION<3; save this example with the name "example_repeat.psc".
Process My_process
Define age as Integer;
Define iteration As Integer;
Age dimension (3);
Iteration<-0;
Repeat
Write "What is the person's age", iteration+1,"?";
Read age (iteration);
Iteration<-iteration+1,
Until iteration<3
PARA structure.
Start the structure by replacing the reserved word REPEAT with the word
reserved FOR, followed by the assignment of the initial value zero to the variable
ITERATION and a space, write the reserved word UNTIL followed by a space
and the final value in this case two, enter a space and the reserved words WITH and
STEP followed by a space and the increment in this case is one, add a space
and the reserved word DO, finally replace the instruction WHILE and the
previous condition by the reserved word FINPARA, like the increment to the counter
it is automatic, it will not be necessary to have it within the instructions of the cycle; save
this example with the name “ejemplopara.psc”.
Process My_process
Define age As Integer;
Define iteration As Integer;
Age dimension (3);
Iteration<-0;
FinPara
Repetitions are useful for performing summations and are used constantly.
in operations or procedures with vectors.
Level 02
Lesson 01
Advantages
Installation
Before you start programming, you must create a project by following these steps:
Click on FILE and select NEW PROJECT, choose the location where it will be saved.
the project, name it and check that the interpreter is Python, in projects it will appear the
folder, right click on it and choose NEW and then FILE, name the file as
Hello World and select Python as the file type. When creating projects
you will keep their files organized and you will be able to group programs and subprograms
that are related to each other.
When you create your first program, consider that the syntax of the instructions
be correct to avoid mistakes, do the following:
Click in the editor, use the hashtag symbol (#) to write text as headers
or comments, use the PRINT command, leave a space and in quotes write "Hello
World
in the console the result.
Lesson 02
Data structure
Data structures are arrays that are used to store values and
manipulate them later, they are divided into three types: Lists, Tuples, and Dictionaries.
Lists
Lists can contain numbers, variables, strings of text, and even others.
lists consist of a variable to which the list is assigned, the elements
separated by a comma, brackets that serve to contain the elements.
Robot= [“bípedo”,6,[“caminar”,”correr”,”saltar”]]
Each of its values has an automatically assigned index and the count
starts with zero, for example, if a list has four elements, the indices go from
zero to three. Two common applications of lists are obtaining and writing
some of its elements, to obtain an element, follow these steps:
Create another variable and set it equal to the list, open a bracket, put an index, in this case
one, and close the bracket, print the variable, if you need to access a list inside
another list, put in a first bracket the index of the nested list and in the second the
element index.
Robot= [“bípedo”,6,[“caminar”,”correr”,”saltar”]]
Variable1 = robot[2] [1]
Print variable1
To rewrite its elements, choose the list followed by the bracket index, place
the new value or text string as the case may be,, print the list to verify that
the change was made.
Robot= [“bípedo”,6,[“caminar”,”correr”,”saltar”]]
trotar
Print robot
Tuples
Tuples are similar to lists with the following differences, their elements are
they are enclosed in parentheses, they cannot be modified, that is, you cannot add or
remove elements.
Dictionaries
They are structures that associate a key with a value, consisting of:
In dictionaries, it is possible to change the values, but not the keys, just like
with lists, it is common to require the obtaining of values from dictionaries, for
do it:
Create another variable, equal it to the key of the dictionary, in case it is a list or
tuple, adds the index of the element, prints the variable.
A logical decision instruction is used to choose the path that must be followed.
program, based on the use of relational and boolean operators. For
exemplify the use of logical decision instructions, you will write a program
simple, just ask how many books you read annually, do the following:
To understand what a nested logical decision is, imagine that you are driving a
On a main road, at a certain point there is a detour and you have to decide what
taking a path, this represents a primary decision, at another point there is another
deviation, this would be a secondary decision, along the way you make several
decisions, until reaching your destination, which represents the end of the program.
Write in the editor an entry to ask if you work from home, use the
IF instruction for the true case and print the result, do the same with the case
opposite and print the result, create an input to ask for travel time
at work, nest the necessary conditionals using relational and logical operators
to determine if it is a short time, if it is a reasonable time or if you should look for others
routes, test the program with different times, use the appropriate syntax and print
the results of each conditional.
If question == False:
You work outside the home
The important thing about logical decisions is to ask the right question to
minimize the length of the programs you make.
Repetition Instructions
They are structures that repeat a certain number of times a set of lines
of codes, in Python two are used: WHILE and FOR.
A simple example of using the WHILE instruction is to calculate the table of seven,
follow these steps:
Create a new file "Use of While" and add a header, use "i" as
variable with an initial condition equal to one, use a WHILE setting as condition
finally the number ten, that is to say, that the program will make ten repetitions, write in a
variable the number seven and multiply it by the variable 'i', print the result using
texts and strings to give presentation, increase the variable 'i' to go
multiplying by each number up to ten, run the program to verify its
operation.
To do the same example now with the FOR instruction, follow these steps:
Add a header, use a FOR with the variable 'j', to assign values use
RANGE from one to eleven, consider that the maximum value is not taken into account, print
the result using texts and strings for presentation, increments the variable 'j'
to keep multiplying by each number up to ten.
Functions
Write a header for what each function is used for, name them, generate one
input to generate the necessary values for the calculation, write the operation
arithmetic and prints the result.
Calculation of areas
F = 3.1416
Area of the square
Def square():
True
while i==True:
area = input("Choose the geometric figure to calculate its area \nSquare =
Triangle = 2
if area==1:
square ()
else:
Enter a valid option
i=input (" Do you want to calculate the area of another figure Yes=True No=False ")
Once the instructions have been created, it's time for the main program, in this case,
it will be a menu, do the following:
The use of functions should be prioritized as they allow you to divide your work into
blocks that you can identify and reuse in other projects, reducing the time of
programming.
Object-Oriented Programming
Objects
To start using an object, you must first create the template of its class, a
this process is called class declaration, which is similar to the declaration of
functions that you already know. Next, you will create a program using orientation to
objects to store some data of a person such as their name and age.
Declaration of a class
Place the cursor inside the class declaration and write the reserved word
DEF followed by a space, write the name of the constructor method, starting
by two underscores, followed by the word INIT and two more underscores, opens a
(SELF):
Python requires the word SELF to be able to access the rest of the methods and
attributes within the class, that is why it must be the first parameter of all methods
of class.
class Person:
def __init__(self):
Now to create the attributes AGE and NAME within the constructor use the
following syntax:
Inside the constructor method, write the word SELF, followed by a dot and the
variable name AGE, which will be the first attribute, assign the value of 18 to
attribute AGE, repeat the previous instruction on a new line to create the attribute
NAME and assign it the value JUAN, to know if the object has been created
correctly, write the following screen print instruction, write the
the PRINT instruction adds the text "It has been created at" and adds a comma, for
concatenate the attribute SELF.NAME, then concatenate the text 'of' and the variable
SELF.AGE, using commas again.
class Person:
def __init__(self):
self.age = 18
self.name = "Juan"
It has been created for
To verify that the class is correct, create a new object in the following way:
class Person:
def __init__(self):
self.edad = 18
Juan
print “Se ha creado a”, self.nombre, “de”, self.edad
juan = Person()
Now that you have created attributes for an object, you will learn to define its
behavior, adding methods to the declaration of your class.
Use of methods
Method Declaration
Type the reserved word DEF and a space, type the name of the function that
it will be SPEAK, open a parenthesis and write the parameter SELF and a comma, add a
parameter most called WORDS and closes the parenthesis, adds the PRINT instruction
a space and the following parameters separated by a comma, the variable
SELF.NAME is the NAME attribute of your PERSON class, the string two
points space between single quotes, finally add the variable WORDS that
you declared as a parameter of the method.
class Person:
def __init__(self):
self.edad = 18
Juan
It has been created for
juan = Person()
Execution of methods
To execute the method you just created, go to the part where you instantiated the
object JUAN of the class PERSON, in the next line write it again
name of the object JUAN a point and the name of the method that will be executed SPEAK,
("Hello, I am speaking")
parenthesis, the result of this procedure is to pass the string HELLO I AM
SPEAKING as a value of the parameter WORDS, note that only is being passed
a value to the SPEAK method, remember that the SELF parameter is for exclusive use
from Python, so the program is only considering words like the only
parameter of the SPEAK method, run the program to see the result.
class Person:
def __init__(self):
self.edad = 18
self.name = "Juan"
It has been created for
juan = Person()
Juan, to speak ("Hello, I am speaking")
class Person:
def __init__(self):
self.edad = 18
Juan
It has been created for
juan = Person()
juan.talk()
juan.speak("Hello, I am speaking")
Use of special parameters
Due to being a language that does not require variable declaration, Python does not allow the
method overloading, however, provides features that make the
more flexible programming, to facilitate code reuse, one of them is the
use of special parameters.
Like any method, the constructor can also include parameters in its
definition, with the aim of preparing processes or attributes of the object, also known
as instance variables, to create more person objects with different
names and ages, you must modify the constructor, add the variables AGE and
NAME as constructor parameters, assigns the value of the parameters AGE and
NAME the attributes SELF.AGE and SELF.NAME respectively, now you must
modify the instance of the object JUAN as follows:
Add the number 18 and the string JUAN separated by a space inside the parentheses.
as in the line that says JUAN equal to PERSON, instantiate another object called LUIS
from the PERSON class, with the number twenty and the string LUIS in quotation marks, invoke the
SPEAK method with the object LUIS just like with the object JUAN, remember that when
instantiating an object, the constructor method is being executed automatically,
so the parameters you pass within the PERSON class will be the ones
requires the constructor, run the program to observe the result and save your
file as "examplevarinstance.py" to be able to consult it later.
class Person:
def __init__(self, age, name):
self.age = age
self.name = name
It has been created for
Person(18, "Juan")
Hello, I am speaking
Person(20, "Luis")
luis.speak("Hello, I am speaking")
In addition to simple variables, the declaration of methods allows the use of tuples and
lists as parameters so that the programmer can handle large amounts
of information in a simpler way.
Open the file 'ejemplometodos.py' and add an asterisk at the beginning of the parameter
WORDS of the TALK method, to indicate that this parameter will receive a tuple,
delete the default value of words, within the definition add the FOR loop
use a variable SENTENCE as the counter of the FOR loop and the parameter WORDS
as the collection that is going to be traversed, the print instruction must remain inside
from the FOR loop, replace the variable WORDS with the variable PHRASE, in the call to
method SPEAK adds the string "This is me", separated by a comma from the first
parameter, run the program to see the result and save the file as
exampledoubleparameter.py
class Person:
def __init__(self, age, name):
self.age = age
self.name = name
It has been created for, self.name, of, self.age
Person(30, "Juan")
Juan says("Hello, I am speaking", "This is me")
luis=Person(18,"Luis")
Hello, I am speaking, This is me
Add one more asterisk to the PALABRAS parameter to indicate to Python that this
parameter will receive a dictionary as a value, in the screen instruction of the loop
FOR replaces the variable PHRASE with WORDS and uses PHRASE as its index within
from brackets, in the invocation of the SPEAK method, add a variable called T1 to
the one you assign the value of the first parameter, add a second variable called
T2, for the value of parameter two, run the file and observe the result,
finally save the file as 'exampledictionaryparameter.py', in order to
consult it later.
class Person:
def __init__(self, age, name):
self.age = age
self.name = name
It has been created for
def speak (self, **words):
for phrase in words:
print self.name, ': ', words[sentence]
Person(30, "Juan")
Hello, I am speaking
luis=Person(18,"Luis")
Hello, I am speaking
The variable that is used to receive tuples, lists, or dictionaries should always be declared.
As the last parameter, Python will know that the rest of the values passed as
parameters, are part of the tuple.
Methods are used to perform operations within the object and to interact
with the main program and other objects.
Lesson 04
One of the most common goals for the programmer is code reuse,
object-oriented programming contributes to achieving this goal with characteristics such as
inheritance.
Inheritance
Class Person:
Overwriting
Sometimes, classes have attributes and methods that are used only in the
execution of internal processes, so they do not need to be accessed from the program
principal or another class.
The encapsulation of attributes and methods consists of differentiating them from those
that will interact directly with the main program and other objects. The information
an object is encapsulated by reserved words known as modifiers
of access, which restricts information at three levels: public, protected, and private.
class Person:
def practiceSport(self):
print self.name, ':I am going to practice';
class Person:
Concealment can also be applied to methods that are only used for their
internal processes or operations, that is, they are executed by other methods within the
class.
Abstract classes
Abstract classes are templates used to define other classes, they establish the
minimum structure that their derived classes must carry without detailing their
functionality.
To define the abstract method SPEAK, check that the name of the
class PERSON after the identifier of ATHLETE, add the
declaration of the METHOD SPEAK with the parameter asterisk WORDS, prepared for
tuples, add a FOR loop in the definition of the SPEAK method to read the values of
words, add a print in the loop for the obtained values of words like
in the previous example, run the code, notice that this time the program runs without
problem.
Lesson 05
File types
There are libraries that allow Python to perform operations with other types of
more specific files. In addition, there are standardized formats such as XML and JSON,
that structure the information to facilitate its transfer between languages of
programming.
In Python, the basic operations with files are creating, writing, and reading lines from
code, these operations are identified by the following syntax:
A variable to which the data to read or write is assigned, the OPEN instruction
which opens the file, the path and the name of the file to be used with its extension, if it is in the
current folder, it is not necessary to specify the path.
Test=open('c:Users/Beto/data.py','w)
There are two ways to open the file:
Create the function escritura with three inputs, assign to the variable PRUEBA the path where
you will save the file and choose the write mode (w), write the three data into the variable,
print the text writing to ensure that it is being written, close the file, send
to call the function and check the result.
Test.close
Writing('Hello',
World
‘Nice’
Create the function LECTURA, assign to the variable PRUEBA, the file path and choose the
reading mode (r), prints the variable TEST with the READ instruction, closes the file,
call the function and verify the result
Test.close
Writing('Hello',
World
Beautiful
Def read():
Test=open('c:Users/Beto/data.py','r)
Print(test.read())
Test.close()
Reading()
These operations allow you to work with files of other extensions and even
export data.
String Methods
Since strings are objects, they also have methods. The most commonly used are:
Split("x",number) Searches for characters equal to "x", removes them and organizes new ones
sub-strings. The number of times it removes the characters can be modified.
Find("x") Search for the character "x" from left to right and return the index where
is located.
Rfind("x") Searches for the character "x" from right to left and returns the index where
is located.
Join("x") Join the elements of a tuple or list with the element "x".
The program distinguishes between uppercase and lowercase letters, and it also recognizes spaces.
as characters. Take this into account when executing the methods you just learned.
List Methods
Index(x) Searches for the index of 'x' in the list; if not found, it marks an error.
Append(x) adds the element “x” to the list starting from the last value.
Count(x) Counts the number of times the value 'x' appears.
Insert(index,x) Inserts the value 'x' at the index you choose and shifts the others.
values of the list.
Pop(index) Removes the value from the list according to the index you choose.
The program distinguishes between uppercase and lowercase letters; it also recognizes spaces.
as characters. Keep this in mind when executing the methods you just learned.
Lesson 06
Start a window
The first step to creating an interface is to generate a window in which you will be able to
add other elements, for this:
Create an object called WINDOW of the class TK(), it contains the elements
necessary to start the graphics engine of the operating system, add a call to the
MAINLOOP window method, this method starts an infinite loop that allows the
program to monitor the actions in the window, if you run the code at that point, it
it will open a small window with the minimize, maximize, and close buttons, when pressing the
the close button will stop the process initiated by MAINLOOP and will close the window.
One of the simplest elements is the tag that serves to add fixed text.
inside the window, the labels are added by creating instances of the LABEL class and
they require two main parameters, the CONTENEDOR object of the label and a
DICTIONARY with the characteristics of the object, the most common are TEXT, it is the text
from the label, FG the name in English of the text color, BG the name in English of the color
from the background of the label, follow these steps to add a label to your window:
Declare a phrase called INTERFACE, declare the constructor and add a parameter
called CONTAINER, create an object named SELF.E1 of the LABEL class, add the
CONTAINER object as the first parameter, the object you pass as a parameter
this label will contain, add TEXT equal to LABEL1 as the second parameter and
first element of the dictionary, add FG equal to BLACK and BG equal to WHITE, like
second and third element of the dictionary, to indicate that the text will be black with background
white, finally add a call to the PACK method of the SELF.E1 object to indicate,
to indicate to the program to add this element to its container; save the code and
run it. Note that the label is just informative text, so you cannot
interact with it and take any action, the next step will be to learn to organize the
elements in the window.
Interface class:
A digital form is a structure that serves as a guide for the user to input
specific data that will be processed by a program. In the Tkinter library
there are functions that help create some basic elements of a form, to
the following are these functions and their parameters.
Label. Displays fixed or descriptive text and does not allow user interaction.
with it, class Label(), specific parameters text: static text displayed
General parameters
Organization of elements
To arrange the elements within a window, the Tkinter library has
three content administrators:
Use of Pack
The Pack administrator adds the items as they call the method,
additionally it can be specified if it is desired that the element load towards some
side or fill the remaining width or length of your container, open the file 'ejemplotk1.py':
Add two more tags called SELF.e2 and SELF.e3 with their respective text and
different background colors, add the call to Pack for SELF.e2 and SELF.e3, in the
Pack method of SELF.e1, adds the parameter SIDE=TOP, for the object SELF.e2, passes
SIDE=RIGHT as a parameter and SIDE=BOTTOM for SELF.e3, in the case of SELF.e3,
add one more parameter FILL=X, run the code, drag the bottom right corner
from the window to readjust it, note that LABEL1 remains at the top
from the window and LABEL2 on the left side due to the SIDE parameter, but its
size has not been modified, on the other hand LABEL3 adjusts its width to that of the window,
besides staying at the bottom, due to the values of SIDE and FILL, this
last one forces you to adjust its size in the indicated dimension until filling the space
remaining in its container, save the code as "exampletk2.py".
Class Interface:
Self.e1.pack (side=TOP)
Self.e2.pack (side=RIGHT)
Self.e3.pack (side=BOTTOM,fill=X)
Window = Tk()
myInterface = Interface(window)
window.mainloop()
Use of Grid
To use the GRID manager, it is necessary to specify the row and column in which
to position the element, do the following to see an example:
Agrega tres etiquetas más llamadas e4, e5 y e6, con su respectivo texto y color,
replace the call to the PACK method of e1, e2 and e3 with the GRID method, add a
call to GRID for e4, e5, and e6, uses as parameters of the GRID method from e1
COLUMN=0 and ROW=0, repeat this with e2 and e3 using ROW values of 1 and 2
respectively, do the same for e4, e5, and e6 changing the value of COLUMN to 1,
execute the code. Note that the elements LABEL1, LABEL2 and LABEL3,
they are found in the first column and the rest in the second, save this example as
ejemplotk3.py
Class Interface:
Self.e1.grid(column=0,row=0)
Self.e2.grid(column=0,row=1)
Self.e3.grid(column=0,row=2)
Self.e4.grid(column=1,row=0)
Self.e5.grid(column=1,row=1)
Self.e6.grid(column=1,row=2)
Window = Tk()
myInterface = Interface(window)
window.mainloop()
Use of Place
Remove the tags from e2 to e6, remove the calls to GRID from e2 to
e6, replace the call to GRID in e1 with PLACE, add parameters X=20 and
y=30, these define the coordinates of the element in pixels, add the parameters
WIDTH=120 and HEIGHT=25, to define the width and height of the element respectively,
run the code to see the result, save this example as "ejemplotk4.py".
Class Interface:
Window = Tk()
myInterface = Interface(window)
window.mainloop()
A window can use more than one manager to organize its elements, to
to facilitate this task, frames or frameworks can be used that allow to subdivide a
container.
An event is the reaction of the system to some change in the state of one of its
elements, in the case of interfaces, the change is caused by the interaction of the
user.
Declare an attribute at the beginning of the constructor called SELF.TEXTOE3 of the class
STRINGVAR that will be used later, changes the text of the TEXT parameter of SELF.E1
to CONVERT CELSIUS TO FAHRENHEIT and remove the background color, replace the value of
TEXT for SELF.E2 to CELSIUS and remove the background color, replace the text color of
TEXT parameter of SELF.E3 for FARENHEIT and remove the background color, change the class
from SELF.E4 by BUTTON and the value of the parameter TEXT by CONVERT, define CYAN
as the value of the parameter BG, replace the class of SELF.E5 with ENTRY, remove the
parameter TEXT and change the value of the parameter BG to WHITE, remove the parameter BG
of SELF.E6 and the value of the parameter TEXT.
Now you will change the organization of the elements, first the left column and
then to the right:
Add the COLUMNSPAN=2 parameter to the GRID method of SELF.E1 to indicate that
this element will span two columns, check the parameters of SELF.E2, COLUMN
y ROW have the values 0 and 1 respectively, do the same for SELF.E3 with the
values 0 and 2, use values 0 and 3, for the parameters of SELF.E4 and add the same
parameter that you added to SELF.E1, check that the values of the COLUMN parameters
and ROW of SELF.E5, be 1 and 1, apply the same for SELF.E6 using values 1 and
2, run the code.
Up to this point, you have only created a window and added the elements you need.
the interface, to start adding functionality, you must define what happens
when the user presses the button, for this:
Enter an integer in the text field and press the convert button and then
test with a decimal number, finally enter letters and observe how the console of
The IDE throws an error, this type of error is known as EXCEPTIONS and can be
prevent
Lesson 07
Creation of a table
How to create a table. As an example, new records of novels that you have will be made.
read with data such as title, author, and years of publication. For this, create a file in
blank with the extension '.db' where you will save the table and another with '.py', in which
you will work, follow these steps:
Import the SQLITE3 library, to be able to work with databases, write the variable
CONNECTION, use the CONNECT method with the filename to create the link to the
database, call the CURSOR method of the CONNECTION variable and save it
result in QUERY, this enables the connection, creates the variable TABLE with the
following fields:
Use conditionals to verify the creation of the table and write the two messages.
possible, disable the connection, save the changes with the COMMIT method, close the
connection and run the program. Once this is done, verify that it was written about the
file NOVELAS.DB.
Import sqlite3
Connection=sqlite3.connect ('novelas.db')
query=connection.cursor()
Table="CREATE TABLE table (id INTEGER PRIMARY KEY AUTOINCREMENT NOT
NULL,
name VARCHAR (30) NOT NULL,
"author VARCHAR (40) NOT NULL,"
year INTEGER (9) NOT NULL)
Print (table)
If (consulta.execute(table)):
The table was created
Else:
The table was not created
Consulta.close()
Connection.commit()
Connection.close()
Insertion of records
Import the SQLITE3 library and create a function called INSERTAR, write the variable
DB1, use the CONNECT method with the file name 'novelas.DB', to create the
link to the database, print “You are in the insert function”, create the entries for
ask for the title, author, and year of publication, enables connection with the method
CURSOR, in a variable assign the entries with the corresponding columns of the
table and print it, use the EXECUTE method to execute an SQL statement that in
this case will allow you to query the records of the table, disable the connection and save
the changes, close the connection and call the function, verify the operation
running the program and fill in the fields that it asks you in the console.
Import sqlite3
Def insert():
Db1=sqlite3.connect('novelas.db')
You are in the insert function
Consulta=db1.cursor()
Consulta.execute(strConsulta)
Consulta.close()
Db1.commit()
Db1.close()
Insert()
Record inquiry
Create the function consult and write the variable DB2 uses the CONNECT method with it
file name, to create the link to the database, prints "You are in the function"
insert
with the CURSOR method, execute the SQL statement to make a query with it
EXECUTE method uses the FETCHALL method to save the result of the query,
create an empty list and with a FOR make the arrangement to add the records, disable the
connection saves the changes and closes the connection, returns the list with the instruction
RETURN y calls the function.
Import sqlite3
Def insert():
Db1=sqlite3.connect('novelas.db')
Print ("You are in the insert function")
Consulta=db1.cursor()
Consulta.execute(strConsulta)
Consulta.close()
Db1.commit()
Db1.close()
Def consult():
Db2 = sqlite3.connect("novelas.db")
You are in the insert function
Db2.row_factory = sqlite3.Row
Query = db2.cursor()
Consulta.execute("select * from tabla")
Rows = query.fetchall()
List = [ ]
For row in rows:
S={
S['name'] = row['name']
row['author']
year
Lista.append(s)
Consulta.close()
Db2.close()
Return(list)
Now a selection menu is created to make insertions and queries
automatically follow these steps:
Create a function called MENU, make an input to ask for the options
INSERT, QUERY, use an IF so that in option 1 it calls the function
INSERT, use an ELIF so that in option 2 it calls the CONSULT function
equal its result to a variable called LISTANOVELAS, create a FOR to print it
database, call the function and run tests, to create a repetitive cycle
call the MENU function in the last line of the logical decision instructions.
Import sqlite3
Def insert():
Db1=sqlite3.connect('novelas.db')
You are in the insert function
Query=db1.cursor()
Consulta.execute(strConsulta)
Consulta.close()
Db1.commit()
Db1.close()
Def consult():
Db2 = sqlite3.connect("novelas.db")
You are in the insert function
Db2.row_factory = sqlite3.Row
Query = db2.cursor()
Consulta.execute("select * from table")
Rows = query.fetchall()
List = [ ]
For fila in filas:
S={
row['name']
row['author']
S['year'] = str(fila['year'])
Lista.append(s)
Consulta.close()
Db2.close()
Return(list)
#consultar()
Def menu():
Option=input(" enter the desired option 1.Insert a value into the table 2.Consult
the values of the table
If Option==1:
Insert()
Menu()
Elif Option==2:
NovelList = consult()
For novel in Novel List:
Print (novel['name'], novel['author'], novel['year'])
Menu()
Menu()
Level 03
Lesson 01
Types of errors
In programming, errors are failures that produce incorrect results or that prevent
that the program runs correctly, these can be:
Syntax errors. They prevent a program from running due to poorly written code.
The IDE detects these errors before executing them by underlining them, this error is solved
putting the correct syntax, take into account that not respecting the indentations is also a
syntax error.
Execution errors. They appear in the console when testing the program, they
they solve by purging the lines of code, the most common are:
Infinite loops are processes that repeat indefinitely because they do not
there is a condition that ends the cycle, in this case it is always met
condition that I be less than or equal to 10, because it is never incremented
value of I.
Exception handling
Exceptions are indications for the program to continue functioning when detecting
Runtime errors, there are two types of exceptions:
Several exceptions can be created and priority is established through the order in which they
that are written.
Use the TRY tag to delimit a block of code catching its possible errors,
in case of finding an error the program visits each EXCEPT tag to associate it
an exception and thus execute the instructions of the corresponding label. If not
find some error associated with an exception the lines of code of the
ELSE label, which is normally used to print a message that confirms the good
operation of the program up to that point, it is advisable to use exceptions
for code blocks that are prone to generating errors, for example, when one
ask for an input of a value.
Manual code verification
Select the part of the program that you are going to review, identify all the variables
involved, create a table where you put the number of iterations and the variables,
calculate the values of each variable according to their arithmetic operations in each
iteration, compare the table with the results from the console, when you find an error
identify the responsible instruction.
Confirm that the flowchart corresponds to your program, locate the first block and
verify that your function is fulfilled, do the same with the other blocks, when
if you find any error, correct it and continue the verification.
Debugging verification
Place the breakpoints on the key lines of the code such as, increments of
variables, function calls or arithmetic operations, click on the DEBUG icon,
the console and the debugger will open at the bottom, use the control menu of
debugging to verify your program, it can be line by line or it can run until
the breakpoints, run the necessary tests on the program to confirm its
operation, debugging should be done by code blocks or by each function
to minimize times.
Lesson 02
Before refactoring a program, make a copy to work on it, so you will avoid
lose information, open the IDE select the option to refactor and do the following:
Code documentation
The documentation aims to explain each part of the program so that others
developers, understand it more easily, it can be done by:
Comments begin with the hash symbol (#) followed by the text, they are used
to describe how the processes are made.
What to document
Before starting a program, enter the following data: Name, A summary of the
purpose, Authors, Version number or if it is a backup.
At the time of writing a class, module, method, or function, document this information:
Name with brief description
Annotations.
Lesson 01
Software development is divided into three stages and programming is only one part
of this process.
Coding, testing and documentation. At this point, creation, testing, and debugging are done.
and document the software following the business rules, previously
determined in the design.
Additionally, there are some methodologies that subdivide the process or change the
order of its stages to adapt to the need for development or the goals that are
establish.
Development areas
Backend. It is responsible for the functional part of the page. Languages are used
PHP, HTML. Ruby, .NET among others.
App programmer. Designs mobile applications. The languages Swift are used.
Java, NET, C#, Visual Basic, among others.
Software programmer. Develops programs for operating systems. They are used
languages like C, C++, C#, Java, Python, PHP, Visual Basic, Java Script, Ruby, among
others.
Video game programmer. Creates entertainment software for computer or
video game consoles. Languages such as C, C++, C#, Python, Java, Ruby, Flash, Lua are used,
among others.