'Python detect string and int using exception handling
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!
Solution 1:[1]
I figured this one out messing with it for a while solution code
# Split input into 2 parts: name and age
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 == 'Beth':
            age = 0
            
    except ValueError as excpt:
        age = 0
        print('{} {}'.format(name, age))
        parts = input().split()
        name = parts[0]
Solution 2:[2]
try:
    age = int(parts[1]) + 1
    print('{} {}'.format(name, age))
    parts = input().split()
    name = parts[0]
        
except ValueError as excpt:
    age = 0
    print('{} {}'.format(name, age))
    parts = input().split()
    name = parts[0]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Lawrence Valdivia | 
| Solution 2 | Tomy | 
