Introduction To Python For Beginner Part 3
32. Key Value Pairing – Dict
Key Value Pairing - Dict
When you wife asks you buy something does she gives you a list, tuple or dict?
Two dictionaries and play with the two dictionaries.
Looping through the key value pairs.
Read about JSON the equilvanet in JS and MongoDB.
1. # create a mapping of state to abbreviation
2. states = {
3. 'Oregon': 'OR',
4. 'Florida': 'FL',
5. 'California': 'CA',
6. 'New York': 'NY',
7. 'Michigan': 'MI'
8. }
9.
10. # create a basic set of states and some cities in them
11. cities = {'CA': 'San Francisco',
12. 'MI': 'Detroit',
13. 'FL': 'Jacksonville'}
14.
15. # add some more cities
16. cities['NY'] = 'New York'
17. cities['OR'] = 'Portland'
18.
19. # print out some cities
20. print('-' * 10)
21. print("NY State has: ", cities['NY'])
22. print("OR State has: ", cities['OR'])
23.
24. # print some states
25. print('-' * 10)
26. print("Michigan's abbreviation is: ", states["Michigan"])
27. print("Florida's abbreviation is: ", states['Florida'])
28.
29. # do it by using the state then cities dict
30. print('-' * 10)
31. print("Michigan has: ", cities[states['Michigan']])
32. print("Florida has: ", cities[states['Florida']])
33.
34. # print every state abbreviation
35. print('-' * 10)
36. for state, abbrev in states.items():
37. print(f"{state} is abbreviated {abbrev}")
38.
39. # print every city in state
40. print('-' * 10)
41. for abbrev, city in cities.items():
42. print(f"{abbrev} has the city {city}")
43.
44. # now do both at the same time
45. print('-' * 10)
46. for state, abbrev in states.items():
47. print(f"{state} state is abbreviated {abbrev}")
48. print(f"and has city {cities[abbrev]}")
49.
50. print('-' * 10)
51. # safely get an abbreviation by state that might not be there
52. state = states.get('Texas')
53.
54. if not state:
55. print("Sorry, no Texas.")
56.
57. # get a city with a default values
58. city = cities.get('FL', 'Does not Exist')
59. print(f"The city for the state 'TX' is: {city}")
Long code.. to reverse things...
Value from key is simple just write a square bracket, or use get. But if you want to do the opposite which is find key for a value then you have write this code.
1. # run the below
2. print(list(cities.keys())[list(cities.values()).index('New York')])
1. #list from dict
2. list( cities.values()).index('New York')
1. #list of keys
2. list(cities.keys())
1. #looping through all
2. for key, value in states.items():
3. print(f"{key} key is abbreviated {value} value")
1. #get items
2. states.items()
1. city = cities.get('XXX', 'Does not Exist')
2. print(f"The city for the state is: {city}")
We tried to loop through the dictionary.
And play with it...
33. Key Value Pairing - Dict
34. For Loops
For Loops
Loop are iterations.
Do things again. Traversing through, Going to each value.
They dont come again
as what you might think in English..
Loops take time to
understand so it is a matter of time... dont give up!!!
For loop
1. the_count =
[1, 2, 3, 4, 5]
2. fruits = ['apples', 'oranges', 'pears', 'apricots']
3. change =
[1, 'rupee', 2, 'paisa', 3, 'mudra']
4.
5. # traverse
through the list we created
6. for xxx in the_count:
7. print(f"This is count {xxx}")
8.
9. # traverse
throught a string list we created
10. for fruit in fruits:
11. print(f"A fruit of type: {fruit}")
12.
13. # also we
can go through mixed lists too
14. for i in change:
15. print(f"I got {i}")
16.
17. # we can
also build lists, first start with an empty one
18. elements =
[]
19.
20. # then use
the range function to do 0 to 5 counts
21. for i in range(0, 6):
22. print(f"Adding {i} to the list.")
23. # append is a function that lists understand
24. elements.append(i)
25.
26. # now we
can print them out too
27. for i in elements:
28. print(f"Element was: {i}")
This one is
for_each_xxx
1. elements =
[]
2.
3. # then use
the range function to do 0 to 5 counts
4. for xxx_each in the_count:
5. print(f"Adding {xxx_each} to the list.")
6. # append is a function that lists understand
7. elements.append(xxx_each)
Traverse and double
the value
1. # this
first kind of for-loop goes through a list
2. for eachvalue in the_count:
3. print(f"This is count {eachvalue*2}")
Other languages dont
have "in" the one in "for xxx in listofelements" hence they
have to do the it the length way!
1. for i in range(0, len(the_count)):
2. print (the_count[i],i)
1. element=[]
2. for i in range(6, 0, -1):
3. print(f"Adding {i} to the list.")
4. # append is a function that lists understand
5. elements.append(i)
List and changing
things for printing.
1. the_count =
[10, 20, 30, 40, 50]
2.
3. for xxx in the_count:
4. print(xxx-1)
1. for i in range(0, 3):
2. print(i)
List with loop and
append command.
1. # we can
also build lists, first start with an empty one
2. elements =
[]
3.
4. # then use
the range function to do 0 to 5 counts
5. for p in range(0, 6):
6. print(f"Adding {p} to the list.")
7. # append is a function that lists understand
8. elements.append(p)
1. xxx
=range(0, 6)
2. print (xxx)
3. list(xxx)
Loop in a loop, dream
in a dream, are we in simulation inside a simulation?
1. for i in range(4):
2. for j in range(4):
3. if j > i:
4. break
5. print((i, j))
It goes through list
and double all values but print it and not change it.
1. # this
first kind of for-loop goes through a list
2. for eachvalue in the_count:
3. print(f"This is count {eachvalue*2}")
simple loop again, I
keep bringing simple code to make sure you are not lost!
1. for i in range(0, len(the_count)):
2. print (the_count[i],i)
Loop in a loop, dream
in a dream... is this real or this is your code in dream?
1. for i in range(4):
2. for j in range(4):
3. # if j > i:
4. # break
5. print((i, j))
Or in a loop...
1. sum = 0
2. for i in range(10):
3.
4. # % is the modulo operator
5. if i % 3 == 0 or i % 5 == 0:
6. sum =sum + i
7. print ("i",i)
8. print ("sum",sum)
Step size changed...
1. for i in range(5,-5,-1):
2. if i >=-2:
3. print ('Non-negative')
4. else:
5. print('Negative')
Printing number triangle
1. def line(n):
2. triangle = ''
3. for i in range(1, n+1):
4. triangle = triangle + (str(i))
5. print(triangle)
6. i+=1
Pyramid world:
1. def half_pyramid(rows):
2. print('Half pyramid...\n')
3. for i in range(rows):
4. print('*' * (i+1))
5.
6. def full_pyramid(rows):
7. print('\nFull pyramid...\n')
8. for i in range(rows):
9. print(' '*(rows-i-1) + '*'*(2*i+1))
10.
11. def inverted_pyramid(rows):
12. print('\nInverted pyramid...\n')
13. for i in reversed(range(rows)):
14. print(' '*(rows-i-1) + '*'*(2*i+1))
15.
16. half_pyramid(5)
17. full_pyramid(5)
18. inverted_pyramid(5)
We played with lot of
for, I am expecting you are running these code with me in your Notebook?
Dont break my trust.
Prime Number and
nested loops:
# First is to search
prime numbers -
#for this we need to
use a code to see if number is divisble by iteself and no other
1. def is_prime(number):
2. # if number is equal to or less than 1, return
False
3. if number <= 1:
4. return False
5.
6. for x in range(2, number):
7. # if number is divisble by x, return False
8. if not number % x:
9. return False
10. return True
11.
12. output = []
13. listofn =
[262, 102, 23, 164, 96]
14. numtotest =
30
15.
16. # this the
main loop - it goes through each number
17. # once we
get access to each then add things and also for prime number we create another
function and check
18.
19. def get_divisors(listofn,
numtotest):
20.
21. for i in listofn:
22. print (i)
23. sumofn = 0
24. #This loop converts the elements like 262 into
string and then sums them up
25. for num in list(str(i)):
26. sumofn = sumofn + int(num)
27. # this is the sum of the digits of the number
28. # if checking for both conditions
29. if (numtotest % sumofn ==0) and (is_prime(sumofn) == True):
30. #adding to the empty list
31. output.append(i)
32. return output
35. For Loops
36. While Loops
While
Loops
While loops controls the iteration inside the loop.
They are different from for loop where the iteration is
fixed.
We will see various examples here and BREAK THE CODE!
1.
i = 0
2.
numbers = []
3.
4.
while i < 7:
5.
print(f"At the top i is {i}")
6.
numbers.append(i)
7.
8.
i = i + 3
9.
print("Numbers now: ", numbers)
10. print(f"At the bottom i is {i}")
11.
12. print("The numbers: ")
13.
14. for num in numbers:
15. print(num)
Checking things before changing in the loop and
understanding the output.
1.
i = 0
2.
numbers = []
3.
4.
while i < 6:
5.
print(f"At the top i is {i}")
6.
numbers.append(i)
7.
8.
i = i + 1
9.
print("Numbers now: ", numbers)
10. print(f"At the bottom i is {i}")
11.
12. print("The numbers: ")
13.
14. for xxx in numbers:
15. print(xxx)
1.
i=0
2.
li = [2,3,5,67,85,5,4]
3.
max = len(li)
4.
while i < max:
5.
print (li[i])
6.
i=i+1
Break in a while loop as while loop never ends.
Dont break my trust and copy paste and run this code on your
Jupyter Notebook.
1.
x = 256
2.
total = 0
3.
4.
while x > 0:
5.
if total > 400:
6.
break
7.
total =total+ x
8.
x = x / 2
We checked while loop, let us say everything in English
after me.
while in a while
1.
line=1 #this is the initial variable
2.
while line <= 5 :
3.
pos = 1
4.
while pos < line:
5.
6.
#This print will add space
after printing the value
7.
print (pos,)
8.
9.
#increment the value of pos
by one
10. pos += 1
11. else:
12. #This print will add newline
after printing the value
13. print (pos)
14.
15. #increment the value of line by one
16. line += 1
Another while inside a while, let us see if you predict the
number of stars.
1.
i=1
2.
while i < 11:
3.
j = 0
4.
while j < i:
5.
print('*',end='')
6.
j=j+1
7.
print()
8.
i=i+1
9.
print("Rest of the
program")
37. While Loops
38. What to remember from this
course
course
What
to remember from this course
Takeaways:
1.
Python
is not hard
2.
Python
tries to guess
3.
Python
like short code
4.
Errors
are hard to read ... sometimes..
Remember to "BREAK THE CODE"
Google search and use stack overflow
Support Green earth
Thanks for taking the course.
If you dont find any material or attachment then please feel
free to email or comment.
The course is constantly updated so you can follow me on
github to see the new content!
39. What to remember from this course
نظرات
ارسال یک نظر