0% found this document useful (0 votes)
20 views19 pages

Python Course - 3.1 Section 1 - Decision Making in Python

Module 3 introduces decision-making in Python through conditional statements and comparison operators. It explains how to use operators like ==, !=, >, <, >=, and <= for making comparisons, as well as how to implement conditional execution with if, if-else, and elif statements. The module also includes exercises and examples to illustrate the concepts of conditional logic and variable assignment in programming.
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)
20 views19 pages

Python Course - 3.1 Section 1 - Decision Making in Python

Module 3 introduces decision-making in Python through conditional statements and comparison operators. It explains how to use operators like ==, !=, >, <, >=, and <= for making comparisons, as well as how to implement conditional execution with if, if-else, and elif statements. The module also includes exercises and examples to illustrate the concepts of conditional logic and variable assignment in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

3.

1 Section 1 - Decision Making


in Python
Welcome to Module 3! In the first section, we will learn about conditional statements and how to use them to
making decisions in Python.

3.1.1 Questions and Answers


A programmer writes a program and the program asks questions.

A computer runs the program and provides the answers. The program must be capable
react according to the responses received.

Fortunately, computers only know two types of responses:

Yes, it's true.


No, this is false.

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.

3.1.2 Comparison: equality operator


Question: Are the two values equal?

To ask this question, the == (equal equal) operator is used.

Don't forget this important distinction:

= is an assignment operator, for example, a = b assigns the value of b to the variable a;


Is this a question? Are these values equal? So a == b compares a and b.

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.

Question #1: What is the result of the following comparison?

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.

Question #2: What is the result of the following comparison?

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.

Question #3: What is the result of the following comparison?

1 == 2

Answer:This should be easy. The answer will be (or rather, is always)False.

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:

black_sheep is equal to 2 times white_sheep

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?

Inequality: the operator is not equal to (!=)

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?

Run the code and check if you were right.

Comparison operators: greater than


You can also ask a comparison question using the > (greater than) operator.

If you want to know if there are more black sheep than white ones, you can write it like this:

black_sheep > white_sheep # Greater than

Truehe/she confirms it;Falsehe/she denies it.


Comparison operators: greater than or equal to
The greater than operator has another special variant, a non-strict variant, but it is denoted by
a different way than classical arithmetic notation: >= (greater than or equal to).

There are two subsequent signs, not one.

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:

centigrade_outside >=0.0# Greater than or equal to

Comparison operators: less than or equal to


As you have probably guessed, the operators used in this case are: The
operator < (less than) and its non-strict brother: <= (less than or equal to).

Observe this simple example:

current_velocity_mph < 85 # Less than


current_velocity_mph <= 85 # Less than or equal to
We are going to check if there is a risk of being fined by the law (the first question is strict, the second
no).

3.1.5 Making use of the responses


What can you do with the answer (that is, the result of a comparison operation) that
is obtained from the computer?

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:

answer = number_of_lions >= number_of_lionesses

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:

3.1.6LABVariables ‒ Questions and


Answers

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.

How does this sentence work?

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.

In real life, we often express a desire:

if the weather is good, we will go for a walk

then, we will have lunch

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

Conditional execution: the if statement

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:

if sheep_counter >= 120:# Evaluate a conditional expression


sleep_and_dream() # Execute if the conditional expression is true
You can read it as follows: if sheep_counter is greater than or equal to 120, then sleep and dream (it is
say, execute the function sleep_and_dream).

We have said that conditional statements must have indentation. This creates a structure.
very readable, clearly demonstrating all possible execution paths in the code.

Analyze the following code:

if sheep_counter >= 120:


make a bed()
take a shower()
sleep_and_dream()
feed the sheepdogs()

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.

Conditional execution: the if-else statement


We start with a simple sentence that said: If the weather is good, we will go for a walk.

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

The execution of if-else is the following:

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.

The if-else statement: more about conditional execution

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:

if the weather is good:


go for a walk
have_fun()
else:
go to a theater()
enjoy_the_movie()
have_lunch()

Nested if-else statements


Now, let's analyze two special cases of the conditional sentence.

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:

Here are two important points:

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.

The elif statement


The second special case presents another new Python keyword: elif. As you probably
suspicions, it's a shorter way of saying else if.

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.

Let's write the same scenario using Python:


The way to assemble the following if-elif-else statements is sometimes called a cascade.

Observe again how indentation improves the readability of the code.

Additional attention should be paid to this case:

You should not use else without a preceding if;


else is always the last branch of the cascade, regardless of whether you have used elif or not;
else is an optional part of the cascade, and can be omitted;
If there is an else branch in the cascade, only one of all the branches is executed;
If there is no else branch, it is possible that none of the available options will be executed.

This may sound a bit confusing, but I hope that some simple examples help to
understand it better.

3.1.8 Code sample analysis


Now we will show you some simple but complete programs. We will not explain them in detail,
because we consider that comments (and variable names) within the code are
sufficient guides.

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.

There are no other differences in the code.


Example 3:

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.

Observe the following code:

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

We temporarily assume that the first number


it is the biggest.
We will verify it soon.
largest_number = number1

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

Print the result.


print("The largest number is:", largest_number)

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.

3.1.9 Pseudocode and introduction to the


loops
Now you should be able to write a program that finds the largest of four, five, six, or even
ten numbers.
You already know the scheme, so enlarging the size of the problem will not be particularly
complex.

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.

Let's look at our pseudocode below:


largest_number = -999999999
number = int(input())
if number == -1:
print(largest_number)
exit()
if number > largest_number:
largest_number = number
Go to line 02

What is happening to him?

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

Check which of the numbers is the largest


and assign it to the variable largest_number.

largest_number =max(number1, number2, number3)

Print the result.


print("The largest number is:", largest_number)

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.

3.1.10 LAB Comparison Operators and


conditional execution

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!

3.1.11LABFundamentals of the sentence


if-else

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.

Your task is to write a tax calculator.

It must accept a floating point value: the income.


Next, you must print the calculated tax, rounded to total pesos. There is a
function called round() that will do the rounding for you - you will find it in the skeleton code
from the editor.

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.

Test your code with the data we have provided.

income = float(input("Introduce el ingreso anual: "))

if income < 85528:


tax = income * 0.18 - 556.02

Write your code here.

tax = round(tax, 0)

print("The tax is:", tax, "pesos")

You might also like