Introduction to Python

davidbpython.com




Projects, Session 2



PLEASE REMEMBER:

  1. re-read the assignment before submitting
  2. go through the checklist including the tests
  3. make sure your notations are as specified in the homework instructions

All requirements are detailed in the homework instructions document.

Careless omissions will result in reductions to your solution grade.

 
2.1 Notes typing assignment. Please write out this week's transcription notes. The notes are displayed as an image named transcription in each week's project files folder.

This does not need to be in a Python program - you can use a simple text file.

 
2.2 Reverse Number Guessor.

  • program generates a random number between 1 and 100 (see starter code below)
  • uses a repeating while True: loop (NOT A LOOP WITH A COMPARISON TEST) to repeatedly ask the user to input() a guess (or 'q' for quit)
  • if the user types 'q', the program breaks out of the while loop
  • if the user types a number, the program tells the user whether his or her guess is greater than, less than or equal to the randomly generated number (i.e. correct)
  • once correct, the program breaks out of the while loop
  • at the bottom of the while True: block the program loops back and allows the user to guess again. This can happen repeatedly until correct
  • count the number of guesses by using an integer counter that is initialized above the loop and incremented inside the loop. If the user guesses correctly, this value is reported.

(Why is this a "reverse" guessor? The classic Number Guessor reverses the roles of guessor and guessee - see extra credit / supplementary.)

Starter Code:
import random

number_to_guess = random.randint(1,100)          # int, 81 (put in a sample value here,
                                                 #          then use for notations below)
Sample program runs:
I am thinking of a number from 1 to 100.   Try to guess it and
I'll give you hints about it.

Your guess?  (q to quit):  50
your guess is LOWER than the number I'm thinking of.

Your guess?  (q to quit):  75
your guess is LOWER than the number I'm thinking of.

Your guess?  (q to quit):  87
your guess is HIGHER than the number I'm thinking of.

Your guess?  (q to quit):  81
you got it!  You guessed it in 4 tries.
I am thinking of a number from 1 to 100.   Try to guess it and
I'll give you hints about it.

Your guess?  (q to quit):  40
your guess is HIGHER than the number I'm thinking of.

Your guess?  (q to quit):  20
your guess is HIGHER than the number I'm thinking of.

Your guess?  (q to quit):  10
you got it!  You guessed it in 3 tries.
I am thinking of a number from 1 to 100.   Try to guess it and
I'll give you hints about it.

Your guess?  (q to quit):  50
your guess is HIGHER than the number I'm thinking of.

Your guess?  (q to quit):  q
You chose to quit.  Have a great day!

NOTE 1: if your program loops endlessly ("infinite loop") then click the red square at the left of the run window in PyCharm to break out of it. NOTE 2: some designs immediately convert the user's guess to int() but then can't compare to 'q'. Resolve this by comparing to 'q' first, then converting to int(). NOTE 3: this is a potentially tricky assignment and some students spend too much time trying to get it to work. If you find yourself spending over an hour trying to work out the logic, take a look at the Project Discussion for commentary and an outline. BONUSES: for an added challenge (not required) you may consider these two goals:

  • input() is taken only once
  • invalid input (not all digits, and not 'q') is rejected and the user is given a chance to guess again
  • the int() function is called only once
  • the counter is incremented (i.e. c = c + 1) only once
Generally we try to follow the DRY principle: Don't Repeat Yourself. Avoiding repetition means that if we want to change how an operation works, we only need to change it in one place.
HOMEWORK CHECKLIST: all points are required
    testing: you have run the program with the sample inputs as shown and are seeing the output exactly as shown (contact me if your output is different and you're unable to adjust to match)

    the guessing takes place in a while True loop so it can happen repeatedly

    the user's guess is compared to the random number, not a fixed number (at the time we run the program, we don't know what the number will be)

    if the user types 'q' or guesses correctly, the program breaks out of the while loop, it does not exit()

    if testing for .isdigit() (not required), code does not compare to True (i.e., 'if x.isdigit() != True'). Instead, say if x.isdigit(): or if not x.isdigit():

    there are no extraneous comments or "testing" code lines

    program follows all recommendations in the "Code Quality" handout

    (extra credit / supplementary): the program counts how many times the user guessed

 
2.3 Text replacement utility.

  • Start with the string assigned in the starter code (see below).
  • Use two calls to input() for the user to input two strings: one for target text and the other for replace text.
  • The program replaces any word or phrase in the text string, and then outputs the same text string after the replacements have been made.
  • It also reports the number of replacements that were made.

  • Starter Code:
    sample_text = """And since you know you cannot see yourself,
    so well as by reflection, I, your glass,
    will modestly discover to yourself,
    that of yourself which you yet know not of."""
    
    # [YOUR CODE GOES HERE]
    
    Sample program run:
    please enter search text:  yourself
    please enter replace text:  your glass
    
    And since you know you cannot see your glass,
    so well as by reflection, I, your glass,
    will modestly discover to your glass,
    that of your glass which you yet know not of.
    
    3 replacements made.
    Sample program run:
    please enter search text:  yourself
    please enter replace text:  your Corgi
    
    And since you know you cannot see your Corgi,
    so well as by reflection, I, your glass,
    will modestly discover to your Corgi,
    that of your Corgi which you yet know not of.
    
    3 replacements made.

    Please note that you do not need to notate the entire long string value. Just show the first 10-15 characters followed by an ellipsis (...).
    HOMEWORK CHECKLIST: all points are required


        testing: you have run the program with the sample inputs as shown and are seeing the output exactly as shown (contact me if your output is different and you're unable to adjust to match)

        the count when running the program with the inputs in the first example is correct (should be 3, not 4)

        there are no extraneous comments or "testing" code lines

        program follows all recommendations in the "Code Quality" handout

        the program uses f'' strings to combine numbers with strings, or strings with other strings

        no need to notate the entire string value -- just show first 10-15 characters followed by an ellipsis (...)


     

    EXTRA CREDIT / SUPPLEMENTARY

     
    2.4 (Extra credit / supplementary) Count from 0 up to 100 by 2's (or 3's or 4's, or any number...). Use input() to take one input from the user: an integer "step" value. Then use a while: loop to print out all the values from 0 up to 100 (or less than 100 if the step value doesn't divide evenly into 100).

    Note that the while will not use True as a test, but instead the value of a counter that eventually reaches 100. Please see slides for examples of a while loop that does not use True as a test. Do not use 'break' for this solution. The 'while' test must control.

    Sample program runs:
    please enter an integer:  3
    counting from 0 to 100 by 3's
    0
    3
    6
    9
    12
    15
    ... (etc., up to 99) ...
    92
    96
    99
    please enter an integer: 25
    counting from 0 to 100 by 25's
    0
    25
    50
    75
    100

    Note that if you're having troubling making the count start at 0 or stop counting below 100, consider the order of printing and increasing the value - which should come first?

     
    2.5 (Extra credit / supplementary) Sum a sequence of integers. Use input() to take a value, and convert to int. Use a while loop to sum up all integers between 0 and the submitted value.

    Note that the while will not use True as a test, but instead the value of a counter that eventually reaches and the submitted value. Please see slides for examples of a while loop that does not use True as a test. Do not use 'break' for this solution. The 'while' test must control.

    please enter an int:  2
    sum from 1 to 2 is 3
    please enter an int:  3
    sum from 1 to 3 is 6
    please enter an int:  4
    sum from 1 to 4 is 10
    please enter an int:  5
    sum from 1 to 5 is 15




     
    2.6 (Extra credit / supplementary) Number Guessor. Write a program that attempts to guess a number from 1 to 100 that the user has chosen and is keeping secret. To guess the number, the program asks the user a series of guesses and questions, narrowing down the possibilities by half each time. The program will:

    a. Ask the user to think of a number from 1 to 100 b. Ask the user if the number is 50 (i.e., halfway between 1 and 100 c. If the user answers "no", ask the user if the number is higher or lower than 50 d. If lower, ask the user if the number is 25 (i.e., halfway between 1 and 50) e. If higher, ask the user if the number is 75 (i.e., halfway between 50 and 100) f. Return to question c -- if the guess is incorrect, ask the user if the number is higher or lower than 25 (or 75) g. Continue halving the possibiltiies and guessing the number until the user reports that the guess is correct.

    Sample program run:
    Think of a number between 100 and 0, and I will try to guess it.
    Hit [Enter] to start.
    is it 50 (yes/no/quit)?  no
    is it higher or lower than 50?  higher
    is it 76 (yes/no/quit)?  no
    is it higher or lower than 76?  lower
    is it 63 (yes/no/quit)?  no
    is it higher or lower than 63?  lower
    is it 57 (yes/no/quit)?  no
    is it higher or lower than 57?  lower
    is it 54 (yes/no/quit)?  no
    is it higher or lower than 54?  lower
    is it 52 (yes/no/quit)?  no
    is it higher or lower than 52?  lower
    is it 51 (yes/no/quit)?  yes
    I knew I could do it!




     
    2.7 (Extra credit / supplementary) Use while to find prime numbers in a range of numbers. Ask the user for an integer, and display all prime numbers between 2 and the user's number. (Note this assignment must use while and not range(), to highlight this week's features.)
    Sample program runs:
    * Prime Numbers *
    Please enter max integer:  5
    
    2
    3
    5
    
    * Prime Numbers *
    Please enter max integer:  20
    
    2
    3
    5
    7
    11
    13
    17
    19




     
    2.8 (Extra credit / supplementary) Chicken, Fox and Grain game. This is a rather lengthy assignment using while, break and continue, as well as numerous if tests comparing strings and numbers. (In fact, it requires a great deal more if/then/else than might be needed if we were to use some upcoming Python features. But, it provides an interesting challenge using this sessions's features.)

    The program is an implementation of a well-known logic puzzle: A farmer has to transport a fox, a chicken and a bag of grain across a river using a rowboat, but the rowboat has room for only one of the items besides the farmer. Therefore when crossing the river, the farmer usually has to leave two of the items alone on one of the shores (the farmer can also cross alone in the boat). The problem is that if the fox is left alone with the chicken, the fox will eat the chicken, and if the chicken is left alone with the grain, the chicken will eat the grain. How can the farmer move all three items across the river without losing any of them?

    Sample program runs:
    **THE FOX, THE CHICKEN AND THE GRAIN**
    
    You are on the east bank of a river.
    You must transport a fox, a chicken
    and a bag of grain to the west bank.
    However, you can only carry one item
    at a time.  Good luck!
    
    you now are on the east bank.
    the chicken is on the east bank.
    the fox is on the east bank.
    the grain is on the east bank.
    
    What would you carry in the seat of the boat ([Enter] for nothing,
    q to quit)?  xx
    
    sorry, I don't recognize 'xx'.  Try again.
    
    you now are on the east bank.
    the chicken is on the east bank.
    the fox is on the east bank.
    the grain is on the east bank.
    
    What would you carry in the seat of the boat ([Enter] for nothing,
    q to quit)?  [pressed Enter alone, meaning carry nothing]
    
    oops, the fox got the chicken!
    **THE FOX, THE CHICKEN AND THE GRAIN**
    
    You are on the east bank of a river.
    You must transport a fox, a chicken
    and a bag of grain to the west bank.
    However, you can only carry one item
    at a time.  Good luck!
    
    you now are on the east bank.
    the chicken is on the east bank.
    the fox is on the east bank.
    the grain is on the east bank.
    
    What would you carry in the seat of the boat ([Enter] for nothing,
    q to quit)?  fox
    
    oops, the chicken got the grain!
    **THE FOX, THE CHICKEN AND THE GRAIN**
    
    You are on the east bank of a river.
    You must transport a fox, a chicken
    and a bag of grain to the west bank.
    However, you can only carry one item
    at a time.  Good luck!
    
    you now are on the east bank.
    the chicken is on the east bank.
    the fox is on the east bank.
    the grain is on the east bank.
    
    What would you carry in the seat of the boat ([Enter] for nothing,
    q to quit)?  chicken
    
    ...carrying the chicken to the west bank...
    
    you now are on the west bank.
    the chicken is on the west bank.
    the fox is on the east bank.
    the grain is on the east bank.
    
    What would you carry in the seat of the boat ([Enter] for nothing,
    q to quit)?  [pressed Enter alone, meaning carry nothing]
    
    ...traveling to the east bank...
    
    you now are on the east bank.
    the chicken is on the west bank.
    the fox is on the east bank.
    the grain is on the east bank.
    
    What would you carry in the seat of the boat ([Enter] for nothing,
    q to quit)?  fox
    
    ...carrying the fox to the west bank...
    
    you now are on the west bank.
    the chicken is on the west bank.
    the fox is the west bank.
    the grain is on the east bank.
    
    What would you carry in the seat of the boat ([Enter] for nothing,
    q to quit)?  [pressed Enter alone, meaning carry nothing]
    
    oops, the fox got the chicken!
     
    [pr]