0% found this document useful (0 votes)
5 views55 pages

Programmer Notes (Object-Oriented)

The document provides an introduction to object-oriented programming, detailing the role of programmers in creating software to solve specific problems. It covers essential programming concepts such as algorithms, data types, variables, and decision structures, along with practical examples using pseudocode. The document emphasizes the importance of logical operations and decision-making processes in programming, making it a foundational guide for aspiring programmers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views55 pages

Programmer Notes (Object-Oriented)

The document provides an introduction to object-oriented programming, detailing the role of programmers in creating software to solve specific problems. It covers essential programming concepts such as algorithms, data types, variables, and decision structures, along with practical examples using pseudocode. The document emphasizes the importance of logical operations and decision-making processes in programming, making it a foundational guide for aspiring programmers.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Object-Oriented Programmer

Introduction

Currently, many everyday activities are carried out through


devices that require software to function, each program must solve a
specific problem, from making a phone call to controlling processes
industrial and it is the programmer's job to make it possible.

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:

The logical operation of computers and devices.


Stay updated on technology topics.
Solve problems using logic.
Create new things with other people's ideas.
Finding solutions that facilitate any task, this training is for you.

Level 01

Lesson 01

What is programming and what is it for?

Programming will help you tell a computer or machine what to do,


for this you will need algorithms that solve specific problems step by step.

Algorithm, program, and programming

An algorithm is an ordered list of instructions that must be followed step by step.


to carry out a task, always with the same result. For example, the procedure
to wash your hands, it is always the same.
A program is composed of one or more algorithms dedicated to solving a
specific problem.

They must be written in a predefined language (C, C++, C#, Python, PHP, Java,
Basic), for the interpretation of a computer.

Programming is the process of designing the code that solves a problem or


need, this solution is known as software.

What is programming for?

A program is similar to a production line in that it receives data as inputs and


uses, transforms or stores them through a process to generate a final result.

There are many areas of application for programming, some of the most
common are:

Development of websites or web platforms.


Software for process control
Development of administrative, commercial, and custom software.
Development of mobile applications.
Computer systems.

Since software is closely related to technology, it can be said


that programming is useful for solving any problem to which it can be applied
technology.

Lesson 02

Structure of a program and pseudocode

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.

The structure of a program, regardless of the language in which it is written, is


composed of three essential parts:

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.

Variables and data types

Variables are containers that temporarily store data, in the


memory of the program, to be able to use them later, the type and size of a
variable, will be defined by the data it will store.

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

Assign value to a variable

The assignment of variables is the action of storing the corresponding data to a


declared variable, to store a value in a variable, you must use the following syntax:
Write the identifier of the variable that will be used in this case AGE below,
add a sign '<' and a hyphen, finally enter the data or the expression that is given to you
it will assign ending with a semicolon.

Process My_process
age < - time;
FinProcess

To use the value of a variable in an instruction or operation, it is enough to insert


with its identifier, one can access a variable or assign it a value as many times as needed
necessary in the program, to finish, save your program with the name
examplevariables.psc

Input and output data instructions

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;

Enter the value of the base of the triangle


Read base;
Enter the value of the height of the triangle
Read height;
Area <-(base*height)/2;
The area of the triangle is
FinProcess

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.

Operator OR. Its function is equivalent to having water taps connected in


parallel to the same water intake and with the same outlet, if any or both are
open, the water will flow to the outlet. Similarly, if the value of any data
compared in the OR operation the result of the comparison will be true
true but if all are false the result of the operation 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.

Logical operators are commonly used to compare the result of


relational expressions.

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

Decision structures are part of the foundations of programming and are


applicable is any formal programming language with slight variations in its
syntax.

Use of vectors or matrices

Vectors are structures that can store a defined number of variables.


of a type and size, under the same identifier, for the computer, this means that
It will use a defined number of locations in memory to be able to access them.
variables under the same identifier.

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.

To start, open the previously saved file as “example1.psc”, a


continuation, you will use the variable AGE as a vector, following the steps:
Write the reserved word DIMENSION followed by a space, enter the
identifier of the variable that you will use as a vector, that is, AGE, open a parenthesis,
write the number 3 and close the parenthesis, end with the semicolon;
you will indicate to the program that the variable AGE can store 3 integer values
under the name AGE.

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);

Write 'What is the age of person 1?'


Read age (0);
What is the age of person 2?
Read age (1);
What is the age of person 3?
Read age (2);
The entered ages were:
Write "Person 1:"; age (0);
Person 2:; age (1);
Write "Person 3:"; age (2);
Use of matrices

Matrices are structures of two or more dimensions grouped in a similar way.


to the vectors, that is, a two-dimensional matrix, whose values are 2 and 3, is
equivalent to having two vectors of three elements each under the same
identifier AGE in total adds up to 6 elements, to declare an array:

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);

Write 'What is the age of person 1?'


Read age (0,0);
What is the age of person 2?
Read age (0,1);
What is the age of person 3?
Read age (0,2);
The entered ages were:
Write "Person 1:"; age (0,0);
Person 2:; age (0,1);
Write 'Person 3:'; age (0,2);

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

Repetition structures allow the program to execute the same series of


instructions as many times as necessary for the fulfillment of a condition
logic. There are three loop structures: While, Repeat, and For. Each structure
it has useful characteristics according to the needs of the algorithm.

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.

The procedure is as follows, it checks a logical condition, executes the conditions.


if it meets the condition, return to the review point. The instructions of the
The cycle will repeat as long as the condition is met. To use a WHILE cycle:

Declare an integer variable named ITERACION, it will serve as a counter of the


number of iterations of the cycle, assign the value of zero to the variable ITERATION for
start the counter, write the reserved word WHILE, followed by a space,
write the relational expression whose logical result you will evaluate, in this case, will be
iteration less than three, use a space to separate the reserved word DO, in
the following lines add the instructions that will repeat in the cycle, assign to the
variable ITERATION, the sum of its own value plus one to increment the
counter, finishes by closing the loop with the instruction ENDWHILE,; save this
example like "examplewhile.psc".

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

The entered ages were:


Person 1:, age (0);
Person 2:, age (1);
Write 'Person 3:', age (2);
FinProcess

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

The entered ages were:


Person 1:, age (0);
Person 2:, age (1);
Write 'Person 3:', age (2);
FinProcess

PARA structure.

Unlike the previous structures, the FOR structure increases the


automatic counter, in addition the initial and final value of the counter are defined
within the structure. The FOR structure requires the following syntax:

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;

For iteration<-0 Up to 2 With Step 1 Do


Write 'What is the age of the person', iteration+1, '?' ;
Read age (iteration);

FinPara

Write "The entered ages were: "


Write "Person 1:", age (0);
Write 'Person 2:', age (1);
Write 'Person 3:', age (2);
FinProcess

Repetitions are useful for performing summations and are used constantly.
in operations or procedures with vectors.

Level 02

Lesson 01

Characteristics of the Python language

The Python language is similar to pseudocode and can be used for:

Structured programming. It consists of 3 characteristics:


Sequential, meaning the lines of code are executed in the order in which
that are written.
Selective, that is, makes decisions based on a condition to
choose the path of the program.
Repetitive, that is to say, as long as a condition is met the program
it is iterative.

Event-driven programming. The program waits for an event to occur to


carry out a task.

Object-Oriented Programming. It uses entities called objects and them


assign properties, methods and a unique identity in order that, in its
group, do one or several tasks.

Advantages

It does not compile


It is modular
Achieve short programs
It is used on large platforms
Contains free use libraries
It is adaptable to programs written in other languages

Installation

In some operating systems it comes pre-installed. If not, follow


these steps:
Enter the pagehttps://www.python.org/downloads/windows/
Select version 2.7 and choose the download that is compatible with your OS.
(32 or 64 bits)
Open the .exe file and click on run
Select 'next' in the windows and wait for it to install.

Integrated Development Environment

An Integrated Development Environment, IDE for its acronym in English, is an interface


used to write code in a programming language, it contains: bar of
tools, editor, project bar and console.

