Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading /...

48
Python - Unit 3 Python Unit 4 4.1 4.3 4.1 The Hangman Program 4.2 Using Dictionaries 4.3 Portable Python and PyScripter

Transcript of Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading /...

Page 1: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Python Unit 4 4.1 – 4.3

4.1 – The Hangman Program

4.2 – Using Dictionaries

4.3 – Portable Python and PyScripter

Page 2: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Python – 4.1

The Hangman Program

Page 3: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Objectives

• By the end of this unit, you will be able

to:

– Describe how the Hangman Program works

– Discuss each function in the Hangman

program

Page 4: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Top of the Hangman Program

HANGMANPICS List

oASCII Art

oMulti-line strings

oAll-caps constants

Words List oSplit() String Method

• Link to the Hangman.py source code

Page 5: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The getRandomWord Function

Returns a random word from the input parameter wordList

o The words list is passed to this function as a parameter.

def getRandomWord(wordList):

wordIndex = random.randint(0, len(wordList)-1)

return wordList[wordIndex]

wordIndex is a random number from zero to the

number of items in wordList.

o Remember: The first index of a list is always zero

Page 6: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The getRandomWord Function (Continued)

def getRandomWord(wordList):

wordIndex = random.randint(0, len(wordList)-1)

return wordList[wordIndex]

len(wordList) - 1

– Returns the number of items in wordList

– The - 1 part accounts for lists being zero based.

return wordList[wordIndex]

– Returns the value of the item in wordList that contains

the index of wordIndex

– What does the return statement do here?

Page 7: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The displayBoard Function (Input variables)

• Prints the Hangman board on the screen. def displayBoard(HANGMANPICS, missedLetters,

correctLetters, secretWord):

Input Parameters:

o HANGMANPICS - A list of multi-line strings that will display the board as ASCII art. The HANGMANPICS constant is always passed to this function.

o missedLetters - A string made up of the letters the player has guessed that are not in the secret word.

o correctLetters - A string made up of the letters the player has guessed that are in the secret word.

o secretWord - The secret word that the player is trying to guess.

Page 8: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The displayBoard Function (Displaying Gallows and Missed Letters)

67. print(HANGMANPICS[len(missedLetters)])

68. print()

70. print('Missed letters:', end=' ')

71. for letter in missedLetters:

72. print(letter, end=' ')

67. Prints the gallows image from the HANGMAN list

based upon how many incorrect letters were guessed.

71. Loops through the missedLetters list

o 72. Prints the missedLetter values

Page 9: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The displayBoard Function (Printing Blanks and Guessed Letters)

75. blanks = '_' * len(secretWord)

76.

77. for i in range(len(secretWord)):

78. if secretWord[i] in correctLetters:

79. blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

81. for letter in blanks:

82. print(letter, end=' ')

75. Puts a dash into the blanks variable for each letter in the secretWord. o You can repeat a string by multiplying it using *

77. Uses range() to loop through the secretWord

• 78. If the letter at the index [i] for the secretWord list is in the correctLetters list.

Page 10: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The displayBoard Function (Formatting Blanks and Guessed Letters)

78. if secretWord[i] in correctLetters:

79. blanks = blanks[:i] + secretWord[i] + blanks[i+1:]

blanks[:i]

• Prints the blanks from the beginning up to the position previous to the one we are working with.

+ secretWord[i]

• Adds the letter at index [i] from the secretWord list.

+ blanks[i+1:]

• Adds the remaining blanks to the end of the string.

Page 11: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The displayBoard Function (Displaying Blanks and Guessed Letters)

81. for letter in blanks:

82. print(letter, end=' ')

83. print()

The blanks list already contains the letters and underscores we want to display.

The end=' ' command forces the print command to end with a space instead of a carriage return.

Page 12: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The getGuess Function (Getting the Guess)

85. def getGuess(alreadyGuessed):

The string parameter called alreadyGuessed contains the letters the player has already guessed.

87. while True:

88. print('Guess a letter.')

89. guess = input()

90. guess = guess.lower()

• Is .lower() a function or method?

• What does the .lower() function do?

• Why do we care about this?

Page 13: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The getGuess Function (Validating the Guess)

