比在python中使用if-else语句更好的方法 [英] better way than using if-else statement in python

查看:164
本文介绍了比在python中使用if-else语句更好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在一行上添加一个简单的if-then语句

我正在研究python表达式,我希望压缩表达式而不是使用if else语句。

I am working on a python expression and I want that expression to be compressed than using the if else statement.

s = [1, 2, 3, 4]
if len(s)>5:
    print s.index(5)
else:
    print 'cant print'

有没有比使用else else语句更好的方法?

Is there a better way than using as if else statement?

推荐答案

你可以这样做:

s = [1, 2, 3, 4]
print 'y' if len(s) > 5 else 'n'

但我不认为这会使代码更具可读性(一目了然) )。另请注意,如果 else 不创建循环,它们只是控制流的语句。循环使用写入,而

However I don't think this makes the code more readable (at a glance). Also note that if and else don't create a loop, they are simply statements for control flow. Loops are written using for and while.

这篇关于比在python中使用if-else语句更好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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