Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # WEBINAR: For Loops
- # We use loops to repeat actions
- # a WHILE loop is basically an IF statement
- # that repeats as long as its condition is true
- # FOR LOOPS are used for repeating actions for every element
- # in a container like a list, string, tuple, etc...
- # Focus on FOR LOOPS for the OA (don't worry about while loops so much)
- # Don't worry about nested loops either :), just one loop at a time
- # BASIC LOOP syntax with a list
- # for __ in ___:
- # for _myVar_ in _someContainer_:
- myList = ["Agent Scully", "Agent Mulder", "Walter Skinner", "CSM", "Mr. X"] # X-Files characters
- for item in myList:
- print(item)
- # tuple
- myTuple = ("Gilligan", "Castaway002", "red", "crew") # things about Gilligan
- for item in myTuple:
- print(item)
- myString = "Just sit right back and you'll hear a tale."
- # for char in myString:
- # print(char)
- # dict
- scoobiesDCT = {
- "Scooby": "a blue collar",
- "Shaggy": "green",
- "Velma": "orange",
- "Daphne": "purple",
- "Fred": "an ascot"
- }
- # nameOfDict[key] = value
- for key in scoobiesDCT:
- v = scoobiesDCT[key]
- print(key, "-->", v)
- # range() turns numbers into an iterable container
- for n in range(0, 5): # integers aren't iterable, but range objects are
- print(n)
- # Getting the index of a list or other container's values
- # 2 ways to do this...
- # range() + len()
- for i in range(len(myList)):
- item = myList[i]
- print(i, ":", myList[i])
- # enumerate()
- for i, item in enumerate(myList):
- print(i, ">>", item)
- # examples and student questions...
- # Ch 8 Task 10
- # Complete the function to return the number of upper case letters in the given string
- def countUpper(mystring):
- # string method isupper()
- count = 0
- for letter in mystring:
- if letter.isupper():
- # print(letter)
- count += 1
- return count
- print(countUpper('Welcome to WGU'))# expected output: 4
- print(countUpper('Hello Mary'))# expected output: 2
- # using help() or dir() in test system
- def myFunction(x, y, z):
- # help(str)
- h = help(str)
- return h
- # return x + y + z
- print(myFunction(1, 2, 3))
- print(myFunction(4, 5, 6))
- # Ch 12 Task 5
- import os
- # Complete the function to print all files in the given directory
- def printFiles(someDirectory):
- # return os.listdir(someDirectory) # wrong! b/c that's a list
- # fileList = os.listdir(someDirectory)
- for item in os.listdir(someDirectory):
- print(item)
- # expected output: main.py # <--- ALWAYS watch the output! It's not a list!
- printFiles(os.getcwd())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement