[Python] Python detect string and int using exception handling

Discussão em 'Python' iniciado por Stack, Janeiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to work on detecting strings and int using exception handling and cannot figure it out. Please help!

    Using the inputs

    • Lee 18
    • Lua 21
    • Mary Beth 19
    • Stu 33
    • -1

    parts = input().split()
    name = parts[0]

    while name != '-1':

    # FIXME: The following line will throw ValueError exception.
    # Insert try/except blocks to catch the exception.
    try:
    age = int(parts[1]) + 1
    print('{} {}'.format(name, age))
    parts = input().split()
    name = parts[0]
    if age != 0:
    raise ValueError(0)
    except ValueError as excpt:
    name = parts[0]
    age = excpt


    The result of the code above is:

    • Lee 19
    • Lua 22

    When I am trying to get the code to result with:

    • Lee 19
    • Lua 22
    • Mary 0
    • Stu 34

    Please assist!

    Continue reading...

Compartilhe esta Página