0% found this document useful (0 votes)
11 views107 pages

Python Programming Basics: Data & Functions

This module introduces fundamental programming concepts in Python, focusing on data types, operators, and variables. It emphasizes the use of the print() function for output, explaining its syntax, arguments, and behavior, including the use of escape characters and keyword arguments. The module encourages experimentation with code to reinforce understanding of these concepts.
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)
11 views107 pages

Python Programming Basics: Data & Functions

This module introduces fundamental programming concepts in Python, focusing on data types, operators, and variables. It emphasizes the use of the print() function for output, explaining its syntax, arguments, and behavior, including the use of escape characters and keyword arguments. The module encourages experimentation with code to reinforce understanding of these concepts.
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

Fundamentals of Programming in Python: Module 2

In this module, you will learn about:

The types of data and the basic methods of formatting, data conversion, input and output
data.
Operators.
Variables.

Hello, World!
It's time to start writing real and functional code in Python. For now, it will be
very simple.

As some fundamental concepts and terms are shown, these code fragments
they will not be complex or difficult.

Run the code in the editor window on the right. If all goes well, you will see the line of
text in the console window.

As an alternative, start IDLE, create a new Python source file, place this code.
name the file and save it. Now run it. If everything goes well, you will see a line in the window
from the IDLE console. The code you have executed should seem familiar. You saw something very
similar when we guide you through the IDLE environment setup.

Now we will take a little time to show you and explain what you are seeing and why.
that looks like this.

As you can see, the first program consists of the following parts:

The wordprint.
An opening parenthesis.
A quotation mark.
A line of text:Hello, World!.
Another quote.
A closing parenthesis.

Each of the previous elements plays a very important role in the code.
The function print()
Look at the line of code below:

print("Hello, World!")

The word 'print' that you can see here is the name of a function. That doesn't mean that anywhere
that this word appears, it will always be the name of a function. The meaning of the word comes from
of the context in which the word has been used.

You have probably encountered the term function many times before, during classes of
matemáticas. Probablemente también puedes recordar varios nombres de funciones matemáticas, como
sine or logarithm.

Python functions, however, are more flexible and can contain more content than their
mathematical relatives.

A function (in this context) is a separate part of the computer code that is capable of:

Cause some effect (for example, send text to the terminal, create a file, draw a
image, play a sound, etc.); this is something completely unheard of in the world of
mathematics.
Evaluate a value or some values (for example, the square root of a value or the length of...
a given text); this is what makes Python functions relatives of the concepts
mathematicians.

In addition, many of Python's functions can do both of the previous things together.

Where do functions come from?

They can come from Python itself. The print function is one of these; this function is a value.
Python add-on along with its environment (it is integrated); you don't have to do anything special
(for example, asking someone for something) if you want to use it.
They can come from one or several of the Python modules called extensions; some of
the modules come with Python, others may require a separate installation, whichever it is
In this case, everyone must be explicitly connected with the code (we will show you how to do it.
this soon).
You can write them yourself, adding as many functions as you want and need within it.
program to make it simpler, clearer, and more elegant.
The name of the function must be meaningful (the name of the print function is evident), it prints in the
terminal.

If you are going to use an existing function, you will not be able to change its name, but when you start to
When writing your own functions, you must carefully consider the choice of names.

The print() function


As mentioned earlier, a function can have:

A non-effect.
A result.

There is also a third component of the function, very important, the argument(s).

Mathematical functions usually take an argument, for example, sin(x) takes an x, which is the
measure of an angle.

Python functions, on the other hand, are more versatile. Depending on the needs
individuals can accept any number of arguments, as many as necessary to perform
his tasks. Note: some Python functions do not require any arguments.

print("Hello, World!")

Regardless of the number of arguments required or provided, Python functions demand


strongly the presence of a pair of parentheses - the opening and closing ones, respectively.

If you want to pass one or more arguments to a function, place them inside the parentheses. If you are going to
use a function that has no arguments, it still needs to have the parentheses.

Note: to distinguish common words from function names, place a pair of parentheses.
spaces after their names, even if the corresponding function requires one or more arguments.
This is a standard measure.

The function we are talking about here isprint().

What is the functionprint()Does our example have any argument?

Of course, but what are arguments?

The print() function


The only argument passed to the functionprint()in this example it is a chain:
print("Hello, World!")

As can be seen, the chain is delimited by quotes - in fact, the quotes form the chain.
They cut a part of the code and assign it a different meaning.

We can imagine that the quotes mean something like this: the text between us is not a code. It is not
designed to be executed, and it should be taken as is.

Almost anything I put inside the quotes will be taken literally, not as code, but
loans. Try to play with this particular string - you can modify it. Enter new content or
delete part of the existing content.

There is more than one way to specify a string within Python code, but for now,
this will be enough.

So far, you have learned about two important parts of the code - the function and the string. We have
talked about them in terms of syntax, but now it is time to discuss them in terms of
semantics.

The print() function


The name of the function (print in this case) along with the parentheses and the arguments, form
Invocation of the function.

We will discuss this in greater depth later, but for now, we will throw in a little more of
light to the matter.
print("Hello, World!")

What happens when Python encounters an invocation like the one below?

functionName(argument)

Let's see:

