[英]How to call datatype of an input in python
I want the output of my code to be ("TypeError") when i typed string on the input instead of Traceback ValueError当我在输入上键入字符串而不是 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")
But it did not work on this code但它不适用于此代码
In python, there is a special statement that can catch errors, the try... except...
statement.在 python 中,有一个可以捕获错误的特殊语句,
try... except...
语句。
What this does is:这是做什么的:
Executes the code in the
try
section of the code.执行代码的
try
部分中的代码。 On encountering an error it executes theexcept
section of the code.在遇到错误时,它会执行代码的
except
部分。
Example:例子:
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.