为什么我不能在if语句中使用if语句?

时间:2020-01-22 12:28:05

标签: python if-statement except statements

为什么不能在除语句之外添加promiseFunction().then(() => { //function body here }) 语句?

我想在输出中显示两种形式的这种错误:

if

3 个答案:

答案 0 :(得分:2)

我认为您的问题不在于您不能将if放在except中。您提供的代码应该可以正常运行。但是,它不会执行您认为的操作。我怀疑您的代码包含以下内容:

t = input('>>>')

在这种情况下,t将始终是字符串。但是,如果您说

if t == float:
    print(">>> you should give a int number (you given float) <<<\n")
elif t == str:
    print(">>> you should give a int number (you given str) <<<\n")

这不会打印任何内容。为什么? t不等于字符串,它是字符串类型的对象。因此,请检查:

if isinstance(t, float):
    print(">>> you should give a int number (you given float) <<<\n")
elif isinstance(t, str):
    print(">>> you should give a int number (you given str) <<<\n")

答案 1 :(得分:1)

您可以在if块中使用条件逻辑,例如except语句:

try:
  raise ValueError("asd")
except ValueError as e:
  if someVal == 10:
    print("someval is 10")
  elif someVal == 20:
    print("someval is 10")

Try it here

但是,如果要检查变量的类型,请使用type

if type(myVar) == int:
    print("myVar is an integer")

在您的情况下,要检查变量具有哪种类型,可以执行以下操作:

#myVar = 10          #comment in the appropiate line
myVar = "a string"

try:
  # some work which might raise a ValueError
  raise ValueError()
except ValueError:
  if type(myVar) == int:
    print("myVar is an int.")
  elif type(myVar) == str:
    print("myVar is a string.")

另一种(可能更好)的检查特定类型的方法是使用isinstance。有关更多信息,请参阅Nathan的答案。

答案 2 :(得分:1)

使用此:

WebView.HitTestResult hr = ((WebView)v).getHitTestResult();

Log.i("TAGa", "getExtra = "+ hr.getExtra() + "Type= " + hr.getType());

在创建try: t = int(input("How time need: ")) except ValueError as e: if isinstance(_,float): print(">>> you should give a int number (you given float) <<<\n") elif isinstance(_,str): print(">>> you should give a int number (you given str) <<<\n") 之前引发了错误,因此是错误。我们知道python将最后的输入/答案存储在t中,因此使用了它。 :)