Python Tutorial_ Conditional Statements
Python Tutorial_ Conditional Statements
Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact
Conditional Statements
A decision has to be taken when the script or program comes to a point where it has a choice of actions, i.e. different computations, to choose from.
The Origins of
Python Search this website:
The decision depends in most cases on the value of variables or arithmetic expressions. These expressions are evaluated to the Boolean values True or False. The
Starting with statements for the decision taking are called conditional statements. Alternatively they are also known as conditional expressions or conditional constructs.
Python: The Go
Interactive Shell So this chapter deals with conditionals. But to code them in Python, we have to know how to combine statements into a block. It also seems to be an ideal moment
Executing a to introduce the Python block principle in combination with conditional statements. This topic in German
Script / Deutsche
Übersetzung:
Indentation Blocks and Indentations
bedingte
Data Types and
Anweisungen
Variables The concept of block building is also known in natural languages, as we can deduce from the following text:
Operators
If it rains tomorrow, I will tidy up the cellar. After this I will paint the walls. If there is some time left, I will do my tax declaration. Python 3
Sequential Data
Types: Lists and As we all know, there will be no time left to deal with the tax declaration. Joking apart, we can see a sequence of actions in the previous text, which have to be performed This is a tutorial in
Strings in a chronological order. If you have a closer look at the text, you will notice that it is ambiguous: Is the action of painting the walls also linked to the event of rain? Python3, but this
List Especially, doing the tax declaration, does it depend on the rain as well? What will this person do, if it doesn't rain? We extend the text by creating further ambiguities: chapter of our course
Manipulations is available in a
If it rains tomorrow, I will tidy up the cellar. After this I will paint the walls. If there is some time left, I will do my tax declaration. Otherwise, I will go swimming. In
Shallow and version for Python
the evening, I will go to the cinema with my wife!
Deep Copy 2.x as well:
Dictionaries Conditional
Can his wife hope to be invited to the cinema? Does she have to pray or hope for rain? To disambiguate the text we can phrase it in a way, which is closer to
Statements in Python
Sets and Frozen programming code and Python code and hopefully, a happy ending for his wife:
2.x
Sets
If it rains tomorrow, I will do the following:
An Extensive - tidy up the cellar Classroom
Example Using - paint the walls
Training
Sets - If there is some time left, I will
- do my tax declaration Courses
input via the
Otherwise, I will do the following:
keyboard - go swimming The goal of this
Conditional go to the cinema with my wife in the evening website is to provide
Statements educational material,
Loops, while Such a work flow is often formulated in the programming environment as a so-called flow chart or programming flowchart: allowing you to learn
Loop Python on your own.
For Loops Nevertheless, it is
Difference faster and more
efficient to attend a
between
"real" Python course
interators und
in a classroom, with
Iterables an experienced
Output with Print trainer. So why not
Formatted output attend one of the live
with string Python courses in
modulo and the Strasbourg, Paris,
format method Luxembourg,
Amsterdam, Zürich /
Functions
Zurich, Vienna /
Recursion and
Wien, London, Berlin,
Recursive Munich, Hamburg,
Functions Frankfurt, or Lake
Parameter Constance by Bernd
Passing in Klein, the author of
Functions this tutorial?
Namespaces
Global and Local
Variables Onsite Training
Decorators Courses
Memoization with
Let us come to your
Decorators
company or institute
Read and Write
and train your
Files employees, as we've
Modular done it many times in
Programming Amsterdam (The
and Modules Netherlands), Berlin
Packages in (Germany), Bern
Python (Switzerland), Basel
Regular (Switzerland), Zurich
(Switzerland),
Expressions
Locarno
Regular
(Switzerland), Den
Expressions, Haag (The Hague),
Advanced Hamburg (Germany),
Lambda Frankfurt (Germany),
Operator, Filter, Toronto (Canada),
Reduce and Map Edmonton (Canada),
List Munich (Germany),
Vienna / Wien
Comprehension
(Austria) and many
Iterators and
other cities. We do
Generators training courses in
Exception England, Switzerland,
Handling Liechtenstein,
Tests, DocTests, Austria, Germany,
UnitTests France, Belgium, the
Object Oriented Netherlands,
Programming Luxembourg, Poland,
UK, Italy and other
Class and
locations in Europe
Instance
and in Canada.
Attributes
Properties vs. This way you will get
getters and a perfect training up
setters to your needs and it
Inheritance will be extremely cost
Multiple efficient as well.
Contact us so we can
Inheritance
define and find the
Magic Methods
best course
and Operator curriculum to meet
Overloading your needs, and
OOP, Inheritance schedule course
Example sessions to be held at
Slots your location.
Classes and
Class Creation
Road to Blocks are used in programming to enable groups of statements to be seen or treated as if they were one statement. A block consists of one or more statements. A program can be seen as a block, which consists of Skilled Python
Metaclasses statements and other nested blocks. There have been different approaches in programming languages to syntactically describe blocks: ALGOL 60 and Pascal, for example, use "begin" and "end", while C and similar Programmers
languages use curly braces "{" and "}". Bash has yet another design by using do ... done and if ... fi or case ... esac constructs.
Metaclasses
Metaclass Use You are looking for
There is a big disadvantage for all of these approaches: The code may be all right for the interpreter or the compiler of the language, but it can be written in a way, which is badly structured for humans. We want to experienced Python
Case: Count illustrate this in the following "pseudo" C-Code snippet: developers or
Function Calls
programmers? We
Abstract Classes if (raining_tomorrow) {
can help you, please
tidy_up_the_cellar();
paint_the_walls(); contact us.
if (time_left)
"The truth is that we do_taxes(); Quote of the
can learn to condition } else Day:
our minds, bodies, enjoy_swimming();
go_cinema();
and emotions to link "To err is human, but
pain or pleasure to to really foul things
Let us include some blanks in front of the go_cinema call:
whatever we choose. up you need a
By changing what we if (raining_tomorrow) { computer." (Paul R.
link pain and tidy_up_the_cellar(); Ehrlich)
pleasure to, we will paint_the_walls();
instantly change our if (time_left)
behaviors." do_taxes();
Anthony Robbins, } else
enjoy_swimming();
self-help author and
go_cinema();
success coach Data Protection
The execution of the program will not change: They will go to the cinema whether it rains or not! The way the code is written misleadingly connotes the meaning that they will only go to cinema, if it does not rain. Declaration
"I think that we're This example demonstrates the possible ambiguity in interpreting C-Code by humans. This means, that people write code, which will lead to a program which will not "behave" in the intended way.
now inescapably in There is even another danger lurking in this example. What if the programmer has forgotten to include the last two statements into braces? Should the code be like this: Data Protection
an age where the
Declaration
large statements of if (raining_tomorrow) {
mathematics are so tidy_up_the_cellar();
complex that we may paint_the_walls();
never know for sure if (time_left)
do_taxes();
whether they're true
} else {
or false." enjoy_swimming();
Keith Devlin, British go_cinema();
mathematician }
"Truth does not need Now, they will only go to cinema, if it is not a rainy day, which makes sense, if it is an open air cinema. The following code is the correct code, if they want to go to the cinema regardless of the weather:
argument,
agreement, theories if (raining_tomorrow) {
or beliefs. There is tidy_up_the_cellar();
only one test for it paint_the_walls();
if (time_left)
and that is to ask
do_taxes();
yourself 'Is the } else {
statement true or enjoy_swimming();
false in my }
experience?" Barry go_cinema();}
Long, Australian
author and teacher The problem in C is that the way we indent code has no meaning for the compiler and it might suggest the wrong interpretation for humans, if they try to understand the code.
This is different in Python. Blocks are created with indentations. We could say "What you see is what you get!"
The example above may look in a Python program like this:
This website is
supported by: if raining_tomorrow:
tidy_up_the_cellar()
paint_the_walls()
Linux and Python if time_left:
Training Courses and do_taxes()
else:
Seminars
enjoy_swimming()
go_cinema()
We also like to thank
Denise Mitchinson for There is no ambiguity in the Python version. The couples visit to the cinema is bound to occur, regardless of the weather. Moving the go_cinema() call to the same indentation level as the enjoy_swimming(),
providing the style changes a lot. In this case there will be no cinema, if it rains.
sheet of this website.
We have just seen that it is useful to use indentation in C or C++ programs to increase or ensure the legibility of a program for the programmer but not for the C compiler. The Compiler relies solely on the
structuring determined by the braces. Code in Python can only and has to be structured by using the correct indentation. This means that Python forces the programmer to use the indentation that he or she is
supposed to use anyway to write nice code. So, Python does not allow to obfuscate the structure of a program by using bogus or misleading indentations.
A block of code in Python has to be indented by the same amount of blanks or tabs. We will further deepen this in the next subsection on the conditional statements in Python.
As we have already stated, the if-statements are used to change the flow of control in a Python program. This makes it possible to decide at run-time whether or not to run one block of code or another.
if condition:
statement
statement
# ... some more indented statements if necessary
The indented block of code is executed only if the condition "condition" is evaluated to True, meaning that it is logically true.
The following program code asks the user about his or her nationality. The indented print statement will only be executed, if the nationality is "French". If the user of this program uses another nationality, nothing
will be printed:
Please note that if somebody types in "French", nothing will be printed either, because we solely check the lower case spelling. We can change this by extending the condition with an "or":
Your Italian colleague may protest that Italian speakers will not be taken into consideration by our previous little program. We can change this by adding another if:
This small python script has a disadvantage: Let's assume that someone inputs "french" as a nationality. In this case, the print below the first "if" will be executed, i.e. the text "Préférez-vous parler français?" will be
printed. After this the program will check, if the value for person is equal to "italian" and "Italian", which cannot be the case, as we assumed "french" is the input. This means that our program performs an
unnecessary test, if the input is "french" or "French".
This problem can be solved with an "elif''condition. The expression is only checked after "elif", if the expression in the previous "elif'' or "if" was "false''.
Like in our previous example, if statements have in many cases "elif" and "else" branches as well. To be precise: There can be more than one "elif" branch, but only one "else" branch. The else branch has to be at
the end of the if statement, i.e. it can't be followed by other elif branches.
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
...
elif another_condition:
another_statement_block
else:
else_block
If the condition "condition_1" is True, the statements of the block statement_block_1 will be executed. If not, condition_2 will be evaluated. If condition_2 evaluates to True, statement_block_2 will be executed, if
condition_2 is False, the other conditions of the following elif conditions will be checked, and finally if none of them has been evaluated to True, the indented block below the else keyword will be executed.
It's a generally accepted belief, to assume that one year in the life of a dog corresponds to seven years in the life of a human being. But apparently there are other more subtle methods to calculate this haunting
problem, haunting at least for some dog owners.
Another subtler - and some think a preciser method - works like this:
A one year old dog roughly corresponds to a fourteen year old child
A dog who is two years old corresponds to a 22 year old human
Every further dog year corresponds to five human years
###
input('press Return>')
There is one drawback to the script. I works only for integers, i.e. full years.
True or False
Unfortunately it is not as easy in real life as it is in Python to differentiate between true and false:
The following objects are evaluated by Python as False:
The ternary if
C programmers usually know the following abbreviated notation for the if construct:
max = (a > b) ? a : b;
if (a > b)
max=a;
else
max=b;
The Python version is by far more readable. The expression above, can be read as "max shall be a if a is greater than b else b".
But the ternary if statement is more than an abbreviation. It is an expression, which can be used within another expression:
Using if statements within programs can easily lead to complex decision trees, i.e. every if statements can be seen like the branches of a tree.
We will read in three float numbers in the following program and will print out the largest value:
There are other ways to write the conditions like the following one:
if x > y:
if x > z:
maximum = x
else:
maximum = z
else:
if y > z:
maximum = y
else:
maximum = z
Another way - which is less efficient, because we have to create a tuple or list to compare the numbers - to do it, can be seen in the following example. We are using the built-in function max, which calculates the
maximum of a list or a tuple:
maximum = max((x,y,z))
If we want to read in an arbitrary number of elements, which we do not want or need to save in a list, we can calculate the maximum in the following way:
Footnotes:
1LOOP is a programming language without conditionals, but this language is purely pedagogical. It has been designed by the German computer scientist Uwe Schöning. The only operations which are supported by
LOOP are assignments, additions and loopings. But LOOP is of no practical interest and besides this it is only a proper subset of the computable functions.
© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein