Category Archives: Programming language

Programming language is a formal language designed to perform processes that can be carried out by machines

Functions in Python

Functions in Python

To define functions in Python we have the instruction def

After this reserved word goes the function name along with a list of arguments delimited by parentheses and separated by commas, ending with the symbol :

Defining a function does not execute the body of the function

It will only be executed when the function is called

Its execution binds the function name with the current local namespace to an objecto function (a wrapper around the executable code for the function)

This object function contains a reference to the global local namespace as the global namespace to be used when the function is called

Optionally you can add an expression that will be returned by the function

The expression can be a valid Python type preceded by the statement return

The DOCSTRING is a descriptive text of the function enclosed in three double quotes of opening and closing, before the first statement

It's optional, so if we don't want to add a description, we can omit it

But it is recommended to use it so that when we review after a while our code, we remember what our function did

Arguments

The argument step is optional and in some cases there may be functions that lack them

Type of arguments

Supports types str, int, float, complex,bool, list, tuple, dic and class

Arguments with value by position

When we send arguments to a function, they are received in order in the defined parameters

Value arguments by name

It is possible to evade the order of the parameters if we indicate during the call the value that each parameter has from its name

No arguments

When calling a function which has a few parameters defined, if you do not pass the arguments correctly it will cause an exception TypeError

Default value arguments

Sometimes we need an argument to have a value, to avoid an error (which would cause the exception to be thrown TypeError), even if the user of the function does not enter it

Note that default arguments become optional and that all arguments to the left of the first default value are required

The example used the null value (None) to express that no arguments had been passed

But we could use any type we need as the default

Indeterminate arguments

Sometimes we won't know in advance how many elements we need to send to a function

For these cases we can use the indeterminate parameters by position or by name

Arguments by position

As an argument we will use a tuple type preceding it with the symbol *

In this way all the arguments will be received by position, being able to navigate them comfortably with a for

Arguments by name

As an argument we will use a type to dictate it before the symbols **

In this way all the arguments will be received by the name of the dictionary key, being able to navigate them comfortably with a for

Arguments by position and name

Sometimes you may need to use both types of parameters simultaneously in a function, so you must create both dynamic collections

First the indeterminate arguments by value and then by name

All examples have used the names args and kwargs but they're not mandatory

Many frameworks and libraries use them so it's a good practice to call them that, by convention

The pass statement

It's a null operation, when we execute it, nothing seems to happen

It is useful as a container when a statement is required syntactically, but you don't need to execute code

The return statement

The statement return it is the one that allows you to return the result of a function

Supports types str, int, float, complex,bool, list, tuple, dic and class

The statement return optional, but if omitted, by default it will return the null value (None)

Multiple return

An interesting feature of the functions in Python, is the possibility to return multiple values separated by commas

Functions are predefined by the language

Language defined functions are sorted by modules

A module is a set of classes and functions stored in a file that can be used later

We can create our own modules and import them into the new programs we make

However, it is advisable to reuse existing modules

To import a module we will use the statement import

In this way we will be driving a namespace, similar to how C++ does (using namespaces) or Java

It has the following syntax

To call a specific function of the module we will use number.funcion() or alias.funcion in case we've given the module an alias

If you don't want to use all the functions of the module but if you do, we'll use the statement from

It has the following syntax

Sys module

This module is responsible for providing variables and functionalities related to the interpreter

The variables of the sys module are:

  • sys.executable

    Returns the absolute directory of the Python interpreter executable binary file

  • sys.platform

    Returns the platform on which the interpreter is running

  • sys.version

    Return the Python version number with additional information

The most prominent methods of the sys module are as follows:

  • sys.exit()

    Force the interpreter out

  • sys.getdefaultencoding()

    Returns the default character encoding

  • sys.getfilesystemencoding()

    Returns the character encoding used to convert unicode file names to system file names

  • sys.getsizeof()

    Returns the size of the passed object as a parameter

os module

This module allows us to access OS dependent features

Above all, those that give us information about the environment of the same and allow us to manipulate the directory structure

Some of the most commonly used methods are:

  • os.getcwd()

    It tells us what the current directory is

  • os.chdir(route)

    Change working directory to last path as an argument

  • os.chroot()

    Switch to the root directory

  • os.mkdir(directory)

    Creates the passed directory as an argument

  • os.rmdir(directory)

    Deletes the passed directory as an argument

  • os.remove(file)

    Delete the file passed as an argument

  • os.rename(current, new)

    Renames the current file by the name of the new file, passed as arguments

math module

This module provides us with mathematical functions and constants

We can find all the functions and attributes in your documentation

Some of the most commonly used variables are:

  • math.pi

    Represents the value of the variable \pi (Pi number)

  • math.e

    Represents the value of variable e (Euler number or Napier constant)

  • math.tau

    Represents the value of the variable \tau = 2\cdot\pi (constant Tau, proposed by Bob Palais, Peter Harremoes, Hermann Laurent, Fred Hoyle, Michael Hartl, Nicolas Atanes, among others)

Some of the most commonly used methods are:

  • math.ceil(x)

    Returns the integer less than or equal to x

  • math.floor(x)

    Returns the largest integer less than or equal to x

  • math.exp(x)

    Returns the number e raised to the power x

  • math.log2(x)

    Returns the base 2 logarithm of x

  • math.sin(x)

    Returns the sine of x radians

  • math.cos(x)

    Returns the cosine of x radians

  • math.tan(x)

    Returns the tangent of x radians

  • math.degrees(x)

    Converts the x-angle of radians to degrees

Random module

