Data Warehousing, BI and Data Science

1 December 2020

Python: If and For

Filed under: Data Warehousing — Vincent Rainardi @ 6:11 am

if-elif-else ends with : and the next line must be indented (can be on the same line though).
Equal is ==, non equal is !=.
Use and, or to combine conditions.

a = 1
if a == 0: print("A") 
elif a != 1: print("B")
elif 4 > a == 8: print("C")
else: print("D")
Output: D
a,b = 5,6
if a==5 and b==7: print("A") 
else: print("B")
if a==5 or b==6: print("A")
else: print("B")
Output:
B
A

for can be used with rangestringlisttupledictionaries or enumerate.
range(a,b,c) means from a to b step c but does not include b.

for i in range(1,5,2): print(i)
Output:
1
3
for i in reversed(range(1,5,2)): print(i)
Output:
3
1

in can be used with a list (without range) like this:

for i in "abc": print(i)
for i in [1,4,2]: print(i)
for i in (1,4,2): print(i)

in can be used with a dictionary like this:

for i,j in {"name":"Harry","age":11}.items(): print(i,j)
Output:
name Harry
age 11

D = {1:["Harry", 11], 2:["Ron", 11], 3:["Hermione", 10]}
for i,j in D.items(): print(i,j)
Output
1 ["Harry", 11]
2 ["Ron", 11]
3 ["Hermione", 10]

for(i,j) can use with enumerate to get the counter in i, like this:

for i,j in enumerate("abc"): print(j, i)
Output:
a 0
b 1
c 2

In for loop we can use break, continue, pass :

a = ''
b = 'abcdef'
for i in range(0,6):
  a += b[i]
  if i == 2: break #pass or continue
print(a)
Output: abc

Use zip to loop around 2 lists together :

list1,list2 = [1,2,3],[10,20,30]
for i,j in zip(list1,list2): print('{0}  {1}'.format(i,j))
Output:
1  10
2  20
3  30

We can use while to make a loop too :

i = 0
while i <= 3:
    print(i)
    i += 1
Output:
0
1
2
3

Use add to append to the range used in the for loop.
Note: add doesn’t output anything.

a = {1, 2}
for i in range(3,5): #5 is not included
    print(a.add(i)) #add doesn't output anything
print(a)
Output:
None
None
{1, 2, 3, 4}

Combining for, if, modulo and pass:

for i in range(1,4): #4 is not included
    if (i % 2 == 0): #modulo means "the reminder"
        print(str(i) + " is divisible by 2")
        pass #after printing 2, continue with 2 (stay in the loop)
    print(str(i) + " is not divisible by 2")
Output:
1 is not divisible by 2
2 is divisible by 2
2 is not divisible by 2
3 is not divisible by 2

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: