Put only True and False in if and while

Asked

Viewed 2,192 times

-1

I wonder what that’s for:

if true:
  #Código

or

if false:
  #Código

or

while true:
  #código

etc..

  • Start by doing the [tour] then, there teaches the basics of how the site works. You can access the [help] also to go deeper.

3 answers

7

I’m going to assume that you capitalized, because either it’s lowercase or it’s not working, or you’re using variables called true or false, which are names a little bad for variables.

Strictly the former serve for nothing. The former will enter the block of the if Every time, the second one never comes in, so you don’t have to wear that. It can be used momentarily for a test, but would probably have a comment along with the actual condition.

Some people use the False to make an excerpt not run momentarily, this is not usually a good idea and can be solved with comment in the codes, this is called comment out. In essence the first two should not be used in real code.

The third can be more useful depending on the code that is inside. You enter a loop anyway and inside you will have a if that will make it come out. This is useful to keep the code longer DRY. If you have a condition in the middle of the code block that exits the loop and that would be the same condition as the while, then it would have an unwanted repeat because it would have twice the same code that needs to be synchronized every time, violating DRY and making maintenance more complicated and risky, so one prefers to only have the condition in the middle and the loop becomes "infinite" (not that it is in fact).

If you do not have this exit in the middle of the block, that is, you should only leave in condition at the beginning of it, or if the conditions of the loop and internal are different there is no reason to do this. How Python doesn’t have one do...while one can use a while True to simulate the do, there a if at the end of the block makes the output, making the check always be at the end of the block and not at the beginning, as is in the while normal.

In other locations, and major functions may be another reason to use true or false I can’t talk without a context.

Has a example in question I answered which demonstrates this type of use:

def entrada(lista):
    while True:
        ad = (int(input('Digite um valor: ')))
        if ad not in lista:
            lista.append(ad)
            print('Adicionado com sucesso!')
        else:
            print('Valor duplicado. Adição negada.')
        while True:
            ask = str(input('Deseja continuar?[S/N] ')).strip().upper()[0]
            if ask == 'S':
                break
            elif ask == 'N':
                return
lista = []
entrada(lista)
print(lista)

I put in the Github for future reference.

6

First, Python differentiates between upper and lower case letters, so true is different from True. In Python, there are values True and False, but there is no true and false; in their examples would give error indicating undefined names.

Let us suppose, then, that it is True and False.

if True:
    print('Executei')

It has no function. The conditional structure serves to execute a particular block of code only when the condition is met; if the condition is always true, the block will always be executed and therefore it makes no sense to have the condition.

Thus, the equivalent code without the conditional structure would be:

print('Executei')
if False:
    print('Executei')

It has no function. Unlike the above situation, when the condition is always false, the code block will never be run; if it is never run, why keep it in the file? Any structure similar to this can be removed from the source file without side effects.

while True:
    print('Executei')

This may be useful, depending on the context. The while defines a repeat loop structure that executes the code block while the condition is met. In this particular case, the condition always is satisfied, therefore it is what we call the infinite loop. Your program will run infinitely, unless it is stopped via external stimulus or when the expression break is executed within the loop.

An example of this is to ask the program user for an integer value between 0 and 10; as long as they do not provide a valid value, submit a message and request again. As we do not know how many attempts this will require, we make an infinite loop:

while True:
    try:
        nota = int(input("Informe a nota entre 0 e 10: "))
        if not 0 <= nota <= 10:
            raise ValueError("Nota fora da faixa permitida")
    except ValueError as e:
        print("Valor inválido:", e)
    else:
        break

print(nota)

Vide Accept only numerics in input.

-2

Not a very useful function. Unless you have a program with a very specific application, like a program that will run a while without stopping and will die only with your intervention, not with a user’s own.

Maaaaas, in my view, is not a very pythonic way of working either. In the case of "if" is even worse, it is not necessary to create a conditional structure if the condition will always be true or false, just code sequentially.

As stated earlier by colleagues, perhaps in a test context it is valid but otherwise I do not see much application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.