26.8k views
4 votes
Python

Two variables, x and y, supposedly hold strings of digits. Write code that converts these to integers and assigns a variable z the sum of these two integers. Make sure that if either x or y has bad data (that is, not a string of digits), z will be assigned the value of -1.

User PauliL
by
7.4k points

1 Answer

2 votes

Answer:
# Assuming x and y are already assigned

try:

# Convert x and y to integers

x = int(x)

y = int(y)

# Calculate the sum

z = x + y

except ValueError:

# Handle the case where x or y is not a valid integer

z = -1

print("The sum is:", z) # Output

Step-by-step explanation:
With comments

User RbtLong
by
7.1k points