Python Course - 3.1 Section 1 - Decision Making in Python
Python Course - 3.1 Section 1 - Decision Making in Python
A computer runs the program and provides the answers. The program must be capable
react according to the responses received.
You will never get an answer like 'Let me think... I don't know, or probably yes, but I don't know.'
with security.
To ask questions, Python uses a very special set of operators. Let's review.
one after another, illustrating their effects in some simple examples.
It is a binary operator with left linking. It requires two arguments and verifies if
they are the same.
3.1.3 Exercises
Now we are going to ask some questions. Try to guess the answers.
2 == 2
Respuesta: True - of course, 2 is equal to 2. Python will respondTrue(remember this pair of literals)
predefined,TrueyFalseThey are also Python keywords.
2 == 2.
Answer:This question is not as easy as the first one. Fortunately, Python can convert the value
whole in its real equivalent and, consequently, the answer isTrue.
1 == 2
3.1.4 Operators
Equality: The equal operator (==)
The operator == (equal to) compares the values of two operands. If they are equal, the result of the
The comparison is True. If they are not equal, the result of the comparison is False.
Observe the equality comparison below - What is the result of this operation?
var == 0
Keep in mind that we cannot find the answer if we do not know what value is stored.
currently in the variable var.
If the variable has been changed many times during the execution of the program, or if its input is
initial value from the console, Python can only answer this question at runtime
program execution.
Now imagine a programmer who suffers from insomnia, and has to count the black sheep and
whites separately as long as there are exactly twice as many black sheep as whites
whites.
The question will be the following:
Due to the low priority of the operator ==, the question will be treated as follows:
black_sheep == (2 * white_sheep)
So, we are going to practice understanding the operator.== Can you guess the output of the code at
continuation?
The operator != (not equal to) also compares the values of two operands. Here is the
difference: if they are equal, the result of the comparison is False. If they are not equal, the result of
the comparison is True.
Now take a look at the inequality comparison below - can you guess the
result of this operation?
If you want to know if there are more black sheep than white ones, you can write it like this:
Both operators (strict and non-strict), as well as the other two that are analyzed in the following
section, binary sonoperators with left linking, and precedence is greater than
the one shown by == and !=
If we want to know whether we need to wear a hat or not, we ask ourselves the following question:
There are at least two possibilities: first, you can memorize it (store it in a variable) and
use it later. How do you do that? Well, you would use an arbitrary variable like this:
The content of the variable will tell you the answer to the question.
La segunda posibilidad es más conveniente y mucho más común: puedes utilizar la respuesta que
obtengas paratomar una decisión sobre el futuro del programa.
You need a special instruction for this purpose, and we will discuss it very soon.
Now we need to update our priority table, and add all the new operators in
she. Now it looks like the following:
Scenario
Using one of the comparison operators in Python, write a simple two-line program.
that takes the parameter n as input, which is an integer, and prints False if n is less than 100,
True if n is greater than or equal to 100.
You should not create any if blocks (we will talk about them very soon). Test your code using the
data that we provide to you.
Test Data
3.1.7 Conditions and conditional execution
You already know how to ask questions to Python, but you still don't know how to make reasonable use of the
responses. There should be a mechanism that allows you to do something if a condition is met, and
do not do it if it is not fulfilled.
It's like in real life: you do certain things or not when a specific condition is met, for
for example, you go for a walk if the weather is nice, or you stay home if it is damp and cold.
To make such decisions, Python offers a special statement. Due to its nature and its
application, is referred to as conditional instruction (or conditional statement).
There are several variants of it. We will start with the simplest, increasing the difficulty.
slowly.
The first form of a conditional sentence, which you can see below, is written in
very informal but figurative way
if true_or_not:
do_this_if_true
This conditional sentence consists of the following elements, strictly necessary in this
order:
The reserved keyword if;
One or more blank spaces;
An expression (a question or an answer) whose value is interpreted only in
terms of True (when its value is not zero) and False (when it is equal to zero);
Two colons followed by a new line;
An instruction with indentation or a set of instructions (is absolutely required to
except one instruction); the blood can be achieved in two ways: inserting a number
specific spaces (the recommendation is to use four spaces for indentation), or using
the tabulator; note: if there is more than one instruction in the part with indentation, the indentation must be
the same in all lines; although it may seem the same if tabs are mixed with
spaces, it is important that all the bloodlines are exactly the same Python 3 no
permite mezclar espacios y tabuladorespara la sangría.
If the expression true_or_not represents truth (that is, its value is not equal to zero), the
Indented statements will be executed;
If the expression true_or_notno represents the truth (that is, its value is equal to zero), the
sentences with indentation will be omitted (ignored), and the next instruction executed will be the
next to the level of the original indent.
As you can see, having lunch is a conditional activity and does not depend on the weather.
Knowing what conditions influence our behavior and assuming that we have the
functions without parameters go_for_a_walk() and have_lunch(), we can write the following fragment
of code:
if the_weather_is_good:
go for a walk()
have lunch()
If a certain Python developer falls asleep when counting 120 sheep without sleeping, and
The sleep induction procedure can be implemented as a special function.
The function sleep_and_dream() has the following code structure:
We have said that conditional statements must have indentation. This creates a structure.
very readable, clearly demonstrating all possible execution paths in the code.
As you can see, making the bed, taking a shower, and sleeping and dreaming are
executed unconditionally - when sheep_counter reaches the desired limit.
Feeding the dogs, however, is always done (that is, the function feed_the_sheepdogs() does not
It is indented and does not belong to the if block, which means it always executes.
Now we will discuss another variant of the conditional sentence, which also allows for a
additional action when the condition is not met.
Note: there is no word about what will happen if the weather is bad. We only know that we will not go out.
outdoors, but we don't know what we could do. It is possible that we also want to plan.
something in case of bad weather.
We can say, for example: If the weather is good, we will go for a walk; otherwise, we will go to the...
cinema.
Now we know what we would do if the conditions are met, and we know what we would not do.
Everything goes as we want. In other words, we have a 'Plan B'.
Python allows us to express these alternative plans. This is done with a second form,
slightly more complex, than the conditional statement, the if-else statement:
if true_or_false_condition:
perform_if_condition_true
else:
perform_if_condition_false
Therefore, there is a new word: else - this is a reserved keyword.
The part of the code that starts with else specifies what to do if the specified condition is not met.
by the if (note the two dots after the word).
If the condition evaluates as True (its value is not equal to zero), the
the perform_if_condition_true instruction is executed, and the conditional statement comes to an end;
Si la condición se evalúa comoFalse(es igual a cero), la
The perform_if_condition_false instruction is executed, and the conditional statement comes to an end.
By using this form of conditional statement, we can describe our plans as follows
way
if the_weather_is_good:
go for a walk
else:
go_to_a_theater()
have_lunch()
If the weather is good, we will go for a walk. Otherwise, we will go to the movies. It doesn't matter if the weather is
good or bad, we will have lunch afterwards (after the walk or after going to the movies).
Everything we have said about indentation works the same way within the else branch:
First, consider the case where the instruction placed after the if is another if.
Read what we have planned for this Sunday. If the weather is good, we will go for a walk. If
We found a good restaurant, we will have lunch there. Otherwise, we will eat a sandwich.
If the weather is bad, we will go to the cinema. If there are no tickets, we will go shopping at the mall.
close
Let's write the same in Python. Carefully consider the following code:
This use of the if statement is known as nesting; remember that each else refers to
If they are at the same level of indentation; this needs to be known to determine
how are ifs and elses related;
Consider how the blood improves readability and makes the code easier to.
understand and track.
elif is used to check more than one condition, and to stop when the first one is found.
true statement.
Our next example resembles nesting, but the similarities are very slight. Again,
we will change our plans and express them as follows: if the weather is good,
We will go for a walk, otherwise, if we get tickets, we will go to the cinema, otherwise, if there is
free tables at the restaurant, let's have lunch; if everything fails, we will return home and play
chess.
Have you noticed how many times we have used the words otherwise? This is the stage in which the
the reserved keyword elif serves its purpose.
This may sound a bit confusing, but I hope that some simple examples help to
understand it better.
All the programs solve the same problem - they find the largest number in a series of
numbers and print them.
Example 1:
We will start with the simplest case - how to identify the larger of the two numbers?:
The above code fragment should be clear - it reads two integer values, compares them, and finds out which one is the
bigger.
Example 2:
Now we are going to show you an intriguing fact. Python has an interesting feature - look at the
code below:
Note: if any of the if-elif-else branches contains a single statement, you can code it as
more complete (it is not necessary for a line with indentation to appear after the keyword)
but just continue the line after the colon.
However, this style can be misleading, and we are not going to use it in our future programs.
but it is definitely worth knowing if you want to read and understand someone else's programs.
It's time to complicate the code - let's find the largest of the three numbers. Will the code expand?
A little.
We assume that the first value is the largest. Then we verify this hypothesis with the two
remaining values.
We check if the second number is larger than the current highest number
and updates the largest number if necessary.
if number2 > largest_number:
largest_number = number2
We check if the third number is larger than the current largest number.
and update the largest number if necessary.
if number3 > largest_number:
largest_number = number3
This method is significantly simpler than trying to find the largest number by comparing all the
possible pairs of numbers (that is, the first with the second, the second with the third, and the third with the first).
Try to reconstruct the portmanteau code.
But what happens if we ask you to write a program that finds the largest of two hundred
numbers? Can you imagine the code?
You will need two hundred variables. If two hundred variables are not complicated enough,
try to imagine the search for the largest number of a million.
Imagine a code that contains 199 conditional statements and two hundred invocations of the
input() function. Luckily, you don't need to deal with that. There is a simpler approach.
For now we will ignore the requirements of Python syntax and try to analyze the problem without
think about real programming. In other words, we will try to write the algorithm, and when
estemos contentos con él, lo implementaremos.
In this case, we will use a type of notation that is not a real programming language (it does not
it can neither compile nor execute), but it is formalized, concise, and readable. It
call pseudocode.
First of all, we can simplify the program if we assign it to the beginning of the code.
variable largest_number a value that will be smaller than any of the entered numbers.
We will use -999999999 for that purpose.
Secondly, we assume that our algorithm will not know in advance how many numbers there are.
they will deliver to the program. We hope that the user enters all the numbers they wish - the
The algorithm will work well with one hundred and with one thousand numbers. How do we do that?
We make a deal with the user: when the value -1 is entered, it will be a signal that there are no more.
data and that the program must finish its work.
Otherwise, if the entered value is not equal to -1, the program will read another number, and so on.
successively.
The trick is based on the assumption that any part of the code can be executed more than once.
precisely, as many times as necessary.
The execution of a certain part of the code more than once is called a loop. The meaning
this term is probably obvious to you.
Lines 02 to 08 form a loop. We will pass through them as many times as necessary to
check all the values entered.
Can you use a similar structure in a program written in Python? Yes, you can.
Additional Information
Python often comes with many built-in functions that will do the work for you. For example,
to find the largest number of all, you can use a built-in function in Python
max() call. You can use it with multiple arguments. Analyze the code below:
Three numbers are read.
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 =int(input("Ingresa el tercer número: "))
Similarly, you can use the min() function to return the smallest number. You can
reconstruct the previous code and experiment with it in Sandbox.
We will talk about these (and many other) functions soon. For now, our focus is
will focus on conditional execution and loops to help you gain more confidence in the
programming and teaching you the skills that will allow you to understand and apply the two concepts
in your code. So, for now, we are not taking shortcuts.
Scenario
Peace lilymore commonly known as the Moses cradle or peace lily, is one of
the most popular indoor plants that filter harmful toxins from the air. Some of the
toxins it neutralizes include benzene, formaldehyde, and ammonia.
Imagine that your computer program loves these plants. Every time it receives an input in
the shape of the word Espatifilo, I involuntarily shouted the following string to the console: "Espatifilo is
the best plant of all!
Write a program that uses the concept of conditional execution, takes a string as
entry and that:
Print the statement 'If - ¡The Peace Lily! is the best plant of all time!' on the screen if the
entered string is "SPATHIPHYLLUM" (uppercase)
No, I want a big Spathiphyllum!
print "Spathiphyllum!, No [input]!" otherwise. Note: [input] is the string taken as
entry.
Test your code with the data we provided. And get yourself a Peace Lily too!
Scenario
Érase una vez una tierra de leche y miel - habitada por gente feliz y próspera. La gente pagaba
taxes, of course - their happiness had limits. The most important tax,
the Personal Income Tax (IPI, for short) had to be paid once a year and
it was evaluated using the following rule:
If the citizen's income was not higher than 85,528 pesos, the tax was equal to 18% of the income.
less 556 pesos and 2 cents (this was the tax exemption).
if the income was above this amount, the tax was equal to 14,839 pesos and 2 cents, plus the
32% of the surplus over 85,528 pesos.
Note: this happy country never gives money back to its citizens. If the calculated tax is less than
zero only means that there is no tax (the tax is equal to zero). Keep this in mind during
your calculations.
Observe the code in the editor - it only reads one input value and generates a result, so you must
complete it with some smart calculations.
tax = round(tax, 0)