Players must enter a single letter that hasn’t already been guessed.

91. if len(guess) != 1:

92. print('Please enter a single letter.')

93. elif guess in alreadyGuessed:

94. print('You have already guessed

that letter. Choose again.')

95. elif guess not in 'abcdefghijklmnopqrstuvwxyz':

96. print('Please enter a LETTER.')

97. else:

98. return guess

Page 14: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The playAgain Function

This function returns True if the player

wants to play again, otherwise it returns False.

def playAgain():

print('Do you want to play again?

(yes or no)')

return input().lower().startswith('y')

Page 15: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Program Execution

• How do we know where the program starts

executing?

• What is the gameIsDone variable used for?

106. print('H A N G M A N')

107. missedLetters = ''

108. correctLetters = ''

109. secretWord = getRandomWord(words)

110. gameIsDone = False

Page 16: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The Game Loop

112. while True:

113. displayBoard(HANGMANPICS,

missedLetters, correctLetters,

secretWord)

Besides being a while loop, what type of loop is

this?

Page 17: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Player Input (Guess a Letter)

115. # Let the player enter a letter.

116. guess = getGuess(missedLetters +

correctLetters)

The getGuess() function helps the player

enter a guess.

(missedLetters + correctLetters) sends

the entire list of letters that the user may not select.

Page 18: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Is the Guess in the Secret Word?

118. if guess in secretWord:

119. correctLetters =

correctLetters + guess

• If the player guessed correctly, the letter is added to the correctLetters variable.

Page 19: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Reading / Exercise(s)

• Complete the exercises found on Intranet

under Game Development/Exercises:

– Link goes here

Page 20: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Did the Player Win? 122. foundAllLetters = True

123. for i in range(len(secretWord)):

124. if secretWord[i] not in correctLetters:

125. foundAllLetters = False

126. break

Loop through every letter in the secretWord string and see if it is not in the correctLetters string.

• If all letters in the secretWord string are also in correctLetters string foundAllLetters stays True.

Page 21: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Did the Player Lose? 131. missedLetters = missedLetters + guess

134. if len(missedLetters) == len(HANGMANPICS) - 1:

135. displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)

136. print('You have run out of guesses!\nAfter '

+ str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')

137. gameIsDone = True

The number of guesses allowed is based upon the number of pictures in HANGMANPICS

A noob message is displayed to the player

gameIsDone is set to True.

Page 22: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Reading / Exercises

• Complete the exercises found on Intranet

under Game Development/Exercises:

– Link goes here

Page 23: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Python – 4.2

Using Dictionaries

Page 24: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Objectives

• By the end of this unit you will be able to:

oUtilize the dictionary data type to store and

manipulate key-value pair data.

o Apply dictionaries to the Hangman program to

have sets of secret words.

Page 25: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Changes to the Hangman Program (P. 152)

• Now we will modify the Hangman.py

program to:

– Allow the player to have two more guesses.

– Group words into separate categories using

the dictionary data type.

• Randomly select the category

• Tell the player what category the secret word

comes from

Page 26: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The Dictionary Data Type (Data Structure)

Dictionary – An unordered collection of items. Like a list, but: 1 Key-Value Pairs Dictionaries contain keys and each key can have one or

more values.

2 Items are accessed by their key.

• Syntax for creating a dictionary: myDictionary = {'key1':'value1', 'key2': 'value2'}

Can access values of myDictionary like so: print(myDictionary['key1'])

• Returns: value1

Page 27: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

More on Dictionaries

The len() method returns the number of items in the dictionary

len(myDictionary)

Dictionaries don’t care about the order of items:

o Lists evaluate to unequal if they have the same values, but they are in different order.

You can also use integers as dictionary key fields .

Page 28: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Looping Through Dictionaries favorites = {'fruit':'apples', 'animal':'cats',

'number':42}

for i in favorites:

print(i) # Prints the keys fruit

number

animal

for i in favorites:

print(favorites[i]) # Prints the values apples

42

cats

Page 29: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

keys() and values() Methods

Use the keys() method to print the keys for the

specified dictionary.

print(str(myDictionary.keys()))

• Returns: dict_keys(['key2', 'key1'])

Use the values() method to print the values for the

specified dictionary.

print(str(myDictionary.values()))

• Returns: dict_values(['value2', 'value1'])

Page 30: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

A Dictionary in Hangman.py List named words that contains four keys, each with

several values.

words = {'Colors':'red orange yellow

blue'.split(),

'Shapes':'triangle

rectangle'.split(),

'Fruits':'apple orange pear

grape'.split(),

'Animals':'bat bear beaver

cat'.split()}

Page 31: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The choice() Function

• The choice() function returns an item randomly selected from a list each time it is called.

import random

myList = ['the', 'teacher', 'is', 'cool']

print(random.choice(myList))

• Returns: – A randomly selected item from myList

Page 32: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The New getRandomWord()

Function def getRandomWord(wordDict):

# Randomly select a key from the dictionary

wordKey = random.choice(list(wordDict.keys()))

# Randomly select a word from the key's list

wordIndex = random.randint(0,

len(wordDict[wordKey]) - 1)

return [wordDict[wordKey][wordIndex], wordKey]

This function returns a list containing the generated dictionary key and value.

Page 33: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Calling getRandomWord()

On line 156 we have two return values. This is

because we know that getRandomWord() returns

a list with two values.

secretWord, secretKey = getRandomWord(words)

Page 34: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Displaying the Secret Word

while True:

print('The secret word is in the

set: ' + secretKey)

displayBoard(HANGMANPICS, missedLetters,

correctLetters, secretWord)

Page 35: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Reading / Exercises

• Complete the exercises found on Intranet

under Game Development/Exercises:

– Link goes here

Page 36: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Python – 4.3

Portable Python and PyScripter

Page 37: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Objectives

• By the end of this unit you will be able to:

– Utilize Portable Python

– Create and execute scripts using Portable

Python and PyScripter

– Debug a program in PyScripter

– Identify types of errors

Page 38: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Portable Python

• A lightweight version of Python

• Can run directly from any USB storage

device.

• Can place multiple versions of Python on

same drive.

– Great for testing

• Comes with PyScripter IDE (see next

slide)

Page 39: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

PyScripter IDE

• What is an IDE

– Integrated Development Environment –

Toolset for creating computer programs.

• Easy to use

• Significantly better than IDLE (in my

opinion)

• Powerful debugging features

Page 40: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

The PyScripter Interface

Page 41: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Using PyScripter (and Debugging)

• Watch video

– PyScripter Video

• Instructor needs to download this video

Page 42: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Programming Bugs

• Bug - Errors in a computer program.

• Originated by an actual insect that caused

a computer crash in 1946.

Page 43: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Types of Bugs • Types of bugs:

– Syntax Errors Caused by invalid use of syntax of typos.

– Runtime Errors Errors that happen while the program is running/executing.

– Semantic Errors The program is not doing what the programmer intended.

• THIS IS WHY WE TEST OUR PROGRAMS EXTENSIVELY!!!

Page 44: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Syntax Error

• Types of bugs:

– Syntax Error - are a type of bug that comes

from:

• Typos in your program.

• Incorrect use of the syntax of the language.

– A Python program with even a single syntax

error will not run.

Page 45: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Runtime Errors

– Runtime Error - Errors that happen while the

program is running/executing.

– The program will work up until it reaches the

line of code with the error, and then the

program terminates with an error message

(this is called crashing).

– The Python interpreter will display something

called a "traceback" and show the line where

the error occurred.

Page 46: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Semantic Errors

• Semantic Errors – The program appears to work, but it is not doing what the programmer intended.

• For example: – if the programmer wants this:

• total = a + b

– but actually enters • total = a * b.

• THIS IS WHY WE TEST OUR PROGRAMS EXTENSIVELY!!!

Page 47: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Reading / Exercises

• Complete the exercises found on Intranet

under Game Development/Exercises:

– Link goes here

Page 48: Python Unit 4 - CoderPete.com · Python - Unit 3 Python Unit 4 4.1 ... Python - Unit 3 Reading / Exercises ... Python - Unit 3 The New getRandomWord() Function

Python - Unit 3

Unit Exam