GNU/Linux Programmer's Solver - Conditionals in Python

Guess program in Python. Conditionals, if, switch and constants
PROGRAMMING GUESS Python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
n = 42

v = int(input("Guess the number? "))

if v < 0:
    print("Only positive numbers")
    exit(1)

if v == n:
    print("Good job!")
else:
    print(f"Keep trying\nThe number is {'HIGHER' if (n > v) else 'LOWER'}"
    )

    # On fail provide a hint
    h = abs(v - n)
    print("HINT  :", end='')  # Don't print CR
    if h < 5:
        print("TOO HOT!!!")
    elif h < 10:
        print("HOT")
    elif h < 15:
        print("WARM")
    else:
        print("COLD")

Python offers the if-else construction for condition checking as most other languages, however, Python groups statements, indenting all of them at the same level, instead of using special characters like curly brackets {}. So, to add instructions to a conditional block, we only need to indent them under the block start, which is indicated by the colon : character. This is how Python indicates what follows as a block of statements.

I’M A BEGINNER

Python, al igual que Perl, no requiere que declaremos nuestra variable por adelantado como C o C++ (si bien esto lo podemos hacer y es una buena práctica) y tampoco requiere el uso de caracteres especiales como Perl.

Python, like Perl, offers a special way to add a condition to the else block. In that case, we use elif (short for “else-if”), which allows us to add a new condition.

The following sequence of instructions

if h < 5    : print ("TOO HOT")
elif h < 10 : print ("HOT")
else        : print ("COLD")

It would be read as:

  • If h is less than 5, print TOO HOT
  • Otherwise (if h is greater than or equal to 5), if h is less than 10 print HOT
  • Otherwise (if h is greater than or equal to 10) print COLD

The parentheses around the conditions are not necessary, but they can be used to make the code easier to read, being only necessary in cases where we have to compose complex conditions. Thus, the expression that checks if we have guessed the number can be written as:

if v == n : print ("Good job!)

In the case where the conditional block only contains one instruction, this can be added after the character :. As happens in the line:

if (v == n) : print ("Bien Hecho!")

DID YOU KNOW…

In reality, we can add as many instructions as we want in a one-line if statement, we just need to separate them with the character ;


if (v < 0): print ("Solo números positivos"); exit(1);

Any else or elif block that follows, must be on a separate line. It is possible to write an if-else condition in a single line using the ternary operator. Python does not have a ternary operator like C or Perl, however it offers an alternative syntax that can be a little confusing if one is used to the C style ternary operator ?:. This syntax can be seen in the line where we indicate if the number is greater or smaller and is something like this:

    INSTRUCTION-THEN if (condition) else INSTRUCTION-ELSE`
        "HIGHER"         if (n > v)     else "LOWER"

Alternatively, the following constructor can be used:

   (condition and INSTRUCTION-THEN  or INSTRUCTION-ELSE
   (n > n     and       "HIGHER"    or      "LOWER")

In this case we are abusing the logical operators and and or to achieve a result similar to the ternary operator, although, we must be careful with the INSTRUCTION-THEN and INSTRUCTION-ELSE parts since if INSTRUCTION-THEN returns a value, 0, False or None the expression will not work as expected. This construction is based on the evaluation sequence of a logical expression. To understand it better, let’s rewrite it as follows:

((condition) AND True) OR value

Python will start evaluating the first expression, our condition, which becomes the first parameter for the following and operation. A logical and is only true if both operands are true:

A AND B = TRUE <===> A = TRUE and B = TRUE

If A is true, then let’s enter that we evaluate the next operand, to know if the expression is true, which must return a True value, or otherwise the else part will also be executed. Since the first part of the expression is true, and the logical or operation is true if only one of its operands is true… then we don’t have to execute INSTRUCTION-ELSE.

On the contrary, if condition is false, the first and operator will return false regardless of the value of INSTRUCTION-THEN, which is not necessary to execute. But, the OR expression that follows, can still be fulfilled depending on the result of INSTRUCTION-ELSE… so it is necessary to execute that last instruction.

As you can see, this trick, let’s call it that, needs INSTRUCTION-THEN to be an expression (something that returns a value), we cannot use statements like print if we use Python2… but the print function of Python3 will work perfectly.

I’M A NEWBIE

Like Perl, Python is able to infer the type, but unlike this one, once the type is assigned to a variable that type is fixed. For that reason we need to use int at the beginning of the program, to convert the string of characters that returns input into a number. Otherwise the conditions below would fail since we would be comparing strings and numbers.

Python, like Perl, does not offer a switch statement, however it is possible to simulate this instruction using different techniques such as dictionaries, iterators, or classes.

Similarly, Python does not allow defining constants. Instead, Python programmers have as a convention to consider constant values as variables whose names are in uppercase, which is a common practice in many languages.

Summary

  • Supports if ... [elif] ... [else] ...
  • Supports reduced form Command if (cond);
  • Supports ternary operator value_True if (condition) else Value_False
  • Python does not support booleans as a native type but as a subclass of integers
  • Does not support switch
  • Does not support constants natively. The convention is to use uppercase names

Related Posts

GNU/Linux Programmer's Solver - Introduction

Programming exercises in 18 Programming Languages

Read

linuxprogramming

GNU/Linux Programmer's Solver - Hello World in Python

Hello World program in Python. Basic structure, comments and string literals

Read

PROGRAMMING PYTHON HELLO WORLD

GNU/Linux Programmer's Solver
Chapter 2 - Conditionals

Conditionals are the may way to add logic to your programs.

Read

PROGRAMMING HELLO WORLD

Return to Home Page