different inputs

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Kasper
User
Beiträge: 1
Registriert: Freitag 8. Oktober 2021, 15:35

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 :(
__deets__
User
Beiträge: 14545
Registriert: Mittwoch 14. Oktober 2015, 14:29

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.
Benutzeravatar
ThomasL
User
Beiträge: 1367
Registriert: Montag 14. Mai 2018, 14:44
Wohnort: Kreis Unna NRW

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.
Ich bin Pazifist und greife niemanden an, auch nicht mit Worten.
Für alle meine Code Beispiele gilt: "There is always a better way."
https://projecteuler.net/profile/Brotherluii.png
Benutzeravatar
__blackjack__
User
Beiträge: 13122
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

@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()
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
Benutzeravatar
Dennis89
User
Beiträge: 1158
Registriert: Freitag 11. Dezember 2020, 15:13

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
"When I got the music, I got a place to go" [Rancid, 1993]
rogerb
User
Beiträge: 878
Registriert: Dienstag 26. November 2019, 23:24

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.
Benutzeravatar
Dennis89
User
Beiträge: 1158
Registriert: Freitag 11. Dezember 2020, 15:13

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
"When I got the music, I got a place to go" [Rancid, 1993]
Benutzeravatar
__blackjack__
User
Beiträge: 13122
Registriert: Samstag 2. Juni 2018, 10:21
Wohnort: 127.0.0.1
Kontaktdaten:

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):
„All religions are the same: religion is basically guilt, with different holidays.” — Cathy Ladman
Benutzeravatar
Dennis89
User
Beiträge: 1158
Registriert: Freitag 11. Dezember 2020, 15:13

Thank you for your explanation, __blackjack__.

Greetings
Dennis
"When I got the music, I got a place to go" [Rancid, 1993]
Antworten