Text Size
Text Size
Exit Full Screen
Python3 Editor
Show
Source Code
View Source Code in Full Screen
# LOOPS #----------------------------------------- # Loops are used to repeat a set of statements. # In python, there are for-loops and while loops. A for-loop runs a specific number of times. # It's syntax is always written like this: # for i in some_list: # some code # i = the iterating variable, it can be named anything so long as it's not a variable already in use # some_list = a list of values for it to iterate through # the range() function generates a range() object. There are 3 ways to use it: # range(end) = generates a range object containing values starting at 0 and ending at end-1. print("range(10) =", list(range(10))) # range(start, end) = generates a range object containing values starting at start, ending at end-1. print("range(5, 12) =", list(range(5, 12))) # range(start, end, skip) = generates a range object containing values starting at start, ending at end-1, and skipping by the skip value print("range(2, 20, 2) =", list(range(2, 20, 2))) print() # The following loop will iterate through the range(10) object, which contains [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. # The first time it runs, i = 0 (first item in list), so it prints out '0'. # Second time it runs, i = 1 (second item in list), so it prints out '1'. # This continues until it reaches the last item in the list, prints it out, and stops running the loop. for i in range(10): print(i, end=" ") print() # You can assume that the loop iterating variable is storing the current value in the iteration, so you can do operations to it, # depending on its type. When using range(), the iterating variable's type is an integer. for i in range(10): print(i**2, end=" ") print('\n') # Let's say you already have a list of items, you can use a loop to iterate through those as well. # In the example below, it will calculate the average of a list of grades. Since each grade is a float, the iterating variable # will also be storing a float (instead of an integer) grades = [95.4, 77.6, 54.2, 67.9, 83.0] total = 0 for g in grades: print(g, end=', ') total += g print() avg = total/len(grades) print('The total is', total) print('The average is', avg) print() # Remember that a string is like a list of characters? You can use a for-loop to iterate through EACH character in a string. s = "Dinosaur" for c in s: print(c, end=" ") print("\n") # You can also check conditions inside the for-loop, and can check properties of each character in the string. s = 'Dino1 saur!' for c in s: if c.isalpha(): print(c, "is a letter!") elif c.isdigit(): print(c, "is a digit!") elif c.isspace(): print(c, "is a space!") elif c in ['!', '@', '#', '$', '%', '^', '&']: print(c, "is a character!") else: print(c) print() #------------------------------------------------------ # Break, Continue #------------------------------------------------------ # If you are iterating (looping) through something and checking for a specific condition, # you can stop the loop when that condition is true by using the keyword 'break' # The example below will print out 0 1 2 3 4 5 6 and will stop running the loop, when i == 7. for i in range(10): if i == 7: break print(i, end=' ') print() # If you want to skip a specific iteration, you can use the keyword 'continue' # The example below will print out 0 1 2 3 5 6 8 9. Notice that 4 and 7 are missing? # It will hit the 'continue' keyword, ignore the rest of the code in the loop, and # return back to the loop header to go to the next iteration. for i in range(10): if i == 4 or i == 7: continue print(i, end=' ') print('\n') #--------------------------------------------------------------------------------- # While loops #--------------------------------------------------------------------------------- # While loops are used when you want to run a loop until a certain condition is true, # but it may not need to run an exact number of times. # The format for a while loop is: # while condition: # some code # Example: Asking the player to enter input over and over again until it's valid. # If they enter a valid choice the first time, the loop won't run. But each time they enter something invalid, # the loop will run and ask them to try again. choices = ['rock', 'paper', 'scissors'] player = input("Enter a choice " + str(choices) + ": ").lower() while player not in choices: print("Invalid input:", player) player = input("Enter a choice " + str(choices) + ": ").lower() print("Final choice:", player) # Example: Run until they guess the right value guess = input("Guess a letter: ").lower() correct = 'h' while guess != correct: print("Wrong!") guess = input("Guess a letter: ").lower() print("CORRECT! The letter was", correct) print() # You can also use this to run similar to a for-loop, but you don't need the iteration to always increase the iterating variable. i = 0 while i < 8: if i % 2 == 0: print(i, "is even so", end=" ") i += 3 else: print(i, "is odd so", end=" ") i -= 1 print("i =", i) print()
CS110_Lesson5_Notes.py
( around 117 lines Python3 code )
Published By:
Mentor Sabrina
Created on
2020-11-09T13:54:03Z
Python3 Editor
- an
OYOclass
application,
own your own class today
.
Run
Result
Status:
Program is not running