if-else
if - elif - ... - else
- There can be zero or more elif.
- There can be nesting to suit given conditions.
# example
if num > 0 :
print("positive")
elif num < 0 :
print("negative")
else:
print("zero")
# shorthand if-else (can be used as ternary operator)
even = True if i%2 else False
Chaining comparison operator
a op1 b op2 c is equivalent to a op1 b and b op2 c
if a < b < c : # equivalent to if a < b and b < c
pass
Loop
For Loop
''' syntax '''
for var in iterable:
pass
''' example '''
l1 = [1, 2.3, "hi"]
for ele in l1:
print(ele)
While loop
''' example with list '''
l1 = [1, 2.3, "hi"]
while a:
print(a.pop())
''' single statement while block '''
count = 0
while (count < 5): count += 1; print("Hello!!")
''' sentinel controlled while loop '''
a = int(input('Enter a number (-1 to quit): '))
while a != -1: # no need of counter
a = int(input('Enter a number (-1 to quit): '))
Loop control statements
Controlling loops
''' examples are with for, but can also be achieved using while '''
# continue, break, pass
moves = ["start", "straight", "left", "straight", "skip", "right", "end", "left", "straight"]
for move in moves:
if move == "skip":
continue # skips execution from here and moves to next loop
elif move == "end":
break # breaks the loop
else:
print(move)
for move in moves:
pass # passes the entire execution
# with else
alphabets = ["x", "y", "z"]
for alphabet in alphabets:
if isVowel(alphabet):
break
else: # executes when no break statement is called in the for loop
print("the loop didn't break immaturely")
Pass
- Pass is a statement which does nothing when executed - Because it is a null statement.
- The statement is not ignored by the interpreter, but the statement results in no operation.
- It is used when we do not want anything to be executed, but a statement is required.
Looping techniques
Using enumerate(): index number along with value present in that index
for key, value in enumerate(l1):
print(key, value)
zip() is used to combine 2 similar
containers(list-list or dict-dict) printing the values sequentially.
questions = ['name', 'colour', 'shape']
answers = ['apple', 'red', 'a circle']
for question, answer in zip(questions, answers):
print('What is your {0}? I am {1}.'.format(question, answer))
iteritem() is used to loop through the
dictionary printing the dictionary key-value pair sequentially which is
used before Python 3 version.
d = {"name": "apple", "colour": "red", "shape": "a circle"}
for i, j in d.iteritem():
print(i, j)
items() performs the similar task on
dictionary as iteritems() but have certain disadvantages when compared
with iteritems().
- It is very time-consuming. Calling it on large dictionaries consumes quite a lot of time.
- It takes a lot of memory. Sometimes takes double the memory when called on a dictionary.
d = {"name": "apple", "colour": "red", "shape": "a circle"}
for i, j in d.items():
print(i, j)
sorted() is used to print the container is
sorted order. It doesn't sort the original list, just returns one in
sorted order.
lis = [1, 3, 5, 6, 2, 1, 3]
for i in sorted(lis):
print(i)
reversed() is used to print the values of the
container in the reversed order
lis = [1, 3, 5, 6, 2, 1, 3]
for i in reversed(lis):
print(i)