Advertisement
jspill

webinar-for-loops-v4-2021-10-2

Oct 2nd, 2021
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. # WEBINAR: For Loops
  2. # We use loops to repeat actions
  3.  
  4. # a WHILE loop is basically an IF statement
  5. # that repeats as long as its condition is true
  6.  
  7. # FOR LOOPS are used for repeating actions for every element
  8. # in a container like a list, string, tuple, etc...
  9.  
  10. myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"]
  11.  
  12. for item in myList:
  13.     # print("The truth is out there, {}!".format(item)) # string.format()
  14.     # BTW you'll see F STRING formatting in the new book and Pre
  15.     # It's very similar to string.format(), just more condensed...
  16.     print(f"The truth is still out there, {item}!")
  17.  
  18. # Student questions
  19. #Lab 26.3.1
  20. # input
  21. user_input = "automobile car   manufacturer maker   children kids"
  22. user_sentence = "The automobile manufacturer recommends car seats for children if the automobile doesn't already have one."
  23.  
  24.  
  25. ''' Type your code here. '''
  26. # help(str.replace)
  27. # for item in dir(list):
  28. #     print(item)
  29. word_pairs = {}
  30. # grab the words to replace
  31. tokens = user_input.split()
  32.  
  33. # fill word pairs dict
  34. for i in range(0, len(tokens), 2):
  35.     # word_pairs[key] = value
  36.     word_pairs[tokens[i]] = tokens[i+1]
  37. # print(f"dictionary: {word_pairs}") # it looks good!
  38.  
  39. # You could... loop over dict to do our string replacement
  40. # for k,v in word_pairs.items():
  41. #   user_sentence = user_sentence.replace(k, v)
  42.  
  43. # an alternate way...
  44. # Loop over the sentence as a list of string instead, checking dict keys as you go:
  45. for word in user_sentence.split():  #
  46.     if word in word_pairs:
  47.         user_sentence = user_sentence.replace(word, word_pairs[word])
  48.  
  49. # check string out
  50. print(user_sentence)
  51.  
  52.  
  53. # find day of the week from a specified date
  54. import datetime
  55. dd = datetime.datetime(1971, 3, 3) # what day of the week?
  56. for item in dir(datetime.datetime):
  57.     if not item.startswith("_"):
  58.         print(item)
  59. help(datetime.datetime.weekday)
  60. print(dd.weekday()) # day is 2... OK, which day is 2?
  61. import calendar
  62. print(calendar.day_name[dd.weekday()])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement