[Python] How can I put multiple statements in one line?

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I know a little bit of comprehensions in Python, but they seem very hard to 'read'. The way I see it, a comprehension might accomplish the same as the following code:

    for i in range(10): if i == 9: print('i equals 9')


    This code is much easier to read than how comprehensions currently work, but I've noticed you can’t have two :s in one line. This brings me to:

    Is there a way I can get the following example into one line?

    try:
    if sam[0] != 'harry':
    print('hello', sam)
    except:
    pass


    Something like this would be great:

    try: if sam[0] != 'harry': print('hellp', sam)
    except:pass


    But again I encounter the conflicting :s.

    I'd also love to know if there's a way to run try (or something like it) without except. It seems entirely pointless that I need to put except:pass in there. It’s a wasted line.

    Continue reading...

Compartilhe esta Página