First, Python checks if the specified name is legal (explores its internal data to
find an existing function by name; if this search fails, Python cancels the code.
Secondly, Python checks the function's requirements for the number of
arguments allow you to invoke the function in this way (for example, if a function
specific requires exactly two arguments, any invocation that provides only one
the argument will be considered erroneous and will abort the execution of the code.
Third, Python leaves the code for a moment and jumps into the function that is desired.
invoke; therefore, it also takes the arguments and passes them to the function.
Fourth, the function executes the code, causes the desired effect (if there was one), evaluates the(s)
desired result(s) and complete the task.
Finally, Python returns to the code (the place immediately after the invocation) and
resumes its execution.
LABORATORY

Estimated Time
5 minutes

Difficulty level
Very easy

Objectives
Get familiar with the functionprint()and its formatting capabilities.
Experiment with Python code.
Scenario
The commandprint(), which is one of the simplest directives in Python, simply
print a line of text on the screen.

In your first laboratory:


Use the functionprint()to print the lineHello, World!on the screen.
Once this is done, use the functionprint()again, but this time print your
nombre.
Remove the double quotes and run the code. Observe Python's reaction. What
What type of error occurs?
Then, remove the parentheses, put the double quotes back, and run it again.
code. What type of error occurs this time?
Experiment as much as you can. Change the double quotes to single quotes, use
multiple functionsprint()in the same line and then in different lines. Observe
what is happening.
The print() function

Three important questions must be answered before proceeding:

1. What is the effect caused by the function?print()?

The effect is very useful and spectacular. The function takes the arguments (it can accept more than one
argument and can also accept less than one argument) converts them into a readable format for the
human being if necessary (as you might suspect, chains do not require this action, since the
the chain is already readable) and sends the resulting data to the output device (usually the console);
In other words, anything put in the print() function will appear on the screen.

It is not surprising then, that from now on, you will useprint()very intensely to see
the results of your operations and evaluations.

What arguments do you expect?print()?


Anyone. We will show you soon thatprint()can operate with virtually all types of
Data provided by Python. Strings, numbers, characters, boolean values, objects: any of these
it can be successfully passed toprint().

3. What value does the function evaluate?print()?

None. Its effect is sufficient -print()does not evaluate anything.

The print() function - instructions


By now you already know that this program contains a function call. In turn, the
function invocation is one of the possible types of Python instructions. Therefore,
this program consists of a single instruction.

Of course, any complex program generally contains many more instructions.


What about one. The question is, how do you combine more than one instruction in Python code?

The syntax of Python is quite specific in this area. Unlike most of the
programming languages, Python requires that there is no more than one statement per one
line.

A line can be empty (for example, it may not contain any instruction) but it cannot
It must contain two, three, or more instructions. This is strictly prohibited.

Note: Python makes an exception to this rule: it allows a statement to span across
more than one line (which can be useful when the code contains complex constructs).

Let's expand the code a bit, you can see it in the editor. Run it and notice what you see.
the console.

Your Python console should now look like this:

The Itsy Bitsy Spider climbed up its web.


The rain came and took it away.

This is a good opportunity to make some observations:

The program invokes the functionprint()twice, as you can see there are two lines
separated in the console: this means thatprint()starts its exit from a
new line every time it starts its execution. You can change this
behavior, but you can also use it to your advantage.
Each invocation ofprint()contains a different string, as its argument and the
the console content reflects this means that the instructions in the code
they are executed in the same order in which they were placed in the source file; they do not
Execute the following instruction until the previous one is completed (there are some
exceptions to this rule, but you can ignore them for now).

The print() function - instructions

We have changed the example a bit: we have added an empty invocation of the
functionprint()We call it empty because we haven't added any arguments to it.
function.

You can see it in the editor window. Run the code.

What is happening?

If all goes well, you should see something like this:

The Itsy Bitsy Spider climbed up its web.

The rain came and took her away.

As you can see, the invocation ofprint()it is not as empty as expected


generate a blank line (this interpretation is also correct) its output is just a new one
line.

This is not the only way to produce a new line in the output console. Right away
we will show another way.
The print() function - escape characters and new
line
We have modified the code again. Observe it carefully.

There are two very subtle changes: we have inserted a strange pair of characters into the text.
They look like this:\n .

Interestingly, while you see two characters, Python sees only one.

The backslash (\ has a very special meaning when used within strings,
it is called the escape character.

The word 'escape' must be clearly understood - it means that the series of characters in the
the chain escapes (stops) for a moment (a very short moment) to introduce a
special inclusion.

In other words, the backslash means nothing, but it is just a type of announcement, of
that the following character after the backslash also has a different meaning.

The lettern placed after the backslash comes from the word newline (new line).

Both the backslash and form a special symbol called a character


of a new line (newline character), which prompts the console to start a new line of
exit.

Run the code. The console should now look like this:

The Itsy Bitsy Spider

he/she climbed to his/her web.

The rain came

and she took it away.

As can be seen, two new lines appear in the children's song, in the places
where it has been used\n .
The function print() escape characters and new
line
Using the backslash has two important characteristics:

1. If you want to place only a backslash within a string, do not forget its nature
to escape: you have to duplicate it, for example, the following invocation will cause an error:

print("

While this will not do it:

2. Not all escape pairs (the backslash along with another character) mean something.

Experiment with the code in the editor, run it and observe what happens.
The print() function using multiple arguments
So far, the behavior of the function has been [Link]()without arguments and with
an argument. It is also worth trying to feed the print() function with more than one
argument.

Look at the editor window. This is what we are going to try now:

Itsy bitsy spider climbed up the spider web.

There is a function callprint()but it contains three arguments. All of them are


chains.

The arguments are separated by commas. They have been surrounded by spaces to make them
más visibles, pero no es realmente necesario y no se hará más.

In this case, the commas that separate the arguments play a completely
different from the comma within the string. The first is a part of Python's syntax, the
the second is intended to be displayed on the console.

If you look at the code again, you will see that there are no spaces within the strings.

Run the code and watch what happens.

The console should now display the following text:

The itsy bitsy spider climbed up the spider web.


The spaces, removed from the strings, have reappeared. Can you explain why?

Two conclusions arise from this example:

A functionprint()invoked with more than one argument generates the output in a


single line.
The functionprint()put a space between the arguments emitted by initiative
own.

The print() function - The positional way to pass the


arguments
Now that you know a little about the functionprint()and how to customize it, I'll
We will show how to change it.

You should be able to predict the output without running the code in the editor.

The way we pass arguments to the functionprint()it is the most common in Python,
and is called positional (this name comes from the fact that the meaning of
the argument is dictated by its position, for example, the second argument will be issued
after the first one, and not the other way around).

Run the code and check if the output matches your predictions.

The print() function - keyword arguments


Python offers another mechanism for passing or transmitting arguments, which can be useful.
when one wishes to convince the functionprint()that he changed his behavior a little.

It will not be explained in depth now. This is planned to be done when the topic is addressed.
functions. For now, we just want to show you how it works. Feel free to
use it in your own programs.
The mechanism is called keyword arguments. The name derives from the fact that
that the meaning of these arguments is not taken from their location (position) but from the
special word (keyword) used to identify them.

The functionprint()it has two keyword arguments that can be used for these
purposes. The first of them is calledend.

In the editor window, you can see a very simple example of how to use an argument.
of keyword.

To use it, it is necessary to know some rules:

A keyword argument consists of three elements: a keyword that


identify the argumentend-ends here); a sign of equality(= ); y
an unassigned value to that argument.
Any keyword argument must be placed after the last positional argument.
positional (this is very important).

In our example, we have used the keyword [Link] we have equalized it to


a string that contains a space.

Run the code to see how it works.

The console should now display the following text:

My name is Python. Monty Python.

As you can see, the keyword argumentenddetermines the characters that the function
print() sends to the output once it reaches the end of its positional arguments.

The default behavior reflects the situation in which the argument of the word
keyendit is implied in the following way:end="\n".
The print() function - keyword arguments
And now, it's time to try something more difficult.

If you look closely, you will see that we have used the [Link], but its chain
the assigned is empty (does not contain any character).

What will happen now? Run the program in the editor to find out.

Since to the argumentendnothing has been assigned the functionprint()it doesn't generate either
nothing, once the positional arguments have been exhausted.

The console should now display the following text:

My name is Monty Python.

Note: No new lines have been sent to the output.

The string assigned to the keyword argumentendit can be of any length.


Experiment with it if you like.

The print() function - keyword arguments


It has been established earlier that the functionprint()separate the generated arguments with
spaces. This behavior can also be changed.

The keyword argument that can do this is calledsep(as a separator).

Look at the code in the editor and run it.

The argumentsepdeliver the following result:

My name is Monty Python.

The functionprint()now use a hyphen instead of a space to separate the


generated arguments.

Note: the value of the argumentsepit can also be an empty string. Try it yourself.
The print() function - keyword arguments
Both keyword arguments can be mixed in a call, as here in
the editor's window.

The example doesn't make much sense, but it visibly represents the interactions.
betweenendysep.

Can you predict the output?

Run the code and see if it matches your predictions.

Now that you understand the functionprint(), are you ready to consider learning how
store and process data in Python.

Sinprint()no results could be seen.

LABORATORY

Estimated Time
5 minutes

Level of difficulty
Very easy
Objectives
Getting familiar with the function ofprint()and its formatting capabilities.
Experiment with Python code.
Scenario
Modify the first line of code in the editor, using the keywordssepyend, for
that matches the expected result. Remember to use two [Link]().

Do not change anything in the second invocation ofprint().

Expected Result
Fundamentals of Programming in Python

LABORATORY

Estimated Time
5-10 minutes

Level of difficulty
Easy

Objectives
Experiment with the existing Python code.
Discover and solve basic syntax errors.
Get familiar with the functionprint()and its formatting capabilities.

Scenario
We recommend that you play with the code we have written for you and make some changes.
corrections (perhaps even destructive). Feel free to modify any part of the
code, but there is one condition: learn from your mistakes and draw your own conclusions.
Try:

Minimize the number of function callsprint()inserting the


sequence\n in the chains.
Make the arrow twice as big (but maintain proportions).
Duplicate the arrow, placing both arrows side by side; note: a chain can be
multiply using the following trick:"string" * 2 will producestringstring(te
we will tell you more about it soon).
Remove any of the quotes and carefully observe Python's response;
pay attention to where Python sees an error: is it the place where it really exists
error?
Do the same with some of the parentheses.
Change any of the wordsprintin another thing (for example, from lowercase to
uppercasePrint) - What happens now?
Replace some of the quotes with apostrophes; observe what happens
carefully.
print(" *")

print(" * *")

* *

**

*** ***

print(" * *")

print(" * *")

*****

* * * * * * * *** *** * * * * *****


Literals - the data themselves
Ahora que tienes un poco de conocimiento acerca de algunas de las poderosas características que ofrece
the functionprint()It is time to learn about new issues, and a new term - elliteral.

A literal refers to data whose values are determined by the literal itself.

Since it is a somewhat difficult concept to understand, a good example can be very useful.

Observe the following digits:

123

Can you guess what value it represents? Of course you can - one hundred twenty-three.

How about this:

Does it represent any value? Maybe. It could be the symbol for the speed of light, for example. Also
it can represent the constant of integration. Even the length of a hypotenuse in the Theorem of
Pythagoras. There are many possibilities.

One cannot choose the correct value without some additional knowledge.

And this is the clue:123it's a literal, andcit is not.

Literals are used to encode data and place it within the code. Now we will show some.
conventions that must be followed when using Python.

Let's start with a simple experiment, observe the code snippet in the editor.

The first line looks familiar. The second seems to be incorrect due to the visible lack of
quotes.

Try to execute it.

If all went well, you should now see two identical lines.

What happened? What does it mean?

Through this example, you find two different types of literals:

Unchain, which you already know.


And an integer, something completely new.
The functionprint()it shows them exactly the same way. However,
internally, the computer's memory stores them in two completely different ways
different. The string exists as that, just a string, a series of letters.

The number is converted to a machine representation (a series of bits). The


functionprint()is capable of showing both in a human-readable form.

We are going to take some time to discuss numeric literals and their internal life.

Enteros
You may already know a little about how computers perform calculations with numbers. Perhaps you have
heard about the binary system, and how it is the system that computers use to
store numbers and how they can perform any type of operations with them.

We will not explore the complexities of positional numeral systems, but it can be stated that
All the numbers handled by modern computers are of two types:

Integers, that is, those that do not have a fractional part.


Floating-point numbers (or simply floats), which contain (or are capable of
to contain) a fractional part.

This definition is not so precise, but it is sufficient for now. The distinction is very important, and the
the boundary between these two types of numbers is very strict. Both types differ significantly in
how they are stored in a computer and in the range of values they accept.

The characteristic of the numeric value that determines the type, range, and application is called the type.

If a literal is encoded and placed within Python code, the form of the literal determines the
representation (type) that Python will use to store it in memory.

For now, let's put floating numbers aside (we'll return to them soon) and let's analyze how it is.
that Python recognizes an integer.

The process is almost like using pencil and paper, it's simply a chain of digits that make up the
number, but there is a condition, characters that are not digits should not be inserted within the number.

Let's take, for example, the number eleven million one hundred eleven thousand one hundred eleven. If you were to take a pencil right now
in your hand, you would write the following number:11,111,111, or so:11,111,111, even of this
way11 111 111.
It is clear that the separation makes it easier to read, especially when the number has
too many digits. However, Python does not accept these things. It is prohibited. What is Python
Is it allowed? The use of underscores in numeric literals.

Therefore, the number can be written either like this:11111111, or as it continues:11,111,111.

NOTEPython 3.6 has introduced the underscore in numeric literals, allowing you to place a
underscore between digits and after base specifiers to improve readability. This
This feature is not available in earlier versions of Python.

How are negative numbers encoded in Python? As is usually done, by adding a sign.
at least. It can be written:-11111111, or-11_111_111.

Positive numbers do not require a preceding positive sign, but it is allowed if one wishes to do so.
The following lines describe the same number:+11111111y11111111.

Integers: octal and hexadecimal numbers


There are two additional conventions in Python that are not known in the world of the
mathematics. The first allows us to use a number in its octal representation.

If an integer is preceded by a code0O o0o(zero-o), the number will be processed


as an octal value. This means that the number must contain digits in the range of [0..7]
only.

0o123it is an octal number with a (decimal) value equal to83 .

The functionprint()perform the conversion automatically. Try this:

print(83)

The second convention allows us to use hexadecimal numbers. Such numbers must
to be preceded by the prefix0xo0X(zero-x).

0x123it is a hexadecimal number with a (decimal) value equal to291The print() function
can also handle these values. Try this:

print(291)
Floats
Now it is time to talk about another type, which is designated to represent and store the
numbers that (as a mathematician would say) have a non-empty decimal part.

They are numbers that have (or can have) a fractional part after the decimal point, and although
this definition is very poor, it is sufficient for what is intended to be discussed.

When comfortable terms and about zero point four are used, we think of numbers that the
computer considers as floating-point numbers:

2.5

-0.4

Note: two point five looks normal when written in a program, however if your native language
prefers the use of a comma instead of a period, it must ensure that the number does not contain more
commas.

Python will not accept it, or (in unlikely cases) it may misinterpret the number, due to the
comma has its own meaning in Python.

If you want to use only the value of two point five, it should be written as shown earlier.
Note that there is a point between the 2 and the 5 - not a comma.

As you can imagine, the value zero point four can be written in Python as:

0.4

But one must not forget this simple rule, the zero can be omitted when it is the only digit before the
decimal point.

In essence, the value0.4It can be written as:

.4

For example: the value of4.0it can be written as:

4.
This will not change its type or its value.

Integers vs. Floats


The decimal point is essentially important for recognizing floating-point numbers in Python.

Observe these two numbers:

4
4.0

One might think they are identical, but Python sees them in a completely different way.

4it is an integer, while4.0it is a floating-point number.

The decimal point is what determines whether it is floating.

On the other hand, it is not only the point that makes a number floating. The letter can also be used.e .

When one wishes to use numbers that are very small or very large, it can be implemented
scientific notation.

For example, the speed of light, expressed in meters per second. Written directly it would look like this.
the following way:300,000,000.

To avoid writing so many zeros, textbooks use the abbreviated form, which probably
you have seen3 times 108 .

It reads as follows: three times ten raised to the eighth power.

In Python, the same effect can be achieved in a similar way, observe the following:

3E8

The letterE(lowercase letters can also be usede- comes from the word exponent) which
significant for ten to the power of n.

Note:

The exponent (the value after the E) must be an integer.


The base (the value before the E) can or may not be an integer.
Encoding Floats
Let's now see how to store numbers that are very small (in the sense that they are very close
from zero).

A physical constant known as 'Planck's Constant' (denoted as h), according to the


textbooks, has a value of: 6.62607 x 10-34.

If you wanted to use it in a program, it should be written as follows:

6.62607E-34

Note: the fact that one of the possible ways of encoding a floating point value has been chosen
it does not mean that Python will present it in the same way.

Python might occasionally choose a different annotation.

For example, let's suppose that the following notation has been chosen:

0.0000000000000000000001

When running in Python:

print(0.0000000000000000000001)

This is the result:

1e-22

exit

Python always chooses the shortest presentation of the number, and this should be taken into consideration.
when creating literals.

Chains
Strings are used when it is necessary to process text (such as names of any kind, addresses,
novels, etc.), no numbers.

Ya conoces un poco acerca de ellos, por ejemplo, quelas cadenas requieren comillas,así como los
float numbers need a decimal point.

This is an example of a string:I am a chain.


However, there is a question. How can you encode a quote within a string that is already
delimited by quotes?

Let's suppose we want to display a very simple message:

I like 'Monty Python'

How can this be done without generating an error? There are two possible solutions.

The first is based on the already known concept of the escape character, which you will remember is used
using the backslash. The backslash can also escape the quote. A
a quote preceded by a backslash changes its meaning, it is not a limiter, it simply is
a quote. The following will work as desired:

I like "Monty Python"

Note: Are there two escaped quotes in the string, can you see both?

The second solution may be a bit surprising. Python can use an apostrophe instead of
a quote. Any of these two characters can delimit a string, but for that it must be
be consistent.

If a string is enclosed with a quote, it must be closed with a quote.

If a string starts with an apostrophe, it must end with an apostrophe.

This example will work as well:

I like "Monty Python"

Note: in this example, no escapes are required.

Encoding strings
Now, the next question is: How can an apostrophe be inserted into a string that
Is it limited by two apostrophes?
At this point, there should already be a possible answer or two.

Try to print a string that contains the following message:

I'm Monty Python.

Do you know how to do it? Click on Review to see if you are right:

Review
I'm Monty Python.
o

I'm Monty Python.

As can be seen, the inverted diagonal is a very powerful tool, it can


escape not only quotes but also apostrophes.

It has already been shown, but emphasis is desired on this phenomenon once more - a
The string can be empty - it may not contain any character.

An empty string is still a string:

''

""

Boolean Values
To conclude with the literals of Python, there are two more.

They are not as obvious as the previous ones and are used to represent a very abstract value - the
veracity.

Every time Python is asked if one number is larger than another, the result is the creation of
a very specific data type - a boolean value.

The name comes from George Boole (1815-1864), the author of The Laws of Thought, which
define Boolean Algebra - a part of algebra that uses two
values:TrueyFalse, denoted as1y0 .

A programmer writes a program, and the program asks questions. Python executes the program, and
provide the answers. The program must be able to react according to the received answers.

Fortunately, computers only know two types of responses:


Yes, this is true.
No, this is false.

There will never be an answer like: I don't know, probably yes, but I'm not sure.

Python is then a binary reptile.

These two boolean values have strict denotations in Python:

True
False

They cannot be changed; these symbols must be taken as they are, even respecting the uppercase letters.
lowercase.

Challenge: What will be the result of the following code snippet?

print(True > False)


print(True < False)

Run the code in the terminal. Can you explain the result?

LABORATORY

Estimated Time
5 minutes

Level of difficulty
Easy
Objectives
Get familiar with the functionprint()and its formatting capabilities.
Practice coding strings.
Experiment with Python code.
Scenario
Write a single line of code, using the functionprint(), as well as the characters of
new line and escape, to get the expected output of three lines.

Expected Output
I am

learning

Python

exit

Key Points
[Link] notation to represent fixed values in the code. Python has several types of
literals, that is, a literal can be a number for example,123), or a string (for example, "I am
a literal.

2. The Binary System is a numerical system that uses 2 as its base. Therefore, a number
binary is composed of only 0s and 1s, for example,1010it is 10 in decimal.

Octal and Hexadecimal numbering systems are similar as they use 8 and 16 as their bases.
respectively. The hexadecimal system uses decimal numbers plus six additional letters.

3. Integers (or simply int) are one of the numeric types supported by Python. They are numbers
that do not have a fractional part, for example,256, o-1(negative integers).

4. Floating-Point numbers (or simply floats) are another numeric type supported by Python.
They are numbers that contain (or are capable of containing) a fractional part, for example,1.27.
5. To encode an apostrophe or a quote within a string, you can use the escape character.
for example,I'm [Link] open and close the chain using a set of different symbols
to the symbol that is to be encoded, for example,I'm [Link] encode an apostrophe, andHe
he said 'Python', not 'typhoon'to encode quotes.

6. Boolean values are two constant [Link] for


represent truth values (in numerical contexts1it isTruewhile0es False).

EXTRA

There is a special literal more used in Python: the literalNoneThis literal is called an object
ofNonType(no type), and can be used to represent the absence of a value. Soon it
hablará más acerca de ello.

Exercise 1

What types of literals are the following two examples?

{"Hola":"Hello","007":"007"}
Review

Both are chains.

Exercise 2

What type of literals are the following four examples?

"1.5", 2.0, 528, False


Review

The first is a string, the second is numeric (float), the third is numeric (integer) and the fourth
it is boolean.

Exercise 3

What is the decimal value of the following binary number?


1011
Review

It is11 , because (2**0) + (2**1) + (2**3) = 11

Python as a calculator
Now, a new side of the print() function is going to be shown. It is already known that the function is capable
to show the values of the literals that are passed to it by the arguments.

In fact, it can do something more. Observe the following code snippet:

print(2+2)

Rewrite the code in the editor and run it. Can you guess the output?

You should see number four. Feel free to experiment with other operators.

Without taking this too seriously, you have discovered that Python can be used as a
calculator. Not a very useful one, and definitely not a pocket one, but a calculator without
without a doubt.

Taking this more seriously, we are venturing into the territory of


the operators and expressions.

The Basic Operators


Unoperators a symbol of the programming language, which is capable of performing
operations with the values.

For example, like in arithmetic, the sign of+ (but) it is an operator that is capable
added numbers, giving the result of the sum.

However, not all Python operators are as simple as the plus sign.
let's look at some of the operators available in Python, the rules that must be followed
to use them, and how to interpret the rules they carry out.

It will begin with the operators that are associated with the arithmetic operations more
known:

+ , - , * , / , // , % , **
The order in which they appear is not by chance. We will talk more about it when they have
seen everyone.

Remember: When data and operators are combined, they form joint expressions. The expression
the simpler one is the literal.

Arithmetic operators: exponentiation


A sign of** (double asterisk) is an exponentiation (power) operator. The argument
on the left is the base, on the right, the exponent.

Classical mathematics prefers notation with superscripts, like the following: 23The
plain text editors do not accept that notation, therefore Python uses** instead of the
mathematical notation, for example,2 raised to the power of 3.

Observe the examples in the editor window.

Note: In the examples, the double asterisks are surrounded by spaces, it is not mandatory.
do it, but make the code more readable.

The examples show an important feature of numerical operators.


Python.

Run the code and carefully observe the results it produces. Can you observe
something?

Remember: It is possible to formulate the following rules based on the results:

When both** arguments are integers, the result is also an integer.


When at least one** if the argument is floating, the result is also floating.

This is an important distinction to remember.


Arithmetic operators: multiplication
A symbol of* (asterisk) is a demultiplication operator.

Run the code and check if the integer vs floating point rule still works.

print(2 * 3)

print(2 * 3.)

print(2. * 3)

print(2. * 3.)

Arithmetic operators: division


A symbol of/ (diagonal) is a division operator.

The value after the diagonal is the dividend, the value before the diagonal is the divisor.

Run the code and analyze the results.

print(6 / 3)

print(6 / 3.)

print(6. / 3)

print(6. / 3.)
You should be able to see that there is an exception to the rule.

The result produced by the division operator is always floating-point, regardless of whether to
at first glance, the result is floating:1 / 2, or it seems to be completely whole:2 / 1.

Does this cause a problem? Yes, at times it may be necessary for the result of a
division should be integer, not floating.

Fortunately, Python can help with that.

Arithmetic operators: integer division


A symbol of// (double diagonal) is an integer division operator. It differs from the operator
standard/ in two details:

The result lacks the fractional part, it is absent (for integers), or always
it is equal to zero (for floats); this means that the results are always
rounded.
It adjusts to the whole number vs float rule.

Run the example below and observe the results:

print(6 // 3)
print(6 // 3.)
print(6. // 3)
print(6. // 3.)

As can be observed, an integer divided by an integer yields an integer result. All


the other cases produce floats.

Let's do some more advanced tests.

Observe the following code snippet:

print(6 // 4)
print(6. // 4)

Imagine that it was used/ instead of// Could you predict the outcomes?

Yes, it would be1.5in both cases. That is clear.

But, what result should be expected from a division?// ?

Run the code and see for yourself.

What is obtained are two ones, one integer and one floating.

The result of the integer division is always rounded down to the nearest lower integer value of
result of the non-rounded division.

This is very important: rounding always goes down.

Observe the code and try to predict the result again:

-2
print(6. // -4)

Note: Some of the values are negative. This will obviously affect the result. But
how?

The result is a pair of two negatives. The actual result (not rounded) is-1.5in both
cases. However, the results are rounded. The rounding is done to the value
lower intestine, the said value is-2 therefore, the results are:-2y-2.0.
NOTE

Integer division is also often referred to in English as floor division. Later on, I will...
you will cross with this term.

Operators: remainder (modulus)


The following operator is a very peculiar one, because it has no equivalent within the
traditional arithmetic operators.

Its graphical representation in Python is the symbol of% (percentage), which can be a
a little confused.

Think of it as a diagonal (division operator) accompanied by two small ones.


circles.

El resultado de la operación es elresiduo que queda de la división entera.

In other words, it is the value that remains after dividing one value by another to produce a
integer result.

Note: the operator is sometimes also referred to as modulo in other languages.


programming.

Observe the code snippet - try to predict the result and then execute it:

print(14 % 4)

As you can see, the result is two. This is the reason:

14 // 4results in a3→ this is the whole part, that is to say the quotient.
3 * 4results in12→ as a result of the multiplication between the
quotient and the divisor.
14 - 12 results in2this is the waste.

The following example is a bit more complicated:

print(12 % 4.5)

What is the result?


Review

3.0no3but3.0(the rule still works:12 // 4.5of2.0; 2.0 * 4.5from9.0; 12


9.0from3.0)

Operators: how not to divide


As you probably know, division by zero does not work.

Don't try:

Dividing by zero.
Perform an integer division by zero.
Finding the remainder of a division by zero.

Operators: addition
The symbol of the operator desum is the+ (plus sign), which is completely aligned
to the mathematical standards.

Again, observe the following code snippet:

print(-4 + 4)

print(-4. + 8)

The result should not surprise you. Run the code and check the results.

The subtraction operator, unary and binary operators


The symbol of the subtraction operator is obviously- (the minus sign), however, you must
Note that this operator has another function - it can change the sign of a number.

This is a great opportunity to mention a very important distinction between


unary and binary operators.

In subtraction applications, the subtraction operator expects two arguments: the left one
(subtracting in arithmetic terms) and the law (subtracting).

For this reason, the subtraction operator is considered one of the binary operators, just like
the other operators of addition, multiplication, and division.

But the negative operator can be used in a different way, observe the last line.
of the code of the following fragment:

-8

print(4. - 8)

print(-1.1)

By the way: there is also an operator+ unary. It can be used as follows:

print(+2)

The operator retains the sign of its only argument, the one on the right.

Although this construction is syntactically correct, using it doesn't make much sense, and
It would be difficult to find a good reason to do it.

Look at the code fragment above - Can you guess the result or output?

Operators and their priorities


So far, each operator has been treated as if it had no relation to the others. Obviously, such a
Such a simple and ideal situation is very rare in real programming.

Also, you will often find more than one operator in an expression, and then this assumption already
it's not that obvious.
Consider the following expression:

2 + 3 * 5

You probably remember from school that multiplications precede additions.

Surely you will remember that first you have to multiply 3 by 5, keep the 15 in your memory and
after adding 2, resulting in 17.

The phenomenon that causes some operators to act before others is known as hierarchy.
of priorities.

Python defines the hierarchy of all operators, and assumes that operators with higher hierarchy should
perform their operations before those of lower hierarchy.

So, if it is known that the* has a higher priority than the+ The final result must be obvious.

Operators and their links


In Elenlacede, an operator determines the order in which the operations of the operators are computed with
the same priority, which are within the same expression.

Most Python operators have left-to-right binding, which means that the
The evaluation of the expression is carried out from left to right.

This simple example will show you how it works. Observe:

print(9 % 6 % 2)

There are two possible ways to evaluate the expression:

From left to right: first9 % 6 results in3 , and then3 % 2 it gives like
result1 .
From right to left: first6 % 2 results in0 , and then9 % 0causaun
fatal error.

Run the example and see what you get.

The result must be1 The operator has a leftward linkage. But there is an exception.
interesting.

Operators and their links: exponentiation


Repeat the experiment, but now with exponents.

Use this code snippet:

print(2 ** 2 ** 3)

The two possible outcomes are:

2 ** 2 → 4 ; 4 ** 3 → 64
2 raised to the power of 3→ 8 ; 256→ 256

Run the code, what do you observe?

The result clearly shows that the exponentiation operator uses chaining towards
the right.

Priority list
Since you are new to Python operators, a complete list of them is not presented for now.
operators' priorities.

Instead, only a few will be shown, and they will expand as they are introduced.
new operators.

Observe the following table:

Priority Operator

1 +, - unary

2 **

3 *, /, %

4 +, - binary

Note: operators are listed in order from highest (1) to lowest (4) priority.
Try to solve the following expression:

print(2 * 3 % 5)

Both operators (* y% they have the same priority, the result can only be obtained by knowing the
sense of linking. What will the result be?

Review

Operators and parentheses


Of course, the use of parentheses is allowed, which will change the natural order of the calculation.
operation.

According to the arithmetic rules, the sub-expressions within the parentheses are always
they calculate first.

As many parentheses as needed can be used, and they are used to improve the
legibility of an expression, even if the order of operations does not change.

An example of an expression with multiple parentheses is the following:

print((5 * ((25 % 13) + 100) / (2 * 13)) // 2)

Try to calculate the value that will be calculated in the console. What is the result of the functionprint()?

Review10.0

Key Points
An expression is a combination of values (or variables, operators, function calls,
you will learn about it soon) which are evaluated and result in a value, for example,1+2.
2. The operators are special symbols or keywords that are able to operate on the values and
perform mathematical operations, for example, the* multiply two values:x*y.

3. The arithmetic operators in Python:+ (sum)- rest* (multiplication)/ classic division:


they return a float if one of the values is of this type),% (module: divide the left operand by
the right operand and returns the remainder of the operation, for example,5%2=1), ** (exponentiation: the
the left operand is raised to the power of the right operand, by
example2 raised to the power of 3 equals 2 times 2 times 2 equals 8), // (integer division: returns the resulting number of the division, but
rounded down to the nearest lower whole number, for example,3//2.0=1.0).

4. A unary operator is an operator with only one operand, for example,-1 , o+3 .

5. A binary operator is an operator with two operands, for example,4+5, o 12%5.

6. Some operators act before others, this is called -priority hierarchy:

Unary+ y- they have the highest priority.


After:** , later:* , / , and% and then the lowest priority: binary+ y- .

7. The sub-expressions within parentheses are always calculated first, for example,15-
1*(5*(1+2))=0.

8. Exponentiation operators use right-to-left binding, for


example2 raised to the power of 2 raised to the power of 3 equals 256.

Exercise 1

What is the output of the following code snippet?

print((2**4), (2*4.), (2*4))


Review

16 8.0 8

Exercise 2

What is the output of the following code fragment?

print((-2/4), (2/4), (2//4), (-2//4))


Review
-0.5 0.5 0 -1

Exercise 3

What is the output of the following code snippet?

print((2%-4), (2%4), (2**3**2))


Review

-2 2 512

What are variables?


It is fair that Python allows us to encode literals that contain numeric values and strings.

We have already seen that arithmetic operations can be performed with these numbers: addition, subtraction, etc. This
it will be done countless times in a program.

But it is normal to ask how the results of these operations can be stored, for
be able to use them in other operations, and so on.

How to store intermediate results, and then use them again to produce results
subsequent?

Python will help with that. Python offers special 'boxes' (containers) for this purpose, these boxes
they are called variables - the name itself suggests that the content of these containers can vary
in almost any form.

What are the components or elements of a variable in Python?

A name.
A value (the content of the container).

Let's start with what is related to the variable name.

Variables do not appear in a program automatically. As a developer, you must decide.


How many variables do you want to use in your program.

You should also name them.

If you want to name a variable, you must follow the following rules:

The name of the variable must be composed of UPPERCASE, lowercase, digits, and
the character_ (underscore)
The variable name must start with a letter.
The underscore character is considered a letter.
Uppercase and lowercase letters are treated differently (a little differently than in the world
real -AliciayALICIA are the same name, but in Python they are two variable names
Different, subsequently, are two different variables.
The names of the variables cannot be the same as any of the reserved words in Python.
I will explain more about this soon.

Nombres correctos e incorrectos de variables


Note that the same restriction applies to function names.

Python imposes no restrictions on the length of variable names, but that does not mean that
a long variable name is better than a short one.

Here are some variable names that are correct, but not always convenient:

MyVariable, i , t34, Tasa_Cambio, counter, Days until Christmas, TheNameIsSoLong


Mistakes will be made with it., _ .

In addition, Python allows the use of not only Latin letters but also specific characters from other languages.
that use other alphabets.

These variable names are also correct:

Goodbye, Madam, sure_on_the_sea, One-way street, переменная.

Now let's look at some incorrect names:

10t(does not start with a letter)Exchange Rate(contains a space).


Keywords
Observe the words that play a very important role in each Python program.

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',


'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
["from","global","if","import","in","is","lambda","nonlocal"]
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with',
yield

They are called keywords (or rather) reserved words. They are reserved because they should not be
use as names: neither for variables, nor for functions, nor for anything else that is desired
create.

The meaning of the reserved word is predefined and should not change.

Fortunately, due to the fact that Python is case-sensitive, any of


these words can be modified by changing one or several letters from uppercase to lowercase or
vice versa, creating a new word, which is not reserved.

For example - you cannot name the variable like this:

import

You cannot have a variable with that name, it is prohibited, but you can do the following:

Import

These words may seem like a mystery right now, but soon you will learn about their meaning.

Creating variables
What can be put inside a variable?

Anything.

A variable can be used to store any type of the values that have already been mentioned, and
many more of which have not yet been explained.

The value of the variable is what has been set inside it. It can vary as much as needed or
It may require. The value can be an integer, then a float, and eventually be a string.

Let's talk about two important things - how variables are created, and how to assign values to them.
them (or better said, how to pass values to them).
REMEMBER

A variable is created when a value is assigned to it. Unlike other programming languages,
it is not necessary to declare it.

If any value is assigned to a non-existent variable, the variable will be automatically created. No
something more needs to be done.

The creation (or its syntax) is very simple: it only uses the name of the desired variable, then the
equals sign (=) and the value that you want to place within the variable.

Observe the following code fragment:

var = 1
print(var)

It consists of two simple instructions:

The first creates a variable calledvar, and assigns it a literal with an integer value of1 .
The second prints the value of the newly created variable to the console.
Note:print()It has one more function - it can also handle variables. Can you predict what it will be?
the output (result) of the code?

Review

Using variables
It is allowed to use as many variable declarations as necessary to achieve the objective of the
program, for example:

var = 1

balance_cuenta = 1000.0

nombreCliente = 'John Doe'

print(var, account_balance, customer_name)

print(var)

However, it is not allowed to use a variable that does not exist, (in other words, a variable that to which
it has not been given a value.

This example will cause an error:

var = 1

print(Var)

Efforts have been made to use the variable calledVar, which has no value (note: varyVarson
different entities, and they have nothing in common within Python.

REMEMBER

It can be usedprint()to combine text with variables using the operator+ to show
strings with variables, for example:

var = "3.7.1"

print("Python version: " + var)


Can you predict the output of the code fragment?

Review

Versión de Python: 3.7.1

Assign a new value to an existing variable


How do you assign a new value to a variable that has already been created? In the same way. You simply ...
it needs the equal sign.

The equal sign is actually an assignment operator. Although this may sound a bit strange, the
the operator has a simple syntax and a clear and precise interpretation.

Assign the value of the right argument to that of the left, even when the right argument
it is an arbitrary complex expression that involves literals, operators, and defined variables
previously.

Observe the following code:

var = 1

print(var)

var = var + 1

print(var)

The code sends two lines to the console:


1

The first line of the code creates a new variable calledvarand assigns it the value of1 .

The statement reads as follows: assigns the value of1a variable calledvar.

More briefly: assign1avar.

Some prefer to read the code like this:varbecomes1 .

The third line assigns a new value to the same variable taken from the variable itself.
adding it up1 Upon seeing something like this, a mathematician would probably protest, no value can be equated.
one more than itself. This is a contradiction. But Python treats the sign= not the same as, but
how to assign a value.
So, how is this read in a program?

Take the current value of the variablevar, add it up1and store it in the variablevar.

Indeed, the value of the variablevarit has been incremented by one, which is not related to
compare the variable with another value.

Can you predict what the result of the following code fragment will be?

var = 100

var = 200 + 300

print(var)

Review

500- Why? Well, first, the variablevar is created and assigned the value of 100. Then, to the
the same variable is assigned a new value: the result of adding 200 to 300, which is 500.

solving simple math problems


Now you should be able to build a short program that solves problems.
simple mathematics like the Pythagorean Theorem:

The square of the hypotenuse is equal to the sum of the squares of the two legs.

The following code evaluates the length of the hypotenuse (that is, the longest side of a
right triangle, the side opposite the right angle) using the Pythagorean Theorem:

a = 3.0

b = 4.0

c = (a ** 2 + b ** 2) ** 0.5

print("c =", c)

Note: it is necessary to use the operator** to evaluate the square root:

√(x) = x(½)
y
c = √ a2+ b2
Can you predict the output of the code?

Check below and run the code in the editor to confirm your predictions.

Review

c = 5.0

LABORATORY

Estimated Time
10 minutes

Level of difficulty
Easy

Objectives
Familiarize yourself with the concept of storing and working with different types of data
in Python.
Experiment with the code in Python.
Scenario
Next, a story:

Once upon a time in the Land of Apples, Juan had three apples, María had five.
apples, and Adam had six apples. They were all very happy and lived for a very long time.
time. End of History.

Your task is:

Create the variables:john, Maria, andadam.


Assign values to the variables. The value must be equal to the number of apples that
everyone had.
Once the numbers are stored in the variables, print the variables in a
line, and separate each one of them with a comma.
Then a new variable called must be [Link] it must be equalized
to the sum of the three previous variables.
Print the stored value intotal applesin the console.
Experiment with your code: create new variables, assign different values to them,
and perform various arithmetic operations with them (for example, +, -, *, /, //, etc.). Try
put a string with an integer together in the same line, for example,Number
Total de Manzanas:" ytotalManzanas.

Abbreviated Operators
It is time to explain the following set of operators that will make life for the
easier programmer/developer.

Very often, the same variable is desired to be used on the right side and the left side of the operator.= .

For example, if a series of successive values of the power of 2 needs to be calculated, one can use the
next code:

x = x * 2

Also, you can use an expression like the following if you can't sleep and you are trying to
solve it using one of the traditional methods:

oveja = oveja + 1

Python offers a shorter way to write operations like these, which can be coded in the
in the following way:

x is multiplied by 2

sheep += 1

The following attempts to present an overview of this type of operations.


Yesopit is a two-argument operator (this is a very important condition) and the operator is
used in the following context:

variable = variable op expression

It can be simplified as follows:

variable op= expression

Observe the following examples. Make sure to understand them all.

i = i + 2 * j⇒ i += 2 * j

var = var / 2⇒ var /= 2

rem = rem % 10⇒ rem %= 10

j = j - (i + var + rem)⇒ j -= (i + var + rem)

x = x squared⇒ x **= 2

LABORATORY

Estimated time
10 minutes

Level of difficulty
Easy

Objectives
Familiarize yourself with the concept of variables and work with them.
Perform basic operations and conversions.
Experiment with Python code.
Scenario
Miles and kilometers are units of length or distance.

Keeping in mind that1is approximately equivalent to1.61kilometers, complete it


program in the editor to convert from:
Miles to kilometers.
Kilometers to miles.

The existing code should not be changed. Write your code in the indicated places with###.
Prueba tu programa con los datos que han sido provistos en el código fuente.

Pay close attention to what is happening inside the functionprint()Analysis of how it is


that multiple arguments are provided for the function, and how the result is displayed.

Note that some of the arguments within the functionprint()they are chains (for
examplemiles are, and others are variables (for examplemiles).

ADVICE

There is one more interesting thing happening. Can you see another function within the
functionprint()What is the function?round()Your job is to round the output of the result to
number of decimals specified in the parentheses, and return a floating value (within the
functionround()you can find the variable name, the name, a comma, and the
number of decimals that are desired to be displayed). We will talk more about this function very soon, no
Don't worry if not everything is very clear. It's just meant to spark your curiosity.

After completing the lab, open Sandbox and experiment further. Try
write different converters, for example, a converter from USD to EUR, a converter
of temperature, etc. - let your imagination soar! Try to show the results
combining strings and variables. Try to use and experiment with the functionround()for
round your results to one, two, or three decimal places. Check what happens if you don't
provide a digit when rounding. Remember to test your programs.

Experimenta, saca tus propias conclusiones, y aprende. Se curioso.

Expected Result
7.38 miles is 11.88 kilometers

12.25 kilometers is 7.61 miles


LABORATORY

Estimated Time
10-15 minutes

Difficulty Level
Easy

Objectives
Familiarize yourself with the concepts of numbers, operators, and arithmetic operations
in Python.
Perform basic calculations.
Scenario
Observe the code in the editor: read a valuefloating, it assigns it to a variable calledx , and
print the value of the variable calledy Your task is to complete the code to evaluate the
next expression:

3x3- 2x2+ 3x - 1
The result must be assigned toy .

Remember that classical algebraic notation often omits the multiplication operator,
here it should be included explicitly. Note how the data type changes for
to ensure thatxit is of the typefloating.

Keep your code clean and readable, and test it using the provided data.
Don't get discouraged for not achieving it on the first attempt. Be persistent and curious.
Data Test
Sample Data

x = 0

x = 1

x = -1

Expected Output

y = -1.0

y = 3.0

y = -9.0

Key Points
1. Variables are a named location reserved for storing values in memory.
A variable is created or initialized automatically when it is assigned a value by
first time.

2. Each variable must have a unique name - an identifier. A valid name must
be one that does not contain spaces, must start with an underscore(_ ), or a letter, and not
it can be a reserved word in Python. The first character can be followed by
underscores, letters, and digits. Variables in Python are case-sensitive and
lowercase.

3. Python is a dynamically typed language, which means that it does not


you need to declare variables in it. To assign values to the variables, you simply use
the assignment operator, that is, the equal sign (=)= ) for example,var = 1.

4. It is also possible to use compound assignment operators (operators


abbreviated) to modify the values assigned to the variables, for example,var += 1,
orvar /= 5 * 2.

5. New values can be assigned to existing variables using the operator


assignment or a shorthand operator:

var = 2
print(var)

var = 3

print(var)

var += 1

print(var)

6. Text can be combined with variables using the operator+ and use the
functionprint()to show or print the results, for example:

var = "007"

print("Agent " + var)

Exercise 1

What is the result of the following code fragment?

var = 2
var = 3
print(var)
Review

Exercise 2

Which of the following variable names are illegal in Python?

my_var
m
101
averylongvariablename
m101
m 101
Del
delete
Review

my_var

m
101 # incorrect (starts with a digit)

averylongvariablename

m101

m 101 # incorrect (contains a space)

Del

del # incorrect (it is a keyword)

Exercise 3

What is the result of the following code fragment?

a = '1'
b = "1"
print(a + b)
Review

11

Exercise 4

What is the result of the following code fragment?

a = 6
b = 3
a is divided by 2 times b
print(a)
Review

1.0
2*b=6
a = 6 → 6 / 6 = 1.0

[Link] Comentarios

Add comments in the code: why, when and


where?
Perhaps at some point it will be necessary to put some words in the code directed not to
Python, but for the people who are reading the code in order to explain how it is
that works, or perhaps specify the meaning of the variables, also for documentation
Who is the author of the program and on what date was it written.
A text inserted into the program that is omitted during execution is called
a comment.

How are these types of comments placed in the source code? It has to be done with
a certain way for Python not to try to interpret it as part of the code.

When Python encounters a comment in the program, the comment is


completely transparent, from Python's point of view, the comment is just a
empty space, no matter how long it is.

In Python, a comment is a text that begins with the symbol# and extends until the
end of the line.

If you want to place a comment that spans multiple lines, you should place this symbol in
each line.

Just like the following code:

This program calculates the hypotenuse (c)

a and b are the lengths of the legs

a = 3.0

b = 4.0

c = (a ** 2 + b ** 2) ** 0.5 # use ** instead of the root


square

print("c =", c)

Good and responsible developers describe every important piece of code.


for example, explaining the role of a variable; although the best way to comment on a
variable is giving it a name that is not ambiguous.

For example, if a certain variable is designed to store the area of a


square, the namesquareAreait will be much better thanTijuana.

The first name given to the variable can be defined as self-commenting.

Comments can be useful in another aspect, they can be used to mark a


code fragment that is currently not needed, whatever the reason. Observe the
in the next example, if you uncomment the highlighted line, this will affect the output or result of
code:

This is a test program

x = 1
y = 2

y = y + x

print(x + y)

This is frequently done when testing a program, in order to isolate.


a fragment of code where an error may be found.

LABORATORY

Estimated Time
5 minutes

Level of Difficulty
Very Easy

Objectives
Familiarize yourself with the concept of comments in Python.
Use and do not use the comments.
Replace comments with code.
Experiment with Python code.
Scenario
The code in the editor contains comments. Try to improve it: add or remove comments.
where you deem appropriate (sometimes removing a comment makes it more
legible), also, change the names of the variables where you think this will improve the
understanding of the code.

NOTE

Comments are very important. They not only make the program easier to
to understand, but they also serve to disable those parts of code that are not
necessary (for example, when it is necessary to test a certain part of the code, and ignore the
The good programmers describe every important part of the code, and
significant names to variables, because sometimes it is much easier
leave the comment within the code itself.

It is good to use readable variable names, and sometimes it is better to divide the code into
parts with names (for example in functions). In some situations, it's a good idea
write the steps on how the calculations were done in a simple and clear way.

One more thing: it may happen that a comment contains a piece of incorrect information.
or wrong, that should never be done on purpose.
Key Points
1. Comments can be used to place additional information in the code. They are
omitted at the time of execution. This information is for readers who are
manipulating the code. In Python, a comment is a fragment of text that starts with
a# The comment extends to the end of the line.

2. If you want to add a comment that spans multiple lines, it is necessary to place a# to the
start of each line. Additionally, a comment can be used to mark a fragment of
code that is not necessary at the moment and is not desired to be executed. (note the last line of
code of the following fragment), for example:

This program prints

a greeting on screen

print("Hello!") # The print() function is called

I am Python.

3. When possible, the names of the variables should be self-commenting, for example,
if two variables are being used to store the height and length of something, the
namesheightylengthare a better choice thanmivar1y mivar2.

4. It is important to use comments to make programs easier to understand.


to understand, in addition to using readable and meaningful variables in the code. However, it is
It is equally important not to use confusing variable names, or to leave
comments that contain incorrect information.

5. Comments can be very helpful when you're reading your own code later.
for a while (it is common for developers to forget what their own code does), and
when others are reading your code (it can help them understand what it does
your programs and how they do it).
Exercise 1

What is the output of the following code fragment?

String #1
String #2
Review

Chain #2

Exercise 2

What will happen when the following code is executed?

This is
a comment
in several lines

print("Hello!")
Review

SyntaxError: invalid syntax

[Link] How to talk to a computer

The input() function


A new feature will now be introduced, which seems to be a reflection of the
functionprint().

Why? Well,print()send data to the console.

This new feature retrieves data from it.

print()it does not have a usable result. The importance of this new feature is
returns a very usable value.

The function is calledinput()The name of the function says it all.

The functioninput()is able to read data that was entered by the user and pass
those data to the running program.
The program can then manipulate the data, making the code
truly interactive.

All programs read and process data. A program that does not receive input data
the user's program is deaf.

Observe the example:

Tell me something...

something = input()

Mmm..., algo, ...really?

A very simple example of how to use the function is [Link]().

Note:

The program requests the user to insert some data from the console.
Surely using the keyboard, although it is also possible to input data
using voice or some image).
The functioninput()it is invoked without arguments (this is the simplest way to use
the function); the function will set the console to input mode; a cursor will appear
that blinks, and you will be able to enter data with the keyboard, when finished press the
Enter key; all entered data will be sent to the program through the
function result.
Note: the result must be assigned to a variable; this is crucial, if it is not done the
entered data will be lost.
Then the function is usedprint()to show the data that was obtained, with
some additional observations.

Try running the code and let the function show you what it can do.

The input() function with an argument


The functioninput()It can do something else: it can show a message to the user without help.
of the functionprint().

The example has been modified a bit, observe the code:

Tell me something...
print("Mmm...", algo, "...Really?")

Note:

La función input()when invoked with an argument, it contains a string with a


message.
The message will be displayed on the console before the user has a chance to
write something.
After thisinput()he will do his job.

This variant of the function invocationinput()simplify the code and make it clearer.

The result of the input() function


It has been said before, but it must be stated unambiguously once again: the result of the
functioninput()it's a string.

A string that contains all the characters that the user inputs from the keyboard. No
it's neither an integer nor a float.

This means that it should not be used as an argument for mathematical operations.
for example, these data cannot be used to square them, to divide them by
something or for something.

cualquierNumero = input("Inserta un número: ")

something = anyNumber ** 2.0

print(anyNumber, 'squared is', something)

The input() function - prohibited operations


Observe the code in the editor. Run it, enter any number, and press Enter.

What is happening?

Python should have given you the following output:

Traceback (most recent call last):

File '.[Link]', line 4, in <module>

result = something ** 2.0

TypeError: unsupported operand type(s) for ** or pow(): 'str' and


float
The last line explains it all, the operator was attempted to be applied.** astr(a string)
accompanied by afloat(floating point).

This is prohibited.

This should be obvious - Can you predict the value ofto be or not to beraised to
the2power?

We can't. Python can't either.

Have we reached a deadlock? Will there be a solution? Of course there is.

Data conversion or casting


Python offers two simple functions to specify a data type and solve this problem,
here are:int()yfloat().

Their names indicate what their function is:

The functionint()take an argument (for example, a string:int(string)) e


try to convert it to an integer value; if it fails, the whole program will fail
there is also a way to solve this, it will be explained later.
The functionfloat()take an argument (for example, a string:float(string))
and try to convert it to float (the rest is the same).

This is very simple and very effective. However, these functions can be invoked.
directly passing the result of the functioninput()directly. There is no need to
use variables as intermediate storage.

This idea has been implemented in the editor, see the code.

Can you imagine how the string entered by the user flows from the
functioninput()it was doing the functionprint()?

Try running the modified code. Don't forget to enter a valid number.

Test with different values, small, large, negative and positive. Zero is also
a good value to introduce.
More about the input() function and type conversion
Having a team composed ofinput()- int()- float()opens many new ones
possibilities.

Eventually you will be able to write complete programs that accept data in
form of numbers, which will be processed and the results will be displayed.

Of course, these programs will be very primitive and not very usable, due to the fact that they do not
they can make decisions, and consequently are not able to react accordingly to each
situation.

However, this is not a problem; it will be explained how to solve it soon.

The following example refers to the previous program that calculates the length of the
hypotenuse. Let's rewrite it so that it can read the lengths of the legs from the
console.

Check the editor window, this is how it looks now.

This program asks the user for the two legs, calculates the hypotenuse, and prints it.
result.

Run it again and try to enter negative values.

The program unfortunately does not respond correctly to this error.


Let's ignore this for now. We will come back to it soon.

Due to the functionprint()accept an expression as an argument, the can be removed


variable of the code.

As shown in the following code:

cateto_a = float(input("Inserta la longitud del primer cateto: "))

leg_b = float(input("Insert the length of the second leg "))

print("The length of the hypotenuse is: ", (leg_a**2 +


(cateto_b**2) ** .5)

String operators - introduction


It is time to return to these two arithmetic operators:+ y* .

Both have a secondary function. They are capable of doing something more.
addmultiply.

We have seen them in action when their arguments are (floating or integer).

Now we will see that they are also capable of handling or manipulating strings, although, in a
very specific way.

Concatenation
The sigo of+ (more), when applied to two strings, it becomes an operator of
concatenation

string + string

Simply concatenate (join) two strings into one. It can also be used more than
once in the same expression.

In contrast to the arithmetic operator, the concatenation operator is non-commutative,


for example,abit's not the same asbaab.

Don't forget, if you want the sign+ it is an uncombiner, not an adder, it should only be
ensure that both arguments are strings.
Data types cannot be mixed here.

This is a simple program that shows how the sign works.+ as a concatenator:

nom = input("¿Me puedes dar tu nombre por favor? ")

ape = input("¿Me puedes dar tu apellido por favor? ")

Thank you.

Your name is

Note: Using+ to concatenate strings allows you to build the output in a more
requires, compared to using only the functionprint()even when
enrich with the argumentsend=ysep=.

Run the code and check if the output matches your predictions.

Replication
The sign of* (asterisk), when applied to a string and a number (or to a number and
) becomes a replication operator.

string * number
number * string

Repeat the string the number of times indicated by the number.

For example:

James James Jamesgives usJamesJamesJames.


3 * "an"gives usananan.
5 * "2" (o"2" * 5) results in22222no10 ).

REMEMBER
A number less than or equal to zero produces an empty string.

This simple program "draws" a rectangle, using the operator(+ ), but in a


new role:

print("+" + 10 * "-" + "+")


print(("|" + " " * 10 + "| ") * 5, end="")
print("+" + 10 * "-" + "+")

Note how the parentheses have been used in the second line of code.

Try practicing to create other shapes or your own works of art!

Data type conversion: str()


By now you already know how to use the functionsint()yfloat()to convert a
string to a number.

This type of conversion is not one-way. A number can also be converted to


a string, which is easier and faster, this operation can always be performed.

A function capable of doing this is calledstr():

str(number)

Honestly, it can do much more than just transform numbers into strings, we will see that.
after.

The "right triangle" again


This is the program of the "right triangle" seen earlier:

cateto_a = float(input("Ingresa la longitud del primer cateto: "))

cateto_b = float(input("Ingresa la longitud del segundo cateto: "))

print("The length of the hypotenuse is: " + str((side_a**2 +


cateto_b**2) ** .5))

It has been modified a bit to show how the function [Link]()work. Thanks to this,
we can pass the entire result to the functionprint()as a single string, without
use commas.

You have taken some important steps on your journey to Python programming.

You already know the basic data types and a set of fundamental operators. You know
how to organize the output and how to obtain user data. These are very fundamental
solids for Module 3. But before moving on to the next module, let's do a few.
laboratories and let's summarize everything you have learned in this section.

[Link] LABORATORY: Simple Inputs and Outputs


LABORATORY

Estimated Time
5-10 minutes

Nivel de Dificultad
Easy

Objectives
Familiarize yourself with data input and output in Python.
Evaluate simple expressions.
Scenario
The task is to complete the code to evaluate and display the result of four operations.
basic arithmetic.

The result must be displayed in the console.


Perhaps you won't be able to protect the code of a user trying to divide by zero. For now, no
one must worry about it.

Test your code - Does it produce the expected results?

LABORATORY

Estimated time
20 minutes

Level of difficulty
Intermediate

Objectives
Familiarize yourself with the concepts of numbers, operators, and arithmetic expressions in
Python.
Understand the precedence and associativity of Python operators, as well as the
correct use of parentheses.
Scenario
The task is to complete the code to evaluate the following expression:
The result must be assigned toy Be cautious, observe the operators and prioritize them.
Use as many parentheses as needed.

You can use additional variables to simplify the expression (however, it is not very
necessary). Test your code carefully.

Test Data
Sample entry:1

Salida esperada: y = 0.6000000000000001

Sample entry:10

Expected output:y = 0.09901951266867294

Sample entry:100

Expected output:y = 0.009999000199950014

Sample entry:-5

Expected output:y = -0.19258202567760344


LABORATORY

Estimated time
15-20 minutes

Level of difficulty
Easy

Objectives
Improve the ability to implement numbers, operators, and arithmetic operations
in Python.
Use the functionprint()and its formatting capabilities.
Learning to express everyday phenomena in terms of a language of
programming.
Scenario
The task is to prepare a simple code to evaluate or find the final time of a period.
of given time, expressed in hours and minutes. The hours go from 0 to 23 and the minutes from 0
59. The result must be displayed in the console.

For example, if the event starts at 12:17 and lasts 59 minutes, it will end at 13:16.

Don't worry if your code isn't perfect, it's okay if it accepts an invalid hour, the most
It is important that the code produces a correct output according to the given input.

Test the code carefully. Hint: use the operator% it can be key to success.

Test Data
Sample entry:12 17 59

Expected output:13:16
Sample entry:23 58 642

Expected output:10:40

Sample entry:0 1 2939

Expected output:1:0

Key Points

1. The functionprint()send data to the console, while the functioninput()obtains


console data.

2. The functioninput()comes with an initial parameter: a string type message for the
user. Allows you to write a message before the user's entry, for example:

name = input("Enter your name: ")

print("Hello, " + name + ". Nice to meet you!")


3. When the functioninput()is called or invoked, the program flow is halted, the
The cursor symbol remains blinking (it is indicating to the user to take action now).
that the console is in input mode) until the user has entered data and/or
you have pressed the Enter key.

NOTE

You can test the full functionality of the [Link]()locally on your machine.
For optimization reasons, the maximum number of executions in Edube has been limited to
only a few seconds only. Go to Sandbox, copy and paste the code that is above,
run the program and wait a few seconds. Your program should stop after a few
seconds. Now open IDLE, and run the same program there - Can you notice any
difference?

Tip: The aforementioned feature of the functioninput()it may be


used to ask the user to finish or end the program. Observe the following
code:

nombre = input("Ingresa tu nombre: ")

print("Hello, " + name + ". Nice to meet you!")

Press the Enter key to end the program.

input()

FIN.

3. The result of the functioninput()It is a string. Strings can be joined with each other.
through the concatenation operator(+ ). Observe the following code:

num1 = input("Ingresa el primer número: ") # Ingresa 12

num2 = input("Ingresa el segundo número: ") # Ingresa 21

print(num1 + num2) # the program returns 1221

They can also be multiplied (* - replication) chains, for example:

miEntrada = ("Ingresa Algo: ") # Ejemplo: hola

print(miEntrada * 3) # Expected output: holaholahola

Exercise 1
What is the output of the following code?

x = int(input("Enter a number: ")) # the user enters a 2


print(x * "5")
Review

55

Exercise 2

What is the expected output of the following code?

x = input("Enter a number: ") # the user enters a 2


print(type(x))
Review

<class 'str'>

Congratulations! You have completed Module 2

Well done! You have reached the end of Module 2 and have completed an important step in your
Python programming education. Here is a brief summary of the objectives you have.
covered and with which you have become familiar in Module 2:

The basic methods of formatting and outputting data provided by Python, along with the
main types of data and numerical operators, their mutual relationships and links.
The concept of variables and the correct way to name them.
The assignment operator, the rules governing the construction of expressions.
Data entry and conversion.

Now you are ready to take the module quiz and attempt the final challenge: The Test.
from Module 2, which will help you assess what you have learned so far.
[Link] Fundamentals of Programming in Python: Module 3

You might also like