138k views
1 vote
the given program reads a list of single-word first names and ages (ending with -1), and outputs that list with the age incremented. the program fails and throws an exception if the second input on a line is a string rather than an integer. at fixme in the code, add try and except blocks to catch the valueerror exception and output 0 for the age. ex: if the input is: lee 18 lua 21 mary beth 19 stu 33 -1 then the output is: lee 19 lua 22 mary 0 stu 34

User Linton
by
8.5k points

2 Answers

2 votes

Final answer:

To handle an exception in the given program where the second input on a line is a string instead of an integer, we need to add try and except blocks to catch the ValueError exception and output 0 for the age.

Step-by-step explanation:

The given program reads a list of single-word first names and ages, and outputs that list with the age incremented. To handle the scenario where the second input on a line is a string instead of an integer, we need to add try and except blocks to catch the ValueError exception and output 0 for the age.

Here is an example of how to modify the code:

while True:
try:
name, age = input().split()
age = int(age) + 1
print(name, age)
except ValueError:
print(name, 0)

if age == -1:
break

This modified code will catch any ValueError exceptions and print the name with 0 age when it occurs.

User StKiller
by
8.3k points
4 votes

Here's an example Python code that addresses the issue by adding try and except blocks to catch the ValueError exception.

def main():

input_data = input().split()

while input_data[0] != '-1':

try:

name = input_data[0]

age = int(input_data[1]) + 1

except ValueError:

age = 0

print(f'{name} {age}')

input_data = input().split()

if __name__ == "__main__":

main()

User Sonic Soul
by
8.0k points