The random module is used for everything related to random numbers

Some of the most commonly used methods are:

  • shuffle(col)

    Randomly reorders items in a collection

  • sample(col, k)

    Take n items without a collection replacement

  • random()

    Generates a random number in the range [0, 1)

  • uniform(a, b)

    Generates a random number in the range [a, b]

  • randint(a, b)

    Generates an integer random number in the range [a, b]

  • gauss(mean, sigma)

    Generates a random number following a gaussian distribution with given mean and sigma

NumPy module

Numpy provides us with a lot of mathematical functions and the type of variable NumPy array

Usually the NumPy package is usually imported with the alias np

This module allows us to work with mathematical structures in a very comfortable way (product of matrices, random numbers, operations on matrices...)

It is a module that is not installed by default

To do this open a terminal and run:

We can find all the functions and attributes in your documentation

Some of the most commonly used methods are:

  • random.rand()

    It returns random values to us with the desired shape

  • empty()

    Creates an empty array with the right shape

  • zeros()

    Creates an array of zeros with the right shape

  • dot()

    Calculates the matrix product between two arrays

  • sum()

    Calculates the sum of the elements of an array

Pandas module

The package pandas is widely used in the Data Scientists

It's one of the packages we should focus on to learn about data analysis

Through pandas we can get acquainted with our data set by cleaning it, transforming and analyzing it

For example, with pandas we can read a CSV file from our computer, pass it to a DataFrame (a table, in essence) and do things like:

  • Calculate statistics and answer questions about the data such as getting the maximum, minimum and average of each column, knowing how correlated columns A and B are, or knowing the statistical distribution of column C
  • Clean up data doing things like removing missing values or filtering rows and columns according to some criteria
  • Visualize the data with the help of matplotlib
  • Save the data already cleaned back in a CSV or database
  • Pandas is based on NumPy, so we should have that module pre-installed

    Jupyter Notebooks it's an app that complements very well with Pandas, since we can run the code by cells instead of completely, which is useful if we work with large datasets

    The primary components of Pandas are series and DataFrame, the first type being a column and the second being a table

    Usually the pandas package is usually imported with the alias np

    It is a module that is not installed by default

    To do this open a terminal and run:

    We can find all the functions and attributes in your documentation

    Now let's create a simple example to show the use of pandas using a series that will contain the members of the Spanish football team that won the 2010 World Cup

    To create the series we use the method pd.Series you will receive a list of player names and a list with the number of players

    Then we'll show it by screen

    Now we're not going to explicitly point indexes on it, then it will generate the indexes automatically starting from the zero value

    Now let's introduce a dictionary into the series instead of a list and add one more player

    Now let's create a simple example to show the use of pandas using a DataFrame that will contain the members of the Spanish football team that won the 2010 World Cup

    To create the DataFrame we use the method pd.DataFrame you will receive a dictionary with player data, a list with the column name and a list with the number of players

    We'll add one more player using the method loc dataFrame object

    Then we'll show it by screen

    Display functions

    print

    The function print serves to send the output of your arguments to the browser in a format

    Operador %

    The operator % can also be used for string format

    Interprets the left argument much like a style format string of the function printf C++, which applies to the right argument

    In Python, there is no function printf but it has been endowed with its functionality print

    For this purpose, the operator % is overloaded for strings to show the format of the string

    It is often called string module operator (or, sometimes, even, module)

    It has the format:

    To format a text you have to enter the following formatting characters preceded by the symbol %:

    Format characters for text
    Character Description
    c

    The argument is treated as a string value and collects a single character

    d

    The argument is treated as a value of type int and presented as an integer

    e

    The argument is treated with scientific notation (for example 1.2e+2)

    E

    As %e but uses the uppercase letter (for example 1.2E+2)

    f

    The argument is treated as a float value and presented as a floating point number (considering the locale)

    F

    The argument is treated as a float value and presented as a floating point number (without considering the locale)

    g

    Like %e and %f

    G

    Like %E and %f

    o

    The argument is treated as an integer value and presented as an octal number

    s

    The argument is treated as a string value and collects a string

    u

    The argument is treated as a value of type int and presented as an unsigned decimal number

    x

    The argument is treated as an integer value and presented as a hexadecimal number

    X

    The argument is treated as an integer value and presented as a hexadecimal number in uppercase

    Format method

    The method format added to string types in Python 2.6

    Allows the use of characters {} to mark where a variable will be replaced and uses detailed formatting policies used to format

    This method allows us to concatenate elements within an output through the positional format

    Brackets and characters within them (called format fields) are replaced with objects passed to the format method

    A number can be used in parentheses to refer to the position of the argument passed to the format method

    Keep in mind that the first argument starts at zero

    A key identifier can also be used when the argument is passed by name

    This option will be useful when working with dictionaries or when we want to reduce the code something

    Optionally you can put the symbol : after the number or name, and specify the type of the object:

    Format characters for text
    Character Description
    s

    The argument is treated as a string value and collects a string

    d

    The argument is treated as a value of type int and presented as a decimal number (signed)

    f

    The argument is treated as a float value and presented as a floating point number (considering the locale)

    Higher order functions

    In mathematics and computer science, higher order functions are functions that meet at least one of the following conditions:

    • Take one or more functions as input
    • Return a function as output

    Lambda functions

    Lambda functions are anonymous functions, that is, unnamed functions

    They are only used where they were created (although they can be named and used later)

    They are usually used in conjunction with map, filter and reduced functions

    They are usually used to create functions that are passed as arguments to other functions

    In Python the syntax of a lamdba function is:

    Where the expression can be any operation we would do when making an assignment

    map function

    It allows us to apply a function on each of the elements of an iterable

    It returns a map object, which we can easily transform into a list

    filter function

    Allows us to filter items in a collection (for example, a list)

    It is a widely used function in the treatment of collections

    reduce function

    Take a function and a collection by reducing it to a single value

    It would be equivalent to an aggregation function

    It belongs to the module functools, so it must be imported before it can use reduce

    The function we pass must take at least two parameters and an optional one

    The first is the aggregate parameter that accumulates in each iteration over the items in the collection

    The second element corresponds to the step of the iteration

    The third is in case an initial value is needed

Python exceptions

Python exceptions

If an operation cannot be completed due to an error, the program must:

  • return to a stable state and allow other operations

  • try to save your work and finish

This task is difficult because usually the code that detects the error is not the one that can perform such tasks this is why you should inform that you can handle it

The most common solution are the error codes

Python offers another way to deal with errors under exceptional conditions: the exceptions

An exceptional condition is one that prevents the continuation of an operation

It's not known how to handle it, but you can't continue

In Python, an exception is thrown for someone who knows how to handle it to handle it in a higher context

In the example the open function checks whether the file readme.txt existed in the system and if it doesn't exist the exception is thrown FileNotFoundError who is untreated at the moment

When the interpreter detects the throw of the exception, the current method ends and launches an object that provides information about the error that occurred

Normally each type of error will be handled individually

Handling of the exceptions

Once detected the error makes it necessary to indicate who is in charge of treating it

An exception handler has the following format:

try block

The block try delimits the group of operations that may produce exceptions

except block

The block except it is the place to which control is passed if any of the operations throws an exception

The example used a block try with his block except to handle the errors in the previous example

If any of the operations in the block throw an exception, the block is interrupted try and runs the except

At the end of this, it is normally continued

If no exception is thrown, the block except is ignored

Multiple exceptions

There is also the possibility to use an exception name to handle specific errors

Some of which are already recognized by the system, such as the exception FileNotFoundError, which is launched when a file does not exist in the system

The example used a block try with several blocks except to handle several exceptions

A block try can have several except associated

We've added the sentence as to the block except after naming it to make it the object of exception we've called and

As you can see, after turning it into an object, we can use it as if it were a class

When an exception does not correspond to any catch spreads backwards in the sequence of invocations until a catch adequate

In the example is managed the exceptions of the methods f1 and f2 and if you don't find any, it continues the execution of the code in the normal way outside of the block try

The sentence has been used raise followed by the name of the type of exception to propagate it and treat it elsewhere

In this case we have treated it within the f1 function itself in its exception blocks

Although spreading it could have been treated outside of it elsewhere in the script

A block has also been used else that allows the code to continue execution in case there are no exceptions before continuing outside the block try

else block

Allows code execution to continue in case there are no exceptions before continuing outside the block try

The block else can be used to exit a loop if the statement is added at the end of a loop break

It is optional and if it is not used, it will continue the execution of the code in the block finally and finally outside the block try

Finally block

There may be occasions in which you want to perform some operation if exceptions occur as if not

Such operations can be placed within a block finally

If there is no exception, the block will be executed try, then the block else and finally the finally

Like the block else, is optional and if it is not used, it will continue to execute the code outside the block try

Rules of use

  1. Standard

    • If an exception can be handle should not be spread

    • It is more convenient to use methods that do not produce errors

  2. Standard

    • Do not use exceptions to avoid a query

      • Not to abuse them

  3. Standard

    • To separate the error handling logic

      All together

      Separate

  4. Standard

    • Do not ignore an exception already that we leave the code with errors without control

Web Page

Web page

A website, or electronic page, digital page, or cyberpage is a document or electronic information capable of containing text, sound, video, digital images, programs, access to other websites through hypertext links, images, etc

Broadcast in HTML or XHTML formats, it also includes other resources called cascading style sheets (CSS) and scripts

A web page can be stored on a local computer or on a remote web server

A web server can restrict access only to private networks, such as a corporate intranet, or it can publish pages to the World Wide Web (WWW)

Access to web pages is done by a transfer from servers, using hypertext transfer protocol (HTTP) or Secure Hypertext Transfer Protocol (HTTPS), being accessible from a browser

Html

Html

The HTML (hypertext markup language) describes the content of a web page, including text, images, videos, etc

The specifications on the functioning of the web makes the W3C (World Wide Web Consortium). On its website we can find all the documentation about HTML and other network standards

For the editing of web pages we can use any text editor

In windows Notepad or Wordpad, in linux vi, joe, mcedit, etc

In them we will take advantage of the capabilities of each one to copy and paste. There are many web editors that make it easy for us to insert HTML code

Some freeware, other shareware and other commercial ones like Adobe Dreamweaver with which you get more professional pages because they have predefined templates that speed up our work

For advanced developers we have Sublime Text, although it may be unfriendly to other developers

Among the friendliest we have Brackets, which allows you to view the HTML code automatically

And Atom, as another alternative, which is now becoming fashionable

We have to take into account the type of encoding that we use with this language, because if when writing our website we use an encoding other than that of the web browser, we can get a page with strange or illegible characters

The most commonly used option is UTF-8 encoding, which is the standard for the Internet and Linux systems

Windows and MacOS systems use other types of encoding so we will have to match the encoding in the document header, with the one that will be displayed in the web browser

Standards

HTML 1.0

Tim Berners-Lee in 1991 describes 18 elements that include the initial and relatively simple HTML design. Thirteen of these elements still exist in HTML 4.4

Berners-Lee considered HTML an extension of SGML, but was not formally recognized as such until publication in mid-1993, by the IETF (Internet Engineering Task Force), of a first proposition for an HTML specification: Berners-Lee and Dan Connolly's Hypertext Markup Language draft, which included an SGML Document Type Definition to define grammar

The draft expired at six months, but was notable for its recognition of the Mosaic browser's own label used to insert images without line change, reflecting IETF's philosophy of successfully basing standards on prototypes. Similarly, Dave Raggett HTML+'s (Hypertext Markup Format) competing draft from late 1993 suggested standardizing features already implemented, such as tables

HTML 2.0

The official version for HTML was until a few years ago HTML 2.0, called HTML+, began to develop in late 1993. It was originally designed to be a superset of HTML that would gradually evolve from the previous HTML format

The first formal HTML+ specification was therefore given the version number 2.0 to distinguish it from previous unofficial proposals. HTML+ work continued, but never became a standard, despite being the basis formally more similar to the common aspect of current specifications

It fulfilled its function perfectly, but many HTML users wanted to have greater control over their documents, both in the formatting of the text and in the appearance of the page

HTML 3.0

Meanwhile, Netscape, which was at the time the undisputed leader of browsers, introduced with each new version tags and attributes not covered by the official standard, creating discontent among some developers

Due to their wide dissemination and acceptance, other browsers tried to copy these innovations, but because Netscape did not fully specify its new tags, the results were no different from those desired. Which caused a lot of confusion and numerous problems, when developers used these elements and found that it didn't work the way they wanted in other browsers

The draft HTML 3.0 standard was proposed by the newly formed W3C in March 1995. Many new capabilities were introduced with him; for example, facilities for creating tables, making text flow around figures, and displaying complex mathematical elements. Although it was designed to support HTML 2.0, it was too complex to be implemented with the technology of the time, and when the draft standard expired in September 1995, it was abandoned due to the lack of support from web browser manufacturers

HTML 3.2

HTML 3.1 never officially came to be proposed, and the next standard was HTML 3.2, which abandoned most of the new features of HTML 3.0 and, in return, adopted many elements initially developed by Netscape and Mosaic web browsers. The possibility of working with mathematical formulas that had been proposed in HTML 3.0 became integrated into a different standard called MathML

The need for a new standard that was accepted by all was becoming increasingly evident. Another committee was formed, the W3C, supported by major software vendors (including IBM, Microsoft, Novell, Netscape, Sun, etc.). The new standard was developed throughout 1996 by the W3C under the nickname Wilbur, and finally, in January 1997 it was approved as HTML 3.2

HTML 3.2 was fully compatible with the above standard, but incorporates many of the innovations of commercial browsers (Netscape and Internet Explorer mainly), such as tables, applets, text bordering images, among others, but not all, such as frames

HTML 4.0

In July 1997, the first public draft of the official HTML 4.0 standard (which has the code name Cougar) was introduced. It incorporates specifications on tables, frames, scripts, style sheets, accessibility by different means, and internationalization (including the use of Unicode, instead of Latin-1)

In 1997, HTML 4.0 (which has the key name Cougar) was published as a W3C recommendation. HTML 4.0 adopted many specific elements initially developed for a particular web browser, but at the same time began cleaning up the HTML by pointing out some of them as deprecated (disapproved)

HTML 4.0 implements features such as XForms 1.0 that do not need to implement navigation engines that were incompatible with some HTML web pages. It incorporates specifications on tables, frames, scripts, style sheets, accessibility by different means, and internationalization (including the use of Unicode, instead of Latin-1)

HTML 5.0

HTML5 specifies two syntax variants for HTML: a "classic", HTML (text/html), known as HTML5, and an XHTML variant known as XHTML5 syntax that should be served with XML syntax (application/xhtml+xml). This is the first time HTML and XHTML have been developed in parallel

In 2004 the W3C reopened the debate on the evolution of HTML, and the basis for the HTML5 version was released. However, this work was rejected by W3C members and preference would be given to the development of XML

Apple, Mozilla and Opera announced their interest in continuing to work on the project under the name WHATWG, which is based on compatibility with previous technologies

In 2006, W3C became interested in html5 development, and in 2007 it joined the WHATWG working group to unify the project

The final version of the fifth revision of the standard was published in October 2014

Because it is not recognized in old browser versions for its new tags, it is recommended that the common user update their browser to the newer version, in order to enjoy the full potential provided by HTML5

Format of an Html page

Format of an HTML page

Its essential principle is the use of labels. The labels are reserved words of the language, enclosed in < >

Types of labels

There are three types of tags:

  • Paired
    when a start and end tag appears, the blocks contained between start and close are elements, which in turn may contain other elements

  • No match
    when the label represents the insertion of an element, these tags end with a forward slash

  • With final optional
    are the labels paired in the which it is not mandatory to use the end tag

The labels can include attributes modifying its behavior, specifying some unique characteristic of the element or including additional information

The attributes are specified as pairs attribute='value', separated by spaces within the home label

Values are not required to be enclosed in quotation marks, but it is recommended

Single or double quotation marks can be used interchangeably, as long as they match their opening and closing

The example has used the id attribute, which is generic for any tag and which will be useful to us when using CSS and Javascript, because it allows us to uniquely distinguish the element to which that particular tag belongs

There are more generic attributes, such as class, title or style, all very useful when we want to format or improve accessibility to our elements

When we introduce a label that does not exist, it will be ignored, we must pay attention to this issue because it makes it difficult to detect errors

