Python Essentials Classroom Series – 28/Jul/2021

Sets

  • Sets are unordered collection of unique objects and is used find distinct values or manage problems related to membership
  • To create a set a collection of values in curly braces or give an existing collection item to set() Preview
  • Set Operations
    • add
    • clear
    • copy
    • difference
    • discard
    • intersection
    • union
    • issubset
    • issuperset Preview

Dicitionary

  • Dictionary is mapping between keys and values.
  • We can create dictionary by closing keys and values with in curly braces
stock = {
    'name' : 'Microsoft',
    'price': 286.54
}
  • To access the elements we can access them by keys
stock['name']
stock['price']

Preview

  • Iterating a dictionary
portfolio = dict()
portfolio['Microsoft'] = 286.54
portfolio['IBM'] = 142.75
portfolio['Amazon'] = 3626.39
portfolio['Apple'] = 146.77
portfolio['Google'] = 2638

for name, price in portfolio.items():
    print(f"{name} ==> {price}")

for name in portfolio.keys():
    print(f"{name} --> {portfolio[name]}")

Range in python

  • Generally when we iterate over a loop we iterate over a range of integers, Python has a range function that create an object that represents range of integers.
range(start, stop [,step])
  • Examples
range(5)  => 0,1,2,3,4
range(1,6) => 1,2,3,4,5
range(0,10,3) => 0,3,6,9
range(5,1,-1) => 5,4,3,2
  • Lets use this range with for loop to find the prime number
  • With while
number = 19
index = 2
while index < number:
    if number%index == 0:
        print('not prime')
        break
    index += 1
else:
    print('prime')
  • With Range
number = 19
for index in range(2,19):
    if number%index == 0:
        print('not prime')
        break
else:
    print('prime')

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin