Guest User

Untitled

a guest
Sep 11th, 2020
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1.  
  2. # chickens in a form of dictionary
  3. chicken1 = {"name":"Liza","hungry":"yes"}
  4. chicken2 = {"name":"Stacy","hungry":"yes"}
  5. chicken3 = {"name":"Lucy","hungry":"no"}
  6. chicken4 = {"name":"Kate","hungry":"no"}
  7. chicken5 = {"name":"Undercover Derek","hungry":"yes"}
  8.  
  9.  
  10. # A bad way to go about it :
  11. if chicken1['hungry'] == "yes":
  12.     # print formatted f-string.
  13.     print(f"Feeding {chicken1['name']}!")
  14.     # change value
  15.     chicken1['hungry'] = 'no'
  16.  
  17. # repeat -->>for each<-- chicken manually..
  18. if chicken2['hungry'] == "yes":
  19.     print(f"Feeding {chicken2['name']}!")
  20.     chicken2['hungry'] = 'no'
  21. if chicken3['hungry'] == "yes":
  22.     print(f"Feeding {chicken3['name']}!")
  23.     chicken3['hungry'] = 'no'
  24. if chicken4['hungry'] == "yes":
  25.     print(f"Feeding {chicken4['name']}!")
  26.     chicken4['hungry'] = 'no'
  27. if chicken5['hungry'] == "yes":
  28.     print(f"Feeding {chicken5['name']}!")
  29.     chicken5['hungry'] = 'no'
  30.  
  31. #What if we had 100 chickens? or 5000? we would have to write a lot of repetetive code which essentially
  32. # does the same thing. It's a "pattern". We can automate this mundane task by making Python do it for us.
  33. #
  34.  
  35. # chickens in a form of dictionary
  36. chicken1 = {"name":"Liza","hungry":"yes"}
  37. chicken2 = {"name":"Stacy","hungry":"yes"}
  38. chicken3 = {"name":"Lucy","hungry":"no"}
  39. chicken4 = {"name":"Kate","hungry":"no"}
  40. chicken5 = {"name":"Undercover Derek","hungry":"yes"}
  41. # lets assign our chikens to hen_house list
  42. hen_house = [chicken1,chicken2,chicken3,chicken4,chicken5]
  43.  
  44. # simple for loop, which does what we want for us in few lines of code, be it 1,2 or 200000 chickens
  45. for currently_selected_chicken in hen_house:
  46.     # we make a check for hungry value
  47.     if currently_selected_chicken['hungry'] == 'yes':
  48.         print(f"Feeding {currently_selected_chicken['name']}!")
  49.         # changing value
  50.         currently_selected_chicken['hungry'] = 'no'
  51.     # we can also define what we want to do if chicken is not hungry
  52.     elif currently_selected_chicken['hungry'] == 'no':
  53.         print(f"{currently_selected_chicken['name']} is not hungry.")
  54.  
  55.  
  56.  
  57.  
Advertisement
Add Comment
Please, Sign In to add comment