The labels can be typed in uppercase or in lowercase

Line breaks and extra white space are not considered. The latter allows you to indent your code to make it more readable

Comments within the HTML

Sometimes it is very useful to write comments in the HTML document about the code we write, they can serve to remind us later what was done, and that we do not want it to be seen on screen

This is achieved by enclosing such comments between these two symbols:

Comments can be used anywhere in the HTML document, but will not be displayed

Special characters

There are certain characters that a browser is not able to recognize in spite of using the correct encoding

Let's imagine that we want to write the text x > y within our HTML, however, the character > will not be recognized by the browser or will show us one wrong

This happens with a set of characters that are special and that the browser will recognize by using the particular label of this character with the following format &label;

In the example above, the label for the > is gt, starting with & and ending with ;

On the following website we can consult the complete list of the 256 universal characters HTML

Header of an Html page

Header of an Html page

The header is delimited by the element head (which in turn is contained within the element html), which describes document information (title, configuration, scripts, and styles)

Document information is placed, which will not be displayed on the main screen and can be:

  • Title of the document
  • Metadata
  • Links to other files
  • Scripts
  • Styles

Title of the document

The title should be brief and descriptive of your content, as it will be what others see when they add our page to their bookmark

This tag is mandatory and must appear only once in our document

The browser will be displayed in the title bar of your window

Metadata

The metadata elements are entered with the label goal, the type of method is defined by its attributes, some of the most common are:

  • charset

    indicates the encoding in which the document is written

    It is important that you enter the correct encoding for the browser to display the document correctly

    In this example we have used the coding UTF-8 that is the standard for internet

  • author

    indicates who is the author of the page, specified with the attributes name and content

  • keywords and description

    Both make reference to the content of the page and are often used by search engines to index the web pages

    Thanks to these fields, which are specified with the attributes name and content, search engines know that search terms best describe our website to show it to other users

Links to other files

In the header we can indicate links to other files that we want to upload along with our website, for this we use the label link

They will usually be CSS style sheets, JavaScript files, additional libraries in other languages or our own files

The example included the CSS style sheet of the wordpress twentyfourteen theme, for this the attributes have been used:

  • rel

    to indicate what type of document is, in this case, a style sheet

  • id

    to assign a unique identifier

  • type

    to indicate the type of text that the browser will receive, in this case a CSS style sheet

  • href

    is the relative path to the document or its absolute path

The example also included a specification for defining multiple languages, which the browser will use to index using the language in which the page is written correctly, for this the attributes have been used:

  • rel

    to indicate what type of document is, in this case, a multisite reference in multiple languages

  • hreflang

    to assign you a language, in this case es for Spanish, en for English and x-default for the default language for the start page

  • href

    is the relative path of the document or its absolute path, in this case the lang parameter is added, starting with ? to indicate the acronym for the language

Scripts

The item script allows you to include executable code in our web page

By default, the browser will take JavaScript as the default language to run, if we don't specify another

The example has taken into account the case that the browser cannot use scripts, either because it is old or that the user has blocked it in its settings

To do this we have used the item noscript, which in this case will display the text in the browser instead of running the script

The example used an external file to include the executable code, using the absolute or relative path in the attribute src

Many web pages do not include scripts in the head, but in the body

The reason for speeding up the loading of HTML, because when you find an external file you have to read and run it, stopping the process of loading the rest of the HTML

Let's imagine that we have the server saturated by the loading of the scripts, the user would not receive anything from the HTML and therefore you would not see the page, just a blank page

For this reason, some developers include the scripts at the end of the document, at the end of the body element

As scripts typically handle interaction with the user, it's not too serious that there's a small delay in starting to see animations, submit forms, etc.

It is easier for the users if you can see the content and then you can interact with it

Styles

The item style allows you to define properties for styles that will apply throughout the document

As you can see in the example, this element usually indicates what you expect to apply, although you can also embed them within the HTML itself

It is also possible to use an external style sheet, in this case we have used the CSS of the twentyfourteen wordpress theme, specifying the relative or absolute path of the file, in the attribute href

Body of an Html page

Body of an Html page

The body of an HTML page includes the content of the web page itself and is defined with the element body

There are a lot of tags that we can use in the body, as a query we can use this listing full

Let's group some of your tags by:

  • Structure of the document

    header, section, navigation

  • The structure of the text

    titles, pararaphos, ...

  • Characterization of the text

    emphasized text, code snippets, ...

Structure of the document

Normally every web page has a title header, some kind of navigation sidebar, a main content and maybe a footer

To achieve this structuring is you can use the item div by divisions

A split cannot be inserted within a lower-level label, such as text structuring and characterization, but it can be inserted within another div element

Thanks to the style sheet, and generic attributes id and class give format to these groupings

The structure of the web sample is fairly standard and the divisions that we see repeated constantly

This is why from HTML5 were added to a series of divisions with meaning to be able to tell more easily how we structure the web

Elements of semantic structure

These elements are analogous to divisions, but they also have associated a meaning related to the structure

In the example we can see that we have been able to replace some divisions by a label equivalent

Some of the most important semantic structuring labels are:

In the example we can see that we have been able to replace some divisions by a label equivalent

Some of the most important semantic structuring labels are:

  • header

    represents the header of a document or section

    To be used to contain introductory information

    There may be more than one in the document

  • footer

    it represents the closure of a document or section

    It usually contains information about the author, copyright, terms of use, contact information, etc

  • nav

    represents the section that contains the navigation links for the web site

  • section

    defines a section of the document

  • article

    represents a content-independent and self-contained

    For example blog posts, news, comments, etc

  • aside

    defines content that is located outside of the place in which it is contained

    As for example a sidebar

    It is usually related to the element that contains

  • figure

    define an independent element such as an image, a code snippet, a diagram, etc

    It is usually related to the element it contains, but its position is independent of the same

  • figcaption

    is the title or reading of an element figure

    It is usually put as the first or last element of the same

  • details

    represents a series of additional details that the user can hide

Elements of structure of a text

The tags structure of a text serve to define the headings of the sections and paragraphs

Among the block labels we highlight the following:

  • p

    contains the text of a paragraph

    The browser does not display the white spaces or extra line breaks to write within the paragraph

  • hN

    defines section headings (there are 6 levels, where N is 1 to 6)

    Can be configured how you see the headers through CSS

    Normally a higher source is used the higher the level, with h1 being the highest level

    Changing the number you can get different visual effects by changing the size of the letter

    These elements are used to structure the document in sections, subsections, etc

  • pre

    contains a paragraph with preformatted text, that is, it will appear as if it had been written with a typewriter, with a fixed spacing font (Courier)

    Takes into account the white spaces and extra line breaks

    It may be useful to write paragraphs with examples of source code

    In the example we simulated a table, although for that task it is advisable to better use the label for tables

    Other types of elements can be simulated, as text will be taken literally, but it is advisable to use their specific tags, as long as they exist

    With what we will get:

    Text
         Tabbed text
    
    Simulation table
    
    column1    column2    column3   column4
    row11      row12      row13     row14
    row21      row22      row23     row24
    

  • blockquote

    is used to include quotations, which may contain multiple paragraphs or other elements

    Generates left and right margins, although it is recommended to define the desired format using a style sheet

    In the example you have used the attribute cite to indicate the origin of the quotation, in this case the novel by Don Quixote de la Mancha, since we have quoted a paragraph of the beginning of the novel

    With what we will get:

    In a place of the stain of whose name does not want to remember me…

  • tt

    we get the text to have a smaller size and the appearance of the characters of a typewriter

    It does not preformat the text, but only changes its appearance

    In the example you have written a paragraph, and we have given the appearance of the characters of a typewriter

    With what we will get:
    Sometimes... I see dead

Elements of characterization from the text

It is generally used within paragraphs

They serve to define the format of the text, although thanks to the style sheets, fewer and fewer

They are maintained for compatibility with older versions of HTML, among the most important ones we highlight:

  • br

    adds a line break without a change of paragraph

    Has No closing tag

    In the example you have written a paragraph, and within the same we have used the line break

    With what we will get:

    Sometimes…
    I see dead

  • nbsp

    it's not a label, but rather a way to add additional blanks for the browser to recognize

    If we want to force him to do it, we have to put the code nbsp (non-breaking space)

    In the example a paragraph has been written and within it we have added a blank space, but we have forced the appearance of another additional

    With what we will get:

    Sometimes… I see dead

  • center

    allows you to center an element, whether it's a paragraph, text, image, etc

    Some older browsers did not support it, although little is currently used as many elements include a similar attribute that replaces it

    Another cause of its disuse is because it is possible to simulate it using style sheets

    In the example you have written a paragraph, and we forced her focused

    With what we will get:

    Sometimes… I see dead

  • hr

    you get a horizontal stripe as wide as the screen, and with the appearance of being embedded on the background

    Has No closing tag

    In the example a paragraph has been written and we have added a horizontal stripe to separate it to simulate that there are two paragraphs

    With what we will get:

    Sometimes… I see dead


    In a place of the stain of whose name does not want to remember me…

  • sup

    is to obtain a mathematical formula that includes an index

    In the example, a text has been written with a mathematical formula in which we have assigned the index 2

    With what we will get:
    m2

  • sub

    is to obtain a mathematical formula that includes a subscript

    In the example we have written a text with a mathematical formula in which we have assigned it subscript 2

    With what we will get:
    m2

  • italic

    puts the text in italics

    You can use the short form i, as it is equivalent

    In the example you have written a text in italics

    With what we will get:
    Sometimes… I see dead

  • em

    indicates that the text will be angry, usually the text is put in italics, although if we use a style sheet we can choose how it will be angry

    In the example you have written a text enfacitado

    With what we will get:
    Sometimes… I see dead

  • bold

    puts the text in bold

    You can use the short form b, as it is equivalent

    In the example you have written a text in bold

    With what we will get:
    Sometimes… I see dead

  • strong

    indicates that the text will be further angry, usually the text is put in bold, although if we use a style sheet we can choose how it will be angry

    In the example you have written a text with a greater emphasis

    With what we will get:
    Sometimes… I see dead

  • code

    embeds code in the middle of a paragraph in a similar way to pre, but without creating margins left and right

    The example has written a paragraph with the special character of white space, but when embedded as code, the page will display it literally

    With what we will get:

    Sometimes…&nbsp;I see dead

Lists in Html

Lists in Html

We will often be interested in presenting things in the form of lists, as they allow us to make enumerations of elements, using a numbering or not, also create definitions of terms

You can choose from three different types:

  • Numbered lists

    serve to create a list with numbers

  • Bulleted lists

    serve to create a list with symbols or bullets, are not numbered

  • Lists of definitions

    are used to create term definitions, are not numbered, and can be used to simulate dictionaries

Numbered lists

Ordered lists are used to present things in a particular order

A correlative number for each item will automatically appear in the resulting list:

In the example you can see that the ordered list starts with the item ol included inside the list of elements li

