MyAI

Control Statement

If Statement

a = 10
if (a>0) and (a<5):
    print("No between 0 to 5")
elif (a>5) and (a<11):
    print("No between 5 to 11")
else:
    print("No more than 11")

Result:

No between 5 to 11

For Statement

mylist = [1,2,3,4,5,6,7,8,9]
for num in mylist:
    print(num)

fruits = ["apple","orange","banana"]
for x in fruits:
    if x == 'banana':
        break
    print(x)

mystring = 'Sunil Marella'
for let in mystring:
    print(let)

for _ in 'Sunil':
    print('Marella')
# print Marella 5 times which is 5 char in Sunil

tup = (1,2,3)
for item in tup:
    print(item)

mylist = [(1,2),3,(4,5,6)]
for items in mylist:
    print(items)

#tuples unpacking
mynewlist = [(1,2),(3,4),(5,6)]
for a,b in mynewlist:
    print(a) #prints all first values
    print(b) # print all 2nd values

mynewlists = [(1,2,3),(4,5,6),(7,8,9)]
for a,b,c in mynewlists:
    print(a) #prints all first values
    print(b) # print all 2nd values
    print(c)

d = {'k1':1,'k2':2,'k3':3}
for items in d.items():
    print(items)

for key,values in d.items():
    print(key)
    print(values)

for num in range(3,10):
    print(num)

index_count = 0

for letter in 'abcdef':
    print(f'At index {index_count} the letter is {letter}')
    index_count += 1

for item in enumerate('abcdef'):
    print(item)

mylist1 = [1,2,3]
mylist2 = ['a','b','c']
for item1 in zip(mylist1,mylist2):
    print(item1)

Result:

1
2
3
4
5
6
7
8
9
apple
orange
S
u
n
i
l

M
a
r
e
l
l
a
Marella
Marella
Marella
Marella
Marella
1
2
3
(1, 2)
3
(4, 5, 6)
1
2
3
4
5
6
1
2
3
4
5
6
7
8
9
('k1', 1)
('k2', 2)
('k3', 3)
k1
1
k2
2
k3
3
3
4
5
6
7
8
9
At index 0 the letter is a
At index 1 the letter is b
At index 2 the letter is c
At index 3 the letter is d
At index 4 the letter is e
At index 5 the letter is f
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
(1, 'a')
(2, 'b')
(3, 'c')

While Statement

x = 0
while x < 5:
    print(f'Current value of x is {x}')
    x += 1
else:
    print('end of loop')

items= 0
mylists = [1,2,3]
while items in mylists:
    pass
print('End of script')

Result:

Current value of x is 0
Current value of x is 1
Current value of x is 2
Current value of x is 3
Current value of x is 4
end of loop
End of script

Case Statement

def observability(tool):
    match tool:
        case "Splunk": return "Log Mgmt, Security O11y"
        case "Dynatrace": return "Observability"
        case "Datadog": return "Log mgmt & Observability"
        case _: return "Might be different tool"
print ("Splunk - ", observability("Splunk"))
print ("Datadog - ",observability("Datadog"))
print ("Newrelic - ",observability("Newrelic"))

Result:

Splunk -  Log Mgmt, Security O11y
Datadog -  Log mgmt & Observability
Newrelic -  Might be different tool

Main Page   Next Chapter: Python - Functions