Python Programming Basics: Data & Functions
Python Programming Basics: Data & Functions
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.
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.
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!")
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.
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.
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.
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.
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.
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).
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.
What is happening?
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).
Run the code. The console should now look like this:
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("
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:
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.
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.
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.
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.
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.
Now that you understand the functionprint(), are you ready to consider learning how
store and process data in Python.
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]().
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:
print(" * *")
* *
**
*** ***
print(" * *")
print(" * *")
*****
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.
123
Can you guess what value it represents? Of course you can - one hundred twenty-three.
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.
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.
If all went well, you should now see two identical lines.
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:
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.
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.
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.
.4
4.
This will not change its type or its value.
4
4.0
One might think they are identical, but Python sees them in a completely different way.
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 .
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:
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.
For example, let's suppose that the following notation has been chosen:
0.0000000000000000000001
print(0.0000000000000000000001)
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.
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:
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.
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.
Do you know how to do it? Click on Review to see if you are right:
Review
I'm Monty Python.
o
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.
''
""
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.
There will never be an answer like: I don't know, probably yes, but I'm not sure.
True
False
They cannot be changed; these symbols must be taken as they are, even respecting the uppercase letters.
lowercase.
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.
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
{"Hola":"Hello","007":"007"}
Review
Exercise 2
The first is a string, the second is numeric (float), the third is numeric (integer) and the fourth
it is boolean.
Exercise 3
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.
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.
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.
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.
Note: In the examples, the double asterisks are surrounded by spaces, it is not mandatory.
do it, but make the code more readable.
Run the code and carefully observe the results it produces. Can you observe
something?
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.)
The value after the diagonal is the dividend, the value before the diagonal is the divisor.
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.
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.
print(6 // 3)
print(6 // 3.)
print(6. // 3)
print(6. // 3.)
print(6 // 4)
print(6. // 4)
Imagine that it was used/ instead of// Could you predict the outcomes?
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.
-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.
Its graphical representation in Python is the symbol of% (percentage), which can be a
a little confused.
In other words, it is the value that remains after dividing one value by another to produce a
integer result.
Observe the code snippet - try to predict the result and then execute it:
print(14 % 4)
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.
print(12 % 4.5)
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.
print(-4 + 4)
print(-4. + 8)
The result should not surprise you. Run the code and check the results.
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)
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?
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
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.
Most Python operators have left-to-right binding, which means that the
The evaluation of the expression is carried out from left to right.
print(9 % 6 % 2)
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.
The result must be1 The operator has a leftward linkage. But there is an exception.
interesting.
print(2 ** 2 ** 3)
2 ** 2 → 4 ; 4 ** 3 → 64
2 raised to the power of 3→ 8 ; 256→ 256
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.
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
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.
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.
4. A unary operator is an operator with only one operand, for example,-1 , o+3 .
7. The sub-expressions within parentheses are always calculated first, for example,15-
1*(5*(1+2))=0.
Exercise 1
16 8.0 8
Exercise 2
Exercise 3
-2 2 512
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.
A name.
A value (the content of the container).
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.
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:
In addition, Python allows the use of not only Latin letters but also specific characters from other languages.
that use other alphabets.
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.
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.
var = 1
print(var)
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
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.
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"
Review
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.
var = 1
print(var)
var = var + 1
print(var)
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.
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
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.
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)
√(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.
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
i = i + 2 * j⇒ i += 2 * j
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.
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.
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.
Expected Result
7.38 miles is 11.88 kilometers
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.
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"
Exercise 1
var = 2
var = 3
print(var)
Review
Exercise 2
my_var
m
101
averylongvariablename
m101
m 101
Del
delete
Review
my_var
m
101 # incorrect (starts with a digit)
averylongvariablename
m101
Del
Exercise 3
a = '1'
b = "1"
print(a + b)
Review
11
Exercise 4
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
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.
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.
a = 3.0
b = 4.0
print("c =", c)
x = 1
y = 2
y = y + x
print(x + y)
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:
a greeting on screen
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.
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
String #1
String #2
Review
Chain #2
Exercise 2
This is
a comment
in several lines
print("Hello!")
Review
print()it does not have a usable result. The importance of this new feature is
returns a very usable value.
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.
Tell me something...
something = input()
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.
Tell me something...
print("Mmm...", algo, "...Really?")
Note:
This variant of the function invocationinput()simplify the code and make it clearer.
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.
What is happening?
This is prohibited.
This should be obvious - Can you predict the value ofto be or not to beraised to
the2power?
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.
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.
This program asks the user for the two legs, calculates the hypotenuse, and prints it.
result.
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.
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:
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
For example:
REMEMBER
A number less than or equal to zero produces an empty string.
Note how the parentheses have been used in the second line of code.
str(number)
Honestly, it can do much more than just transform numbers into strings, we will see that.
after.
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.
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.
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
Sample entry:10
Sample entry:100
Sample entry:-5
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
Expected output:1:0
Key Points
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:
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?
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:
Exercise 1
What is the output of the following code?
55
Exercise 2
<class 'str'>
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