Python:If-else语句 [英] Python: If-else statements

查看:83
本文介绍了Python:If-else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码显示错误:

  if((type(varA)or type(varB)) == type('t')):
printstring involving
elif varA< varB:
printRANDOM

错误适用于这种情况:

 测试值:varA = 0,varB = adios 

输出:

  RANDOM 

而另一段代码

  if((type(varA)== type('t'))或(type(varB)== type('t' ))):
打印涉及字符串
elif varA< varB:
打印RANDOM`

对于以下测试值:

 测试值:varA = 6,varB = adios 

输出如下:

 涉及的字符串

这两个if条件之间有什么区别?我发现它们具有相同的逻辑!

解决方案

问题在于这个表达式:

  if((type(varA)or type(varB))== type('t')):

编程语言不像英语。上面首先评估类型(varA)或类型(varB),这将产生 varA 的类型 - 因为返回第一个truthy值,任何类型都是真实的。



然后它将检查是否相同as type('t') - 即 str 。这意味着当 varA 是一个字符串时,它才会成立,并且完全忽略 varB 的类型。 / p>

您想要的可能是:

 如果是type(varA) == type('t')或type(varB)== type('t'):

但是有更多的惯用/ Pythonic方法可以做到这一点;请参阅ÓscarLópez的答案。


The following piece of code is showing an error:

if ((type(varA) or type(varB) ) == type('t')):
    print "string involved"
elif varA<varB:
    print "RANDOM"

the error is for this case:

Test Values: varA = 0, varB = adios

output:

RANDOM

while this other piece of code

if ((type(varA) == type('t')) or (type(varB)== type('t'))):
    print "string involved"
elif varA<varB:
    print "RANDOM"`

For the following test values:

Test Values: varA = 6, varB = adios

ouput is as follows:

string involved

What is the difference between these two "if" conditions? I am finding them to be of the same logic!

解决方案

The problem is this expression:

if ((type(varA) or type(varB) ) == type('t')):

Programming languages don't work like English. The above first evaluates type(varA) or type(varB), which will yield the type of varA - because or returns the first truthy value and any type is truthy.

Then it will check to see if that is the same as type('t') - that is, str. Which means that it will only be true when varA is a string, and the type of varB is completely ignored.

What you want is probably this:

if type(varA) == type('t') or type(varB) == type('t'):

But there are more idiomatic/Pythonic ways of doing that; see Óscar López's answer for some examples.

这篇关于Python:If-else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