one-line conditional & switch statements in python

http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements

Conditional Statements

Many languages (like Java and PHP) have the concept of a one-line conditional (called The Ternary Operator), often used to simplify conditionally accessing a value. For instance (in Java):

int in= ; // read from program input
 
// a normal conditional assignment
int res;
if(number < 0)
  res = -number;
else
  res = number;
 
// this can be simplified to
int res2 = (number < 0) ? -number : number;

For many years Python did not have the same construct natively, however you could replicate it by constructing a tuple of results and calling the test as the index of the tuple, like so:

number = int(raw_input("Enter a number to get its absolute value:"))
res = (-number, number)[number > 0]

It is important to note that, unlike a built in conditional statement, both the true and false branches are evaluated before returning, which can lead to unexpected results and slower executions if you're not careful. To resolve this issue, and as a better practice, wrap whatever you put in the tuple in anonymous function calls (lambda notation) to prevent them from being evaluated until the desired branch is called:

number = int(raw_input("Enter a number to get its absolute value:"))
res = (lambda: number, lambda: -number)[number < 0]()

Since Python 2.5 however, there has been an equivalent operator to The Ternary Operator (though not called such, and with a totally different syntax):

number = int(raw_input("Enter a number to get its absolute value:"))
res = -number if number < 0 else number



Switch

A switch is a control statement present in most computer programming languages to minimize a bunch of If - elif statements. Sadly Python doesn't officially support this statement, but with the clever use of an array or dictionary, we can recreate this Switch statement that depends on a value.

x = 1
 
def hello():
  print ("Hello")
 
def bye():
  print ("Bye")
 
def hola():
  print ("Hola is Spanish for Hello")
 
def adios():
  print ("Adios is Spanish for Bye")
 
# Notice that our switch statement is a regular variable, only that we added the function's name inside
# and there are no quotes
menu = [hello,bye,hola,adios]
 
# To call our switch statement, we simply make reference to the array with a pair of parentheses
# at the end to call the function
menu[3]()   # calls the adios function since is number 3 in our array.
 
menu[0]()   # Calls the hello function being our first element in our array.
 
menu[x]()   # Calls the bye function as is the second element on the array x = 1
This works because Python stores a reference of the function in the array at its particular index, and by adding a pair of parentheses we are actually calling the function.

Another way

Source

Another way is to use lambdas. Code pasted here without permissions.

value='a'
x=10
result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)
print("result=",result)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值