Seite 1 von 1

different inputs

Verfasst: Freitag 8. Oktober 2021, 16:05
von Kasper
while True:
_group = input("")
if type(_group)==int:
print("number")
breake
elif type(_group)==str:
print("word")
breake
elif type(_group)==bool:
print("value")
breake
else:
continue

_________________________________________________________________
doesn't work :(

Re: different inputs

Verfasst: Freitag 8. Oktober 2021, 17:06
von __deets__
input always yields a string. If you want to auto-detect the type, you’ll need to write a converter that e.g. tries to invoke int on your string, catch the exception, and attempt something else.

Re: different inputs

Verfasst: Samstag 9. Oktober 2021, 08:11
von ThomasL
It doesn´t work because you wrote "break" with an e at the end.
It would work if the indentation is correct which we can´t see as you didn´t use the editor function </> to insert code.

Code: Alles auswählen

while True:
    _group = input("")
    if type(_group) == int:
        print("number")
        break
    elif type(_group) == str:
        print("word")
        break
    elif type(_group) == bool:
        print("value")
        break
    else:
        continue
If your code looks like above it works but will always output "word" as input() always yields a string.

Re: different inputs

Verfasst: Samstag 9. Oktober 2021, 14:04
von __blackjack__
@Kasper: Further comments: One leading underscore in local names usually means that this name gets assigned some value that isn't used. But `_group` *is* used, so that's a bit confusing.

The empty string is the default value for `input()`\s `prompt` argument. And the ``else`` with ``continue`` doesn't have an effect because that is what happens anyway.

As __deets__ already mentioned `input()` returns strings. But if you actually would need to test for a value's type, the `isinstance()` function would be preferable as it also recocnizes subtypes. Then the order of the tests have to be different as `bool` is a subtype of `int`:

Code: Alles auswählen

In [32]: isinstance(True, bool)                                                 
Out[32]: True

In [33]: isinstance(True, int)                                                  
Out[33]: True

In [34]: isinstance(0, bool)                                                    
Out[34]: False

In [35]: isinstance(0, int)                                                     
Out[35]: True
So the code would look like this:

Code: Alles auswählen

    while True:
        group = input()

        if isinstance(group, bool):
            print("value")
            break
        
        if isinstance(group, int):
            print("number")
            break
        
        if isinstance(group, str):
            print("word")
            break
Now theres three times almost the same code for each type. This can be replaced by a loop over the differences:

Code: Alles auswählen

#!/usr/bin/env python3


def main():
    while True:
        group = input()
        for type_, text in [(bool, "value"), (int, "number"), (str, "word")]:
            if isinstance(group, type_):
                print(text)
                return


if __name__ == "__main__":
    main()
The loop(s) are left with ``return`` now, because ``break`` would just leave the inner loop.

This leaves us with the problem that `group` is a string. Always. So let's forget about the code with the ``while`` loop, because if `group` is not a string describing a boolean value or a number, it is a ”word”:

Code: Alles auswählen

#!/usr/bin/env python3


def main():
    group = input()
    if group in ["True", "False"]:
        print("value")
    elif group.isdigit():
        print("number")
    else:
        print("word")


if __name__ == "__main__":
    main()

Re: different inputs

Verfasst: Samstag 9. Oktober 2021, 17:24
von Dennis89
Hello,
__blackjack__ hat geschrieben: Samstag 9. Oktober 2021, 14:04 @Kasper: Further comments: One leading underscore in local names usually means that this name gets assigned some value that isn't used.
can you tell me please a example when to use one leading underscore?
Why do I need a name when I dosen't use them?

Thank you.
Dennis

Re: different inputs

Verfasst: Samstag 9. Oktober 2021, 18:06
von rogerb
I'm sure __blackjack__ has a good comment on that as well, but since I had my hands already on the keyboard:

Code: Alles auswählen

presidents = [
    "Joe Biden",
    "Donald Trump",
    "Barack Obama",
    "George Bush",
]

for president in presidents:
    _first, lastname = president.split(" ")
    print(lastname)
It becomes obvious to the reader, that "president" is split into two parts. However only the "lastname" is needed in the following code section.
"_first" is only used as a container when unpacking parts of the "president" string.

A bit more ugly and less readable approach would be this:

Code: Alles auswählen

for president in presidents:
    lastname = president.split(" ")[-1]
    print(lastname)
So, it's about readability.

Also, some code checkers will issue a warning, that a value is assigned to "first" without ever accessing it. However, with the leading underscore, this warning is silenced.

Re: different inputs

Verfasst: Samstag 9. Oktober 2021, 20:23
von Dennis89
Hello rogerb,

thank you for your explanation.
I think if I had to write your example, my code would be ugly. So it's good to know to use the underscope.

Greetings
Dennis

Re: different inputs

Verfasst: Samstag 9. Oktober 2021, 22:34
von __blackjack__
Another example are arguments of functions or methods that need to be there, for instance because the base class method expects them or because they are used as callbacks and get called with some argument(s). For instance `bind()` callbacks from `tkinter` pass in an event object but often that isn't used. A typical signature of such a callback method would be:

Code: Alles auswählen

    def on_mouse_click(self, _event=None):

Re: different inputs

Verfasst: Samstag 9. Oktober 2021, 23:46
von Dennis89
Thank you for your explanation, __blackjack__.

Greetings
Dennis