Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use ternary expressions in python

Shulou Source: shulou.com Published: 2022-06-01 05:42:11 10月03日 Update

This article mainly shows you "python how to use ternary expressions", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "python how to use ternary expressions" this article.

Ternary expression

Programmers familiar with python + will miss the classic ternary operator when they start using python, because it seems more troublesome to write it in python to express the same idea. For example:

> y = 5 > if y

< 0:print('y是一个负数')else:print('y是一个非负数')y是一个非负数 其实,python 是支持三元表达式的,只是稍微怪异了一点,类似于我们山东人讲话。比如,山东人最喜欢用倒装句:打球去吧,要是不下雨的话;下雨,咱就去自习室。翻译成三元表达式就是: 打球去吧 if 不下雨 else 去自习室 来看看三元表达式具体的使用: >

> > y = 5 > > print ('y is a negative number'if y

< 0 else 'y是一个非负数')y是一个非负数 python 的三元表达式也可以用来赋值: >

> > y = 5 > x =-1 if y

< 0 else 1>

> > x above is all the content of the article "how to use ternary expressions in python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Ternary expressions negative numbers content articles Shandong people self-study rooms Shandong learning help self-study weird inverted sentences just that is thoughts operators easy to understand more organized Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information vpn Xiaomi Shulou Tech Info