07-02 Exceptions

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

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

sum=0 badvalues=" " try: [Tab Key]sum += int(x) except ValueError: [Tab Key]badvalues += " x" try: [Tab Key]sum += int(y) except ValueError: [Tab Key]badvalues += " y" try: [Tab Key]sum += int(z) except ValueError: [Tab Key]badvalues += " z" if badvalues==" ": [Tab Key]print(sum) else: [Tab Key]print("bad value(s) in:"+badvalues)

Two variables, num_boys and num_girls, hold the number of boys and girls that have registered for an elementary school. The variable budget holds the number of dollars that have been allocated to the school for the school year. Write code that prints out the per-student budget (dollar spent per student). If a division by zero error takes place, just print out the word "unavailable".

try: [Tab Key]print(budget / (num_boys + num_girls)) except ZeroDivisionError: [Tab Key]print("unavailable")

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

try: [Tab Key]z = int(x) + int(y) except ValueError: [Tab Key]z = -1


Set pelajaran terkait

Ch.2 financial statements, taxes, and cash

View Set

Chapter 8: Race and Ethnicity as Lived Experience

View Set

ACCT 2020 Chapter 15 and 16 Quiz Questions

View Set

Business Data Networks & Security Ch: 4-6

View Set

ba 市場營銷管理8 電子市場營銷策略

View Set