Difference between revisions of "CSC111 Lab 8 2015"
Line 24: | Line 24: | ||
</source> | </source> | ||
<br /> | <br /> | ||
− | Complete the function '''getPositiveNumber() | + | Complete the function '''getPositiveNumber()''' so that it asks the user for a number larger than 0, and keeps on prompting the user as long as she doesn't enter a valid number. |
Below is an example of the interaction between computer and user. | Below is an example of the interaction between computer and user. |
Revision as of 13:23, 22 March 2015
--D. Thiebaut (talk) 14:10, 22 March 2015 (EDT)
<showafterdate after="20150325" before="20150601">
Part 1: While Loops
Exercise 1: Robust Input with While
def getPositiveNumber(): # # put your code here # def main(): # Part 1, Exercise 1 x = getPositiveNumber() print( "getPositiveNumber() returned", x ) main()
Complete the function getPositiveNumber() so that it asks the user for a number larger than 0, and keeps on prompting the user as long as she doesn't enter a valid number.
Below is an example of the interaction between computer and user.
Please enter a number greater than 0: -1 -1 is invalid. Please enter a number greater than 0: -3 -3 is invalid. Please enter a number greater than 0: 0 0 is invalid. Please enter a number greater than 0: 20 getPositiveNumber() returned 20 >>>
Exercise 2: Ask for Yes/No answer
Same idea as in Exercise 1, but this time the new function, called getYesNo() will keep on asking a question until the user's input is "YES", "yes", "y", "NO", "no", or "n". Any combination of lower/upper case in the spelling is accepted ("yES" is valid).
- Source
def getYesNo(): # # put your code here # def main(): # Part1, Exercise 2 likesChoco = getYesNo() if likesChoco in ["YES", "Y" ]: print( "Me too!" ) else: print( "Sorry to hear that!" ) main()
- Example output
Do you like chocolate (Y/N)? possibly please enter by 'Yes' or 'No' Do you like chocolate (Y/N)? I don't know please enter by 'Yes' or 'No' Do you like chocolate (Y/N)? Oui please enter by 'Yes' or 'No' Do you like chocolate (Y/N)? y Me too!
</showafterdate>