38.2k views
0 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

User Jjczopek
by
3.6k points

1 Answer

4 votes

Answer:

x = str("abc")

y = str("15")

z = str("boo")

try:

total = int(x) + int(y) + int(z)

print(total)

except ValueError:

print("bad value(s) in:",end=' ')

if not x.isdigit():

print(' x',end=' ')

if not y.isdigit():

print(' y',end=' ')

if not z.isdigit():

print(' z',)

Step-by-step explanation:

  • Inside the try-catch block for exception handling, add the x, y and z variable to calculate the total of these three.
  • Use an if statement to check whether x is a digit or not and display the string "bad value(s) in:"
  • Use an if statement to check whether the y is a digit or not and display the string "bad value(s) in:"
  • Use an if statement to check whether the z is a digit or not and display the string "bad value(s) in:"
User SuryaKantSharma
by
3.7k points