this post was submitted on 13 Sep 2023
4 points (61.1% liked)

Asklemmy

42489 readers
2517 users here now

A loosely moderated place to ask open-ended questions

Search asklemmy 🔍

If your post meets the following criteria, it's welcome here!

  1. Open-ended question
  2. Not offensive: at this point, we do not have the bandwidth to moderate overtly political discussions. Assume best intent and be excellent to each other.
  3. Not regarding using or support for Lemmy: context, see the list of support communities and tools for finding communities below
  4. Not ad nauseam inducing: please make sure it is a question that would be new to most members
  5. An actual topic of discussion

Looking for support?

Looking for a community?

~Icon~ ~by~ ~@Double_[email protected]~

founded 5 years ago
MODERATORS
 

to my knowledge, if you input any text it will return true and if you input nothing it will return false. if it's possible without if statements, how do i check if they inputted 'True' or 'False (/ '1' or '0') when im doing 'bool(input("Input True or False ")'.

all 19 comments
sorted by: hot top controversial new old
[–] [email protected] 14 points 9 months ago

input("Input True or False") == "True"

Will work but this strikes me as a likely example of an XY problem. What are you actually trying to achieve?

[–] [email protected] 5 points 9 months ago

If you're asking homework questions online you should really step up your game. ChatGPT is how all the cool kids are cheating on their homework and that doesn't require waiting on replies.

This stackoverflow answer has a whole bunch of approaches you can try.

bool doesn't work because it uses the standard truth testing algorithm in Python:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a bool() method that returns False or a len() method that returns zero, when called with the object. 1 Here are most of the built-in objects considered false:

constants defined to be false: None and False

zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

empty sequences and collections: '', (), [], {}, set(), range(0)

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

In other words, bool(string) checks if your string has a length of 0 or is any of the other falsy types, and everything else is True.

[–] [email protected] 5 points 9 months ago

Text input by a user is almost always a string, because the user presses 0 or more keys on their keyboard before hitting enter.

Without validation, we have no way to know that the user typed - did they type “1” or “True”, or did they embrace chaos and type in “Batman”? Unless we check, we can’t be sure.

We can assume, but then we have to accept that our program will have what we call “undefined behaviour” if our assumption is incorrect - which is definitely not good. In the best case scenario, your code harmlessly crashes. In the worst case scenario, your code is being used by the Pentagon for some reason and just started global thermonuclear war, which ideally should be avoided.

There are ways around this. For example, we could listen for individual keystrokes and only accept the inputs if they meet our criteria - if the user presses the 1 key, that’s true, if they press 0, that’s false, any other key is ignored, for example.

But the best thing to do, in my humble opinion, is to accept a string input and then check what the user entered. In most cases, “True” or “False” aren’t usually what we want, unless you’re writing some sort of true or false guessing game or something. Most cases where we want a Boolean input from a user, it’s a yes/no kind of thing. “Would you like to continue?” or “Shall we start global thermonuclear war? y/N”

So you’re better off just embracing the string, and using that to determine behaviour, rather than a Boolean directly. For example, something along the lines of :

if user input is “y” then launch nukes
else if user input is “n” send fruit basket
else print “input invalid”`

As others mentioned in the thread, it may be wise to convert the input to lowercase - just in case the user enters Y or y. Personally I wouldn’t go so far as to take the first letter as the answer, in case the user enters “you must be joking!” for example :-)

[–] [email protected] 3 points 9 months ago

Why can't you use if statements?

[–] [email protected] 2 points 9 months ago* (last edited 9 months ago) (1 children)

Without if statements?

Apologies typing on my phone

def input_checker(input_str):

input_str = input_str.lower()

validation_dict = {“true”: “they input true”,
                               “false”: “they input false”}

return validation_dict.get(input_str, “They input something else”)

You are comparing the content of strings, not their truth value. A string is true if it’s not empty and false if it is. The string “True” is no closer to the bool True than the string “Oranges” is.

What you are looking for is input validation. Check the content of what they wrote and respond accordingly.

[–] [email protected] 0 points 9 months ago (4 children)

why is my input being seen as a string in the firsr place if i typecasted the variable as a boolean? how do i make the input itself a bool (rather than the variable?)

[–] [email protected] 5 points 9 months ago* (last edited 9 months ago) (1 children)

User inputs are strings, which can be anything. You are hoping they input True or false but what if they input tRUe or FALSE77 or Hunter4 or jgidqopqncb uriwnsvsveyqiaoNcbtjwnak? bool(“tRUe”) doesn’t evaluate to True or False in the way you think it does.

If you want to convert user input to a bool use a lookup dict with some validation rules (like lower casing input text) to sanitize the input. I cannot emphasize this enough - never trust user input.

[–] [email protected] 1 points 9 months ago

Always trust user input'); DROP TABLE users;

[–] [email protected] 3 points 9 months ago* (last edited 9 months ago)

Worth remembering that python uses the concepts of truthy and falsey. Empty string ("") is falsey. Any other string ("true", "false", "0", etc.) Is truthy. All bool(str) does is evaluate whether str is truthy or falsey. It does not evaluate what str actually is.

So bool(input("Input True or False ") will return False is the user input is empty and True otherwise.

[–] [email protected] -4 points 9 months ago (2 children)

You can use eval(input). It converts string to whatever the actual content is.

[–] [email protected] 5 points 9 months ago

Which is really bad if the user inputs executable code. Never call eval on unsanitized text

[–] [email protected] -2 points 9 months ago (1 children)

wait so eval(bool(input('Input:')

[–] [email protected] 4 points 9 months ago

Yeah, don’t do that. Users could accidentally or maliciously type something that would get executed as python code and break your program

[–] [email protected] 1 points 9 months ago

Just use 'strtobool' from distutils to parse str as bool much better than reinventing the wheel https://docs.python.org/3.11/distutils/apiref.html#distutils.util.strtobool

edit: ok it uses if internally so without if you could do it with match statement

[–] [email protected] -1 points 9 months ago (2 children)

I'm a little rusty, but can't you do it with a '?'

something like,

var ? print("true") : print("false")

[–] [email protected] 3 points 9 months ago (1 children)

I think you're thinking of JavaScript, not Python. The closest thing Python has to a ternary operator is foo if condition else bar.

[–] [email protected] 3 points 9 months ago

You might be right actually.

[–] [email protected] 2 points 9 months ago

I have to imagine the ternary operator would still count as an if statement in spirit