Creation of projects and files

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.

Your first program

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.

Xy = (“Primavera”, “Verano”, “Otoño” , “Invierno”)


Print xy[0]

Dictionaries

They are structures that associate a key with a value, consisting of:

A variable to which the dictionary is assigned


Keys are used as indexes to access values, they can be
numbers, strings and tuples
Values can be a number, variables, text strings, lists, and tuples.
Keys that enclose the keys and values.

Dic = {‘Clave1’: “Bipedo”,


‘Clave2’: 6,
‘Clave3’: [“caminar”, “correr”, “saltar”]
}

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.

Dic = {‘Clave1’: “Bipedo”,


‘Clave2’: 6,
‘Clave3’: [“caminar”, “correr”, “saltar”]
}

Dic 2 = dic ["Key3"] [1]


Print dic2
Logical decision instructions

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:

Use an entry called BOOKS to ask the question, use an IF to compare


BOOKS, if it is greater than or equal to 15, print 'You are a good reader', use an ELSE if not.
meets the previous condition, and prints 'You need to read more', test the program with
different data, consider that the language only accepts characters from the English language,
so accents and some signs are not used.

Use of nested logical decisions

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.

It is enough to use indentations to determine which decision will be made first,


an example is to write a program that asks for the commuting time to work, for
create a new file with the name 'Nested Conditionals' and follow these
steps:

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.

input ('Do you work from home?')


If question == True:
You are lucky

If question == False:
You work outside the home

input('How many minutes do you take to work?')


If time == 0:
You work from home
If time <= 20:
It's a little time
Elif time >= 21 and time <= 45:
It is a reasonable time
Else:
Search for other routes

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.

Table of 7 using for


i=1
while i<=10:
table = 7*i
print "7X" + str (i), "=" + str(table)
i=i+1

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.

Table of 7 using for


For j in range(1, 11):
Print "7X" + str(j), "=" + str(j*7)
j=j+1

Another common application of FOR in Python is the reading of elements in lists,


including words.

Table of 7 using for

For j in range(1, 11):


Print "7X" +str(j), "=" +str(j*7)
j=j+1
For words in 'Vladimir':
Print words

Functions

A function is a set of lines of code that can be reusable and serve


to organize a program in the form of short blocks, the structure of a function
it consists of the DEF instruction with its name and the necessary variables in parentheses
for the process, a simple example is to create functions to calculate areas
geometric of the square, triangle or circle, follow these steps:

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():

Side = input ("What is the value of the side?")


X = side**2
The area of the square is

Area of the triangle


Def triangle():

Base = input ("What is the value of the base?")


Height = input ("What is the value of the height?")
Y = base*height/2
Print "\nThe area of the triangle is", and, "square units"
Area of the circle
Define circle():

Radio = input ("What is the value of the radius?")


Z = (F * radio) **2
The area of the circle is, z, square units

