[英]How to call datatype of an input in python
当我在输入上键入字符串而不是 Traceback ValueError 时,我希望我的代码的 output 为(“TypeError”)
import math
log = input("log of:")
base = input("with base: ")
print(type(log))
if (int(log)> 0 and int(base)>0):
log= int(log)
base = int(base)
n = math.log(log,base)
print("log of", log,"with base",base, "is", n)
else:
print("typeerror")
但它不适用于此代码
在 python 中,有一个可以捕获错误的特殊语句, try... except...
语句。
这是做什么的:
执行代码的
try
部分中的代码。 在遇到错误时,它会执行代码的except
部分。
例子:
import math
log = input("log of:")
base = input("with base: ")
print(type(log))
try:
log= int(log)
base = int(base)
n = math.log(log,base)
print("log of", log,"with base",base, "is", n)
except ValueError: # If ValueError occurs.
print("TypeError") #Prints TypeError
有关更多信息,请参阅此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.