164k views
2 votes
Three variables , x, y and z, supposedly hold strings of digits, suitable for converting to integers. Write code that converts these to integers and print the sum of these three integers. However, if any variable has a value that cannot be converted to an integer, print out, the string "bad value(s) in: " followed by the names of the variables that have bad values (separated by spaces, in alphabetically ascending order).

For example, if the values of x, y and z were respectively "3", "9", "2" then the number 14 would be printed; but if the values were "abc", "15", "boo" then the output would be:
bad value(s) in: x z
This is what I have so far:
try:
print(int(x)+int(y)+int(z))
except ValueError:
if x=ValueError:
print("bad value(s) in:", x)
elif y=ValueError:
print("bad value(s) in:", y)
elif z=ValueError:
print("bad value(s) in:", z)

User GabrielBB
by
3.4k points

2 Answers

5 votes

Answer:

See explaination for the program code

Step-by-step explanation:

Code below:

x, y, z = "abc", "15", "boo"

errors = []

try:

x = int(x)

except ValueError:

errors.append('x')

try:

y = int(y)

except ValueError:

errors.append('y')

try:

z = int(z)

except ValueError:

errors.append('z')

if len(errors) == 0:

print(x+y+z)

else:

print('bad value(s) in: ' + ' '.join(errors))

User Xgretsch
by
3.5k points
1 vote

Answer:

Check the explanation

Step-by-step explanation:

x, y, z = "abc", "15", "boo"

errors = []

try:

x = int(x)

except ValueError:

errors.append('x')

try:

y = int(y)

except ValueError:

errors.append('y')

try:

z = int(z)

except ValueError:

errors.append('z')

if len(errors) == 0:

print(x+y+z)

else:

print('bad value(s) in: ' + ' '.join(errors))

User Madlan
by
3.3k points