def try_div(x):
if x:
return 5 / x
# else: return None
print(try_div(5))
print(try_div(0)) # функция вернет None
1.0 None
a = 5
result = try_div(a)
if result is not None:
print(result)
1.0
def my_function_1(x):
import math
result = try_div(x)
if result is not None:
return result * math.pi
print(my_function_1(5))
print(my_function_1(0))
3.141592653589793 None
def my_function_2(x):
result = my_function_1(x)
if result is not None:
return result ** 3
print(my_function_2(5))
print(my_function_2(0))
31.006276680299816 None
def try_div_raise(x):
if x:
return 5 / x
else:
# генерируем исключение:
raise ZeroDivisionError
def my_function_1(x):
import math
return try_div_raise(x) * math.pi
def my_function_2(x):
return my_function_1(x) ** 3
print(my_function_2(0))
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-11-217e689aad21> in <module> ----> 1 print(my_function_2(0)) <ipython-input-10-a14a0e1cae82> in my_function_2(x) 1 def my_function_2(x): ----> 2 return my_function_1(x) ** 3 <ipython-input-9-df39f950897f> in my_function_1(x) 1 def my_function_1(x): 2 import math ----> 3 return try_div_raise(x) * math.pi <ipython-input-8-5197d1b33b74> in try_div_raise(x) 4 else: 5 # генерируем исключение: ----> 6 raise ZeroDivisionError ZeroDivisionError:
try:
print(my_function_2(0))
except ZeroDivisionError:
print("Ошибка деления на ноль!")
Ошибка деления на ноль!
4/0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-13-221068dc2815> in <module> ----> 1 4/0 ZeroDivisionError: division by zero
def my_function_1(x):
import math
return 5/x * math.pi
def my_function_2(x):
return my_function_1(x) ** 3
try:
print(my_function_2(0))
except ZeroDivisionError:
print("Ошибка деления на ноль!")
Ошибка деления на ноль!
int("r")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-17-569d5a0b6fc1> in <module> ----> 1 int("r") ValueError: invalid literal for int() with base 10: 'r'
try:
x = int(input("Введите число: "))
print(5/x)
except ZeroDivisionError:
print("Ошибка деления на ноль!!!")
except ValueError:
print("Ошибка преобразования типа!!!")
1.25
try:
x = int(input("Введите число: "))
print(5/x)
except:
print("Какая-то ошибка")
1.25
try:
x = int(input("Введите число: "))
print(5/x)
except Exception as err:
#print(type(err))
print(err)
1.6666666666666667
def get_int(msg):
while True:
try:
x = int(input(msg))
return x
except ValueError:
print("Ошибка преобразования типов")
get_int("Введите целое число: ")
3
x = (1, 2, 3)
assert len(x) > 5, 'len(x) not > 5'
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-23-6c33631a5f58> in <module> 1 x = (1, 2, 3) ----> 2 assert len(x) > 5, 'len(x) not > 5' AssertionError: len(x) not > 5