Unit-3 Conditional Statements
Unit-3 Conditional Statements
Conditional Statements
Python Programming
Logical Operator
• AND
• (True and True) = True
• OR
• (True and False) = True
• IN
• a=“123456”, 2 in a = True
• NOT
• not(True) = False
If – elif - else
• If (condition– answer in boolean)
• else
• List comprehension is generally more compact and faster than normal functions
and loops for creating list.
• However, we should avoid writing very long list comprehensions in one line to
ensure that code is user-friendly.
• Remember, every list comprehension can be rewritten in for loop, but every for
loop can’t be rewritten in the form of list comprehension.
Lambda Function
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but
can only have one expression.
• x = lambda a : a + 10; print(x(5))
• x = lambda a, b : a * ; print(x(5, 6))
• Eg:
• def myfunc(n):
return lambda a : a * n
• mydoubler = myfunc(2)
• print(mydoubler(11))
Advanced Lambda usage
• Example use with filter()
• The filter() function in Python takes in a function and a list
as arguments.
• The function is called with all the items in the list and a
new list is returned which contains items for which the
function evaluates to True.
• # Program to filter out only the even items from a list
• my_list = [1, 5, 4, 6, 8, 11, 3, 12]
• new_list = list(filter(lambda x: (x%2 == 0) , my_list))
• print(new_list)
Advanced Lambda usage
• Example use with map()
• The map() function in Python takes in a function and a list.
• The function is called with all the items in the list and a
new list is returned which contains items returned by that
function for each item.
• # Program to double each item in a list using map()
• my_list = [1, 5, 4, 6, 8, 11, 3, 12]
• new_list = list(map(lambda x: x * 2 , my_list))
• print(new_list)