Game Development Reference
In-Depth Information
11 - Bagels
>>> ' '.join(['My', 'name', 'is', 'Zophie'])
'My name is Zophie'
How the Code Works: Lines 29 to 53
We need a couple more functions for our game to use. The first is a function that will tell
us if the guess that the player entered is a valid integer. Remember that the input()
function returns a string of whatever the player typed in. If the player enters in anything but
numbers for their guess, we want to ask the player again for a proper guess.
The second function is something we've seen before in previous games. We want a
function that will ask the player if they want to play the game again and from the player's
response, figure out if it was a Yes or No answer.
Checking if a String Only has Numbers
29. def isOnlyDigits(num):
30. # Returns True if num is a string made up only of
digits. Otherwise returns False.
31. if num == '':
32. return False
The isOnlyDigits() is a small function that will help us determine if the player
entered a guess that was only made up of numbers. To do this, we will check each
individual letter in the string named num and make sure it is a number.
Line 31 does a quick check to see if we were sent the blank string, and if so, we return
False .
34. for i in num:
35. if i not in '0 1 2 3 4 5 6 7 8 9'.split():
36. return False
37.
38. return True
We use a for loop on the string num . The value of i will have a single character from
the num string on each iteration. Inside the for-block, we check if i does not exist in the list
returned by '0 1 2 3 4 5 6 7 8 9'.split() . If it doesn't, we know that there is
a character in num that is something besides a number. In that case, we should return the
value False .
If execution continues past the for loop, then we know that every character in num is a
number because we did not return out of the function. In that case, we return the value
True .
 
Search WWH ::




Custom Search