True
while i==True:
area = input("Choose the geometric figure to calculate its area \nSquare =
Triangle = 2

if area==1:
square ()

elif area ==2:


atriangulo ()

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:

Use a WHILE and declare a variable as true create an entry for


ask according to an assigned value, which area is going to be calculated, use decisions
logics, to choose according to the value of the input, which function is executed, in
in case no valid option is chosen, print the option to say it, lastly
create an entry to ask if you want to do another calculation, test the program.

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

The object-oriented paradigm is a methodology that allows organizing the


information according to the interaction of entities.

Objects

An object in programming is the computer representation of a physical object or


imaginary can be simple or complex depending on the dimension of its three
properties: State, Behavior, and Identity.

State. It is defined by a set of data called attributes, which store


the characteristics of the object at a given moment.

Behavior. It is defined by its methods, these are functions that allow


your interaction with the program and other objects.

Identity. In programming, the object is defined by the identifier with which


is declared.

Additional properties. There are properties that extend the functions of a


object such as inheritance, abstraction, and encapsulation. These allow the
programmer to create larger and better-structured systems, taking advantage of the
code reuse.

All the mentioned properties are defined through templates called


classes, in other words, objects are instances that possess the characteristics
essentials defined in their class similar to a building based on a plan.

Objects and class declaration

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

Create a new file named "ejemploobjetos.py", to begin declare a


class using the following syntax, write the reserved word CLASS, followed by a
space and the name of the class PERSON and two points, the name of a class must
Write in lowercase letters and start with uppercase; this is done because
convention and best practices. In Python, attributes are declared within a
special method, which is executed automatically when creating an object, to this method is
it is called a constructor, it has a special syntax that Python recognizes as reserved,
is developed as follows:

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:

Following the class declaration, add a variable called 'Juan',


followed by the equal sign and the name of the class person followed by a parenthesis, for
last save and run the program to view the result.

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

Methods are functions declared within a class that serve to


interact with her.

Method Declaration

To start, open the file you saved as "ejemploobjetos.py" and below


of the constructor method, leave a blank line, add a new line to create
a new method called SPEAK with the following syntax:

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

def speak (self, words)


print self.name, ': ', words

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

def speak (self, words)


print self.name, ': ', words

juan = Person()
Juan, to speak ("Hello, I am speaking")

Similarly to Python functions, it allows the use of values.


default in class methods, to implement this use the method
No sé qué decir
default, for the parameter words, now make a call to the method
SPEAK right below the creation of object JUAN, but this time leave the
parameter space, run the program and observe on screen that the first
call to the method, shows the default value, while the second call,
show the phrase you have passed as a parameter; save this file as
examplemethods.py, to consult it later.

class Person:
def __init__(self):
self.edad = 18
Juan
It has been created for

def speak (self, words="I don't know what to say")


print self.name, ': ', words

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

def speak(self, words='I don't know what to say')


print self.name, ': ', words

Person(18, "Juan")
Hello, I am speaking
Person(20, "Luis")
luis.speak("Hello, I am speaking")

Tuples and dictionaries in parameters

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

def speak (self, *words="I don't know what to say")


for phrase in words:
print self.name, ': ', phrase

Person(30, "Juan")
Juan says("Hello, I am speaking", "This is me")
luis=Person(18,"Luis")
Hello, I am speaking, This is me

To create an example of using dictionaries as parameters, do the following


modifications to the code:

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

Inheritance and method overriding

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

Inheritance is the most used mechanism to optimize coding since


allows reusing methods defined in superclasses to define new subclasses,
returning to the example of the PERSON class, we know that a person can
practice sports besides talking, so you will declare a class called
ATHLETE that inherits the SPEAK method from the PERSON class, to
implement inheritance in this example:

Open the file you saved as 'ejemplotuplaparametro.py', now add two


line breaks after the definition of the PERSON class for it to be easy
differentiate the definition of the new class from the previous one, move the cursor to the beginning
from the line to indicate to the program that it is a new class declaration,
declare a new class with the name of ATHLETE, followed by the name of the
class from which it will inherit methods, it declares a method called
PRACTICARDEPORTE, within the definition of the new class, adds a
print instruction, in the definition of the method PRACTICARDEPORTE, with the
variable SELF.NAME and the string ":I am going to practice", modify the declaration of the
object LUIS, to make it an instance of the new class ATHLETE, add a
call to the PRACTICARDEPORTE method of the LUIS object after the call to the
method SPEAK of it; execute the code, observe how the object LUIS, which
now it is an instance of ATHLETE, it continues to behave like an instance of
PERSONA because it has inherited its methods.

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, ':', phrase

Class Athlete (Person):

Def practiceSport (self):


print self.name, ': I am going to practice';

Juan = Person (30, "Juan")


Juan.speak("Hello, I am speaking", "This is me")
Athlete
Luis.speak("Hello, I am speaking", "This is me")
Luis.practiceSport()

Overwriting

It is called method overriding to a new definition created within a


subclass for one or more inherited methods from its superclass, to override the
constructor inherited from the PERSON class, follow these steps:

Enter a new constructor method declaration within the class


ATHLETE, add the parameters AGE, NAME, and SPORT, within the
definition of the constructor, adds the attributes SELF.EDAD, SELF.NOMBRE and
SELF.DEPORTE and assign them the corresponding parameters, add the same
print instruction used in the constructor of the PERSON class, in the
main program adds a print screen, with the phrase 'Luis practices' and
concatenate the DEPORTE attribute of the LUIS object with a period; execute the code. How
you can see the LUIS instance of the ATHLETE class, it now accepts three parameters
because the PERSON constructor is overridden, also the SPEAK method
it is still the same inherited from PERSON; save this example as
"exampleinheritance.py", to use it as a reference in the future.
class Person:

def __init__(self, age, name):


self.age = age
self.name = name
A has been created

def speak (self, *words):


for phrase in words:
print self.name, ':', phrase

class Athlete (Person):

def __init__(self, age, name, sport):


self.age = age
self.name = name
sport
Created for

def practiceSport (self):


print self.name, ': I am going to practice';

Person (30, "Juan")


juan.speak ("Hello, I am speaking", "This is me")
Athlete (18, "Luis", "swimming")
luis.speak("Hello, I am speaking", "This is me")
luis.practiceSport()
Luis practices, luis.sport

Encapsulation and hiding in objects

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.

Within Python, there are no formal access modifiers, therefore, the


the hiding of attributes and methods is achieved by adding two underscores at the beginning of them
identifier, to encapsulate an attribute observe this example:
Open the file 'ejemploherencia.py', locate the definition of the class ATHLETE,
add two underscores before the word SPORT of the attribute SELF.SPORT,
update the name of the attribute SPORT of the object LUIS in the screen print of
the last line, if you run the program at this point, the program will indicate that there is a
error, because in the printing of the last line it is trying to access the value of the
attribute SPORT that is now private.

class Person:

def __init__ (self, age, name):


self.age = age
self.name = name
A has been created

def speak (self,*words):


for phrase in words:
print self.name, ':', phrase

class Athlete (Person):

def __init__ (self, age, name, sport):


self.age = age
self.name = name
self.__sport
A has been created with

def practiceSport(self):
print self.name, ':I am going to practice';

Person (30, "Juan")


Hello, I'm talking. This is me.
luis = Deportista (18, "Luis", "natacion")
luis.speak ("Hello, I am speaking", "This is me")
luis.practiceSport()
Luis practices

To access the value of an encapsulated attribute, use the following function:

Within the definition of ATHLETE add a function called VERMIDEPORTE


in the definition of the function add a RETURN statement with the underscore attribute
SPORT replaces the underscore attribute SPORT of the LUIS object in the last line
for the call to the VERMIDEPORTE method, execute the code, now the main program
you can access the value of the underscore attribute sport, because there is a public method
in the object that locally accesses the attribute and returns its value; keep this example
with the name 'ejemploencapsular.py'.

class Person:

def __init__ (self, age, name):


self.age = age
self.name = name
A has been created for

def speak (self,*words):


for phrase in words:
print self.name, ':', phrase

class Athlete (Person):

def __init__ (self, age, name, sport):


self.age = age
self.name = name
self.__sport
A has been created with

def practiceSport (self):


print self.name, ": I am going to practice";

def seeMySport (self):


return self.__sport;

Person (30, "Juan")


Hello, I am speaking, This is me
luis = Athlete (18, "Luis", "swimming")
luis.talk("Hello, I am talking", "This is me")
luis.practiceSport()
Luis practices

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.

Declaration of an abstract class

To declare an abstract class, it is necessary to include prewritten code, since Python


it does not have that function by default, open the file "ejemploencapsular.py" and continue
these steps to use PERSONA as an abstract class, add on the first line of the
program the instruction FROM space ABC space IMPORT ABCMETA comma
ABSTRACTMETHOD, to include the necessary predefined structure, adds in the
first line of the definition PERSON the instruction underscore, another underscore
METACLASS, underscore and another underscore, equal sign ABCMETA, to indicate that the
class PERSON is abstract.

Include the instruction ATABSTRACTMETHOD just before the definition of the


HABLAR method of PERSON to indicate to the program that it is an abstract method,
enter the reserved word PASS at the end of the HABLAR method declaration, to
indicate the end of the method, remove the object JUAN and the call to its method HABLAR in it
main program, if you run the code at this point, Python will indicate that it cannot
create an instance of ATHLETE because the abstract method SPEAK is not
defined.

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.

from abc import ABCMeta, abstractmethod


class Person:
ABCMeta

class Athlete (Person):

def __init__ (self, age, name):


self.age = age
self.name = name
It has been created for
@abstractmethod
def speak (self): pass

class Athlete (Person):

def __init__ (self, age, name, sport):


self.age = age
self.name = name
self.__sport
A has been created with

def practiceSport (self):


print self.name, ':I am going to practice';

def seeMySport (self):


return self.__sport;
def speak (self,*words):
for phrase in words:
print self.name, ':', phrase

Athlete (18, "Luis", "swimming")


Hello, I am talking, This is me
luis.practiceSport()
Luis practices

A class derived from an abstract class is called an implementation, in this


example ATHLETE is an implementation of PERSON, if an abstract class has
more than one method declared as abstract its implementations must have one
definition for each method.

Lesson 05

File types

Python natively supports some file formats useful when


generate reports, create records, export or import information, among others
applications.
Library
File type Extension Characteristics of the files
of Python
It does not have a standard.
Its structure depends on the use given to it.
It is commonly used for importation and
CSV (values
.csv export of spreadsheets and databases Csv
separated by commas
data.
Use commas and line breaks to separate the
data.
It is used in Python to write programs
that the end user can customize.
Provide a structure similar to the files
Files of
.cfg Windows INI. ConfigParser
configuration
The data are section name between
brackets as well as name pairs y
values separated by (:).
It is a list of URL segments.
Request search engine robots to
some sections are omitted.
robots.txt file .txt It begins by indicating that robots are allowed Robotparser
make searches.
Use the numeral (#) to mark lines like
comments.
Allows connection to remote systems of
easy way.
Files of
.netrc It contains the user and password data Netrc
FTP configuration
for access to remote systems.
Use UNIX console instructions.
It has a standard for packaging of
data.
Protocol of
.xdr It is used to transfer data between different Xdrlib
data presentation
architectures and operating systems.
Works at the byte sorting level.
Store application information y
List of properties .plist user settings. plist
Everything is stored in serialized objects.

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.

Basic operations with files

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:

"r" for reading. It needs the previously created file.


"w" or writing. If the file does not exist, it creates it.

An application exercise is to create a function to write three data points, to do so,


follow these steps:

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.

def write(dataa, datab, datac):


Test=open('c:Users/Beto/data.py','w')
Test.write(data)
Test.write(datob)
Test.write(data)
/nWriting/n

Test.close
Writing('Hello',
World
‘Nice’

To call the data from the file:

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

Def write(dataa, datob, datoc):


Test=open('c:Users/Beto/data.py','w)
Test.write(datao)
Test.write(data)
Test.write(datoc)
/nWriting/n

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:

Count("x",start,end) Counts the number of times a character or a string is repeated


(x) in the range from start to end.

lower() changes all characters in the string to lowercase.

Upper() changes all characters in the string to uppercase.

Replace("x","y","number") Replaces the values of "x" with "y" in the string of


according to the number of times specified.

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

Lists are also objects, and their methods are:

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.

Extend(x) adds a new list, tuple, or string to another list.

Pop(index) Removes the value from the list according to the index you choose.

Remove(x) Eliminates the first value "x" from the list.

Reverse() reverses the order of the values in the list.

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

Use of Tkinter for graphical interfaces

In programming, the creation of a graphical user interface or GUI (Graphical


User Interface), which is a set of images that simulate physical elements for
facilitate the interaction of the user with the program.

Tkinter is a library of pre-written classes that facilitate the creation of interfaces.


graphs, to be able to use the functionality of Tkinter, it is necessary to add a call
at the beginning of the code in the following way:

Create a new file named 'ejemplotk1.py', add as the first instruction


FROM TKINTER import *; this instruction will tell you
the program that the first thing it must do is to load all the definitions of the
Tkinter library.

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.

From Tkinter import*


Window = Tk()
Window.mainloop()

Add an element to 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:

Label (contenedor, text = “opción”, fg = “color”, bg = “color”)

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.

From Tkinter import *

Interface class:

Def __init__(self, container):


Label (container, text = "Label 1", fg = "black", bg = "white")
Self.e1.pack ()

Elements of the Form

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.

Button. Add a button with a title inside, class Button(), parameters


specific text: the button title

Box. Displays a check box with description, class Checkbutton(),


specific parameters text: it is the label that accompanies the box

Input. It is a field that allows entering characters, class Entry(),


specific parameters textvariable: if a variable of type StringVar is passed, it
Can you read the content of this element

Radio. Add a selectable option of type radio, class Radiobutton().


specific parameters text: label displayed next to the button

List. Add a list of selectable elements, Listbox(), parameters


specifics selectmode: selection type (BROWSE, SINGLE, MULTIPLE and
EXTENDED

Label. Displays fixed or descriptive text and does not allow user interaction.
with it, class Label(), specific parameters text: static text displayed

Marco. Add a subcontainer within an existing container, class


Frame(), specific parameters, this element serves to subdivide a
container, so the most important parameter is the container itself

General parameters

The following parameters apply to all elements:

Fg: Letter color in English


Bg: Background color in English
Width: Width of the element in characters
Cursor: You can specify the cursor design when hovering over
this element

The syntax to create any of the elements is as follows:

elementId = Class(Container, parameter="stringValue", parameter=numericValue,


parameter=variable, …)

Organization of elements
To arrange the elements within a window, the Tkinter library has
three content administrators:

Pack. He adds them one after another.


Grid. It arranges them in rows and columns.
Place. It positions them in specific coordinates.

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".

From Tkinter import *

Class Interface:

Def __init__(self, container):


Label(container, text="Label 1", fg="black", bg="white")
Label(container, text="Label 2", fg="black", bg="gray")
Self.e3 = Label(container, text="Label 3", fg="black", bg="green")

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

From Tkinter import *

Class Interface:

Def __init__(self, container):


Label(container,text="Label 1", fg="black", bg="white")
Label(container, text="Label 2", fg="black", bg="gray")
Self.e3 = Label(container, text="Label 3", fg="black", bg="green")
Label(container, text="Label 4", fg="black", bg="blue")
Self.e5 = Label(container, text="Label 5", fg="black", bg="yellow")
Self.e6 = Label(container, text="Label 6", fg="black", bg="red")

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

The PLACE manager is used to position elements in specific locations of


the window, to use PLACE follow these steps:

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".

From Tkinter import *

Class Interface:

Def __init__(self, container):


Self.e1 = Label(container, text="Label 1", fg="black", bg="White")
Self.e1.place(x=20, y=30, width=120, height=25)

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.

Implementation of events (Video saved)

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.

If an event is detected by the system, but there is no defined reaction to it


program, will go unnoticed by the user, to create an example of an interface with
events, open the file "ejemplotk3.py" and make the following modifications:

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:

Add the parameter COMMAND=SELF.HACERCONVERSION, in the instance


SELF.E4. add the parameter TEXTVARIABLE=SELF.TEXTOE3 in the instance of
SELF.E6, with this you will be able to dynamically modify the text of the label. Create a
new method called HACERCONVERSION, create a variable called CEL and assign it the
FLOAT function using SELF.E5.GET as a parameter, with this you will obtain the value of the
text field and you will convert it to decimal number before saving it in the variable. Create
another variable called FAR and assign it the operation CEL by 1.8 in parentheses and add
plus 32, finally enter the instruction SELF.TEXT.E3.SET(FAR) to use the
result as text from the label SELF.E6; save the code as 'ejemplotk5.py' and
execute it.

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

Sometimes you may need to extract information from a database or


create it from scratch, for this Python has the functionalities of: Create tables, Insert
records and Consult records.

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:

ID, this will be the number to identify the records


NAME will keep the title of the novel
AUTHOR, will keep the writer
YEAR, will store the year in which the novel was published

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

New records can be inserted into a table to populate the database, to


do it create a new file and follow these steps:

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

Name1=raw_input("Write the title of the novel")


Author1=raw_input("Write the author of the novel")
Year1=str(input("Enter the year of the novel"))

Consulta=db1.cursor()

strConsulta = "insert into table(name, author, year) values


(' + name1 + ', ' + author1 + ', ' + year1 + ')
Print(strConsulta)

Consulta.execute(strConsulta)
Consulta.close()
Db1.commit()
Db1.close()

Insert()

Record inquiry

Queries aim to retrieve data from the tables, to do so follow


these steps:

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")

Name1=raw_input("Write the title of the novel")


Author1=raw_input("Write the author of the novel")
Enter the year of the novel

Consulta=db1.cursor()

strConsulta = "insert into table(name, author, year) values


(“’+name1+’”,”’+author1+’”,”’+year1+’”)
Print(strConsulta)

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

Name1=raw_input("Write the title of the novel")


Author1=raw_input("Write the author of the novel")
Year1=str(input("Enter the year of the novel"))

Query=db1.cursor()

strConsulta = "insert into table(name, author, year) values


('
Print(strConsulta)

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:

Operations that cannot be performed, such as dividing a number by zero.


Mixing types of variables, for example, combining a number with a string of
text.
Assign values to static objects. Like tuples.
Undefined variables, that is, when initial conditions are needed, in
in this case it is necessary to declare the value of I equal to zero.

Logical errors. They generate unwanted results because the programmer, is


he made a mistake in the logic of the process, unlike execution errors, these do not
they show in the console, they can only be solved by code debugging.

Some examples are:

Using relational operators incorrectly, in this case the instruction


WHILE, it will not be executed, since the condition is that I must be equal to or greater than
a 10 has been declared with an initial value of zero.

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:

General, it is unique and catches all the mistakes.


In particular, it catches a type of error, for example, division by zero or a value
mistaken.

Several exceptions can be created and priority is established through the order in which they
that are written.

Exception Detection Process

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

Manual code verification is used to troubleshoot failures in programs.


due to errors.

Table verification. It is used to correct short and simple programs,


to carry it out follow these steps:

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.

Flowchart verification. It is useful for solving errors in programs


longer and more complex, follow these steps:

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

Debugging code is the verification of the program's logic through its


controlled execution, to carry it out, breakpoints are used which are pauses
intended in the lines of code in order to review processes or values, they are created
left-clicking next to the line of code that you want to verify, to make the
debugging follows these steps:

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

Refactoring of the code

Refactoring consists of improving the structure of a program without affecting its


functionality, aims to maintain the program to make it clearer,
facilitate code addition and eliminate redundancies, reduce processing time and
memory usage.

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:

Select a code fragment, it can be a block or an element, click on


REFactor and then choose the type, in case a view window appears
previously, click on accept to confirm the changes, make one change at a time and
make sure to understand all its implications, run tests on the program to verify
its operation, in case some of the functionalities of the
program undoes the changes, if it still does not solve, use the original program, for
last documents in a list the changes you made, this is useful when you give
maintenance of a program for several days or you collaborate in a team.

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:

Docstrings. They are a string of characters in quotes at the beginning of a


module, class, method or function are used to describe what the code does.

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.

Documentation is a habit you should foster in your work routine to


remember how you arrived at each solution.
Level 04

Lesson 01

General process of software development

Software development is divided into three stages and programming is only one part
of this process.

Planning. This stage includes the gathering of requirements,


analysis and design of the system in flow diagrams and database model.

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.

Implementation and maintenance. As a final stage, the software is released,


tested and guaranteed for use. Additionally, errors are corrected
through patches and updates.

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

As a programmer, you can apply your knowledge to different languages that


there are to specialize in a field of your interest, for example:

Web programmer. Creates web pages based on client requirements. It


divide into two:

Backend. It is responsible for the functional part of the page. Languages are used
PHP, HTML. Ruby, .NET among others.

Frontend. It is the graphic design of the page.

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.

You might also like