What’s wrong with the logic of this Python code?

Asked

Viewed 151 times

1

x = bool(input("True or False...? "))
if x == 'True':
    print("Você escollheu True")
else:
    print("Você escolheu False")

What’s wrong with this logic, more specifically about logic involving the boolean variable?

1 answer

4


There are two problems in logic. First the function bool() cannot transform the string at a boolean value like hold, so the correct comparison is with string, but without the function. Second if the person does not type True, there’s no way of knowing if she typed False without specifically testing for it.

x = input("True ou False...? ")
if x == 'True':
    print("Você escolheu True")
else:
    print("Você não escolheu True")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Or

x = input("True ou False...? ")
if x == 'True':
    print("Você escolheu True")
elif x == 'False':
    print("Você escolheu False")
else:
    print("Você não escolheu True ou False")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Or you can still accept typing ignoring uppercase:

x = input("True ou False...? ").lower()
if x == 'true':
    print("Você escolheu True")
elif x == 'false':
    print("Você escolheu False")
else:
    print("Você não escolheu True ou False")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If you still want the job bool() has to understand that a string false is when it is empty:

x = bool(input("Digite alguma coisa ou deixe em branco...? "))
if x: #não precisa usar True porque é isto que o if espera
    print("Você digitou algo")
else:
    print("Você não digitou algo")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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