knerr cs21 notes...

back to schedule

WEEK06: indefinite (while) loops, strings as objects, random, more functions...
---------------------------------------------------------------
 F: strings as objects, lists, and random

STRINGS as objects:

 - see stringOps.py for an example of how to use the str class methods

 - type help(str) during an interactive python session to see all
   of the different string methods

 - what does the strip() method do?

 - how can you use the str methods to write a robust input function
   like getmenuoption?

$  python getmenuoption.py

What do you want to do next?
 1. Spin the Wheel
 2. Buy a Vowel
 3. Guess the Puzzle
 4. Quit, I can't stand this game anymore!

Enter your choice: hello
Hey, hello isn't a valid option.  Try again...
Enter your choice: a
Hey, a isn't a valid option.  Try again...
Enter your choice: -3
Hey, -3 isn't a valid option.  Try again...
Enter your choice: 5
Hey, 5 isn't a valid option.  Try again...
Enter your choice: 2

GetMenuOption returned: 2


LISTS as objects:
 
 - see listOps.py for examples of using list methods

 - type help(list) during an interactive python session to see all
   of the different list methods


RANDOM:

 - see randOps.py for examples of using the random library

>>> from random import *
>>> randrange(10)
3
>>> randrange(10)
4
>>> randrange(10)
7
>>> random()
0.016396322052558476
>>> random()
0.6342173978301141
>>> random()
0.49443063887292016
>>> 

 - how can we use randrange(2) to simulate a coin flip?

 - can you write a program to do 1000 coin flips and keep
   track of how many heads and how many tails you get?

$ python coinflip.py 

heads = 509 (50.9%)
tails = 491 (49.1%)

$ python coinflip.py 

heads = 502 (50.2%)
tails = 498 (49.8%)

$ python coinflip.py 

heads = 486 (48.6%)
tails = 514 (51.4%)