You have used the attribute type to specify what type of numbering we want to use:

  • 1

    uses numeric values

  • to

    use lowercase letters

  • To

    use letters in uppercase

  • i

    uses roman numerals in lowercase

  • I

    uses roman numerals in uppercase

If not specified, the default is 1

You have used the attribute start to specify from which numbering begins, in this case it starts from the number 3

You have used the attribute value to specify a specific value for that element, in this case the number 8

In the example we can also see that lists with numbered can be nested

Remaining as a result:

  1. Mammals
  2. Fish
    1. Sardine
    2. Cod
  3. Birds

Bulleted lists

Unordered lists are used to present things that, because they do not have a particular order, do not need to be preceded by a number

The resulting list automatically displays the symbol or bullet chosen with the attribute:

In the example you can see that the ordered list starts with the item ul included inside the list of elements li

You have used the attribute type to specify what type of bullet we want to use:

  • circle

    use a circle

  • disc

    use a circle with the hollow interior

  • square

    use a square

If not specified, the default is circle

In the example we can also observe that bulleted lists can be nested and in addition we have used different types of bullets to distinguish between them

Remaining as a result:

  • Mammals
  • Fish
    • Sardine
    • Cod
  • Birds

Lists of definitions

Definition lists are appropriate for glossaries (or term definitions)

Thanks to this type of list, simple dictionaries can be built

In the example you can see that the list of definitions that begins with the element dl included inside the list of elements dt that represent the thing to define and the elements dd that represent the definition of the thing to define

The example has not been included, but we can also nest lists of definitions

Remaining as a result:

Sardine

Fish osteíctio of the order clupeiformes (Sardina pilchardus) in the Mediterranean sea and the Atlantic ocean

About 25 cm long, bluish green on the back, silvery on flanks and belly

Consumed fresh or canned

Cod

Marine fish osteíctio of the order gadiformes (Gadius callarias) which reaches over a meter in length

Links

Links

The links or hyperlinks allow the user to browse non-sequentially, other external websites spread around the world through hypertext links or parts of the same website

For this we use the element to that is an anchor

In example it has been linked to the home page of this website where the attribute href is the destination of the link (it is advisable to use quotation marks (single or double) so that the browser understands that it is of text type) and the text within the element is the indicative text that will appear on the link screen (with a special color and generally underlined)

Remaining as a result:

Home page

Three types of links can be distinguished:

  • With absolute address
  • With relative address
    • Within the same page
    • Within our web
    • Outside of our website
  • E-mail

With absolute address

If we want to link to our page or a page that is outside of ours (i.e. it is on a server other than the one that we have hosted it)

You need to know your full address, or URL (Uniform Resource Locator)

The URL could be, in addition to the address of an Internet page, an ftp address, gopher or other internet service

The destination of the link will in these cases be the initial or default page of that web page, which will normally be by default index.html, index.htm, index.php or index.asp, will depend on the language used when writing the web page

For that reason, we will be able to skip that login page and it depends how your server is configured, you'll get the desired response or a type 404 error wrong direction

In the example it has been linked to the Microsoft home page by using the URL of a secure website HTTPS and you have used the attribute target with the value _blank to instruct the browser to open a new window with the linked page, so that we can see both pages without losing the content that we were previously viewing

It is very important to copy these addresses correctly (respecting the case, because the servers are able to distinguish them and may not recognize the address we have written, returning the aforementioned error 404 of incorrect address)

It has also been used for the attribute rel with the values noopener and noreferrer for that is not stored in the cache of the browser

Remaining as a result:

Microsoft Homepage

With relative address

We might have only one page. But most often we have several pages, one initial (or main) and others connected to it, among themselves or with other external ones that in turn are connected to themselves and other external ones

Within the same page

Sometimes, in the case of very large pages, we may be interested in leaping from one position to another

The destination of the link, in this case the site within the page where we want to jump, is replaced by a brand (the word mark can be any word we want, but preceded by the symbol #)

This word (or words, since we can use more than one separated with _) will appear on a colored screen (in the form of hypertext and if we use a CSS style sheet can be modified according to our needs)

In the example, a link has been created at the end of this same page, to which we can jump to the label that we have called end if you click on the link

For it to work properly, there must also be the final link, but the browser will ignore the link because it will not know where to jump

In the example we have the link that we will have to include, in the position that we want to be jump, the attribute has been used for this purpose name, with the chosen value but without using the symbol #

Remaining as a result:

Press to go to the end

Within our web

We can also go to another page of our website hosted in our server

In the example has been linked to the page within this website that talks about the lists, we have included in the attribute href relative direction and parameters, which are preceded by the symbol ? and have the format of variable='value' and if we have more than one, they separate with the symbol &

Remaining as a result:

Lists

The example has been linked to a specific place on the list page, specifically the one that talks about the bulleted list

To this end, the system brands explained above

Remaining as a result:

Bulleted lists

In the examples above we were assuming that the page on which we write the tag and the page to which you want to make the leap they were in the same directory

It may happen that we have organized the Web site with a main directory and subdirectories auxiliary hanging from the same

If the page to which I want to skip is in the subdirectory subdir, then in the href attribute we should have written /subdir/pagina.html, indicating the full path from the root directory to the page page.html

Conversely, if we want to jump from one page to another that is in a previous directory, in the href attribute we should have written ../page.html

In this case, the colons instruct the browser to go to the previous directory

You must use the symbol / to indicate the subdirectories if you are working with a Unix server, and the symbol \, if you are working with a Windows server, because the directory system is treated differently

If we want to avoid the complications of having both subdirectory, we can save everything in the root directory or in a single directory

However, this practice has the disadvantage that everything is more messy and if in the future we want to make modifications it is more complicated to find the contents, than if we had ordered it by specific subdirectories with a name that is descriptive about its content

Outside of our website

Is applied as explained above for the absolute addresses and within our web, but this time the links will not be hosted on our server, but on an external one

E-mail

If we want our users to get in touch with us, we can include our email address in a link

In the example has been included within the attribute href the reserved word mailto followed by a two point along with the email address of the administrator of this website

It has also been repeated within the tag so that the user knows that the link belongs to an email, so that it is easily recognized, although a descriptive message or the image of a mailbox (a metaphor that the user might relate to the email) could have been used, for example

Remaining as a result:

edrunner1@hotmail.com

By clicking the link we will see that the browser will try to open the program that has associated for the management of the mail, with the address of the recipient already filled in, which is the one that appeared in the link

We can also add other values that will be used by the email manager using reserved words that are preceded by the symbol ? and have the format of variable='value' and if we have more than one, they separate with the symbol &

Among the most outstanding we have:

  • subject

    is the recipient user of the mail, by default it will be Feedback

  • cc

    simulates a carbon copy used in case there is more than one recipient, we should indicate them here separating them with the symbol ;

    The recipients will be able to see who are the other recipients

  • bcc it's similar to copying in carbon copy

    In this case the copy is hidden and the recipients will not be able to see who are the other recipients

  • body

    it's the text of the email itself, the mail manager could ignore it or add something to it, such as a farewell message or a signature, so it won't always be the same as what we've written on the link

End

This is the end mark (it does not contain an actual link as it is a binding reference, but because it has text, it will be underlined as if it were) for the previous example of the system brands explained above

Images in Html

Images in Html

Images on a web page are known as bitmaps and can represent icons, buttons, images with transparent areas, or photos

Depending on the level of compression used we will lose quality, so we must know how to choose the format that best suited to our needs:

  • png

    it is a lossless compression format that also supports transparency

    We can represent icons or images with transparent areas, so that is a good alternative for any type of image that is not a photograph

  • jpg or jpeg

    it is a format of compression with loss that does not supports transparency

    It is typically used for photographs

  • gif

    it's a lossless compression format, but it's limited to 256 colors

    It takes up very little space and is ideal for low-quality images, such as icons or buttons

    Supports transparencies and animations

As with HTML editing, we need an image editor for manipulation

There are commercial and very powerful editors like Photoshop, but we can also use editors with a similiar quality and open source like GIMP

We also have the possibility to use some tool that allows us to convert between the different formats, such as ImageMagick

The item to include images in our web page is img which must include at least the attribute src to which we will tell the browser, by means of the relative or absolute path, the name of the image and by its extension, the format of the same

In the example we can see that in addition to the attribute src we have used width that allows us to specify the width of the image

The attribute height that allows you to specify the height of the image

And the attribute alt entering a description (a word or a short sentence) about the image

In principle it can be omitted, but it is beneficial for those who access the page with a browser in the form of only text, since they will not be able to see the image, but at least they will be able to get an idea about it thanks to that description

Remaining as a result:

Secarcam's Computer Science Web

You can capture the images that the browser shows us, in order to save them permanently on your hard drive

From the browser, click on the image with the right mouse key, we will see a menu in which there is the possibility to save the image in the directory of the hard drive that we indicate

In the event that we do not want users to be able to save the images from our website we will need to use some technique to avoid the press of the right key of the mouse using Javascript

Image used as link

In some cases, an image is also used as a link to another page

With regard to the location of the image file, it is used just like a link. If nothing special is indicated, it means that the file is in the same directory as the HTML document we are writing

An image that is not on our system can be uploaded using the same method as the links, the full URL of the image is indicated on the label. Although this is not very advisable, as it would unnecessarily lengthen the loading time of our page

A very important aspect to consider is the size of the images, because a large image is a large file, and this can cause excessive loading time, with the consequent risk that anyone trying to load our page will get tired of waiting, and desist from it

The example has used a thumbnail (miniature reproduction of the image), which links to the image in its true size

This way we don't reload a page too much, and the user will be the one who decides which images they want to upload

Another way to achieve this is to reduce it with an image editor to 150×75, save it with another name, and then make the small one the link of the big

This would be a solution if we used a very old version of Netscape, as it did not recognize the width and height attributes

Remaining as a result:

In the example the image has been used to redirect us to the home page, so we can link the image to the desired page

We can also use icons, buttons or animations to perform this task

In the example we have also used the attribute border with the value 0 because sinó the image will be surrounded by a rectangle of the normal color of the links, in this way, we prevent that rectangle from appearing

Remaining as a result:

By hovering over this image, we check that it also acts as a link even if it lacks the colored rectangle. This may be more aesthetic, although there is a risk that the user will not realize that the image serves as a link

Position of the text relative to the image

To choose the position of the image relative to the text there are different possibilities

The simplest is to place it between two paragraphs, with the text on one side

Using CSS style sheets you can get more elaborate effects, such as animations, motion, rotations, etc

To choose the position of the text relative to the image using the attribute align and allowed the following possibilities:

  • top

    the text is top-aligned

  • middle

    the text appears aligned in the middle

  • bottom

    the text appears bottom-aligned

This attribute is no longer supported in HTML5 and the example has been included for backward compatibility, we recommend that you use a style sheet to get this effect or by using the element div

In the example we have opted to use the item div

Remaining as a result:

Top-aligned text
Text aligned in the middle
Bottom-aligned text