Loops: Compound Interest

Classwork:
CompoundInterest_YI.py: Use a while loop to calculate how many years it would take to have an accumulated total of at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account.

Homework:
CompoundIntTable_YI.py: Use a while loop to show how the investment increases as the accumulated total becomes at least $1,100 at an interest rate of 1.2% when $1,000 is deposited in a savings bank account.

Welcome to THE INVESTMENT TABLE

year  1  interest for this year  12.0  total accumulated up to this year  1012.0
year  2  interest for this year  24.144000000000005  total accumulated up to this year  1024.144
year  3  interest for this year  36.433727999999974  total accumulated up to this year  1036.433728
year  4  interest for this year  48.870932735999986  total accumulated up to this year  1048.870932736
year  5  interest for this year  61.45738392883209  total accumulated up to this year  1061.457383928832
year  6  interest for this year  74.19487253597799  total accumulated up to this year  1074.194872535978
year  7  interest for this year  87.08521100640974  total accumulated up to this year  1087.0852110064097
year  8  interest for this year  100.13023353848666  total accumulated up to this year  1100.1302335384867

Number of years for the investment of $1000 to reach at least a value of $1,100 with an interest rate of 1.2% is  8

Flowchart 3

Class work:
Make sure you did the following:

  1. Flowcharts for single “if” and uploaded to edmodo.com.
  2. Flowcharts for single “if/else” and uploaded to edmodo.com.
  3. Flowcharts for single “while“. Check your email for a google doc. Upload it to edmodo.com.
  4. Flowcharts for YI_isitRight.py. Upload it to edmodo.com.
  5. Draw your a flowchart from one of your programs.

 

Homework : The “while” with a counter – use the program discussed in class to work on this assignment.

 

Loops: prime_numbers_YI.py

Assignment:
Write a program, prime_numbers_YI.py that prompts the user for an integer and then prints all the prime numbers up to that number. Prime numbers are numbers that are only divisible by itself and the number 1.
Note: 1 is not a prime number
Example: if the user enters 15, the output should look like this

Up to what number would you like to display all prime numbers? 15
All the prime numbers from 2 to 15 are:
2
3
5
7
11
13

screen-shot-2016-10-11-at-1-18-54-pm

Loops: permutation and combinations

O

Class work:

Some probability problems required the used of factorial in a different way.To calculate the number of sets that can be created from selecting in order r number of objects from n number of objects is:
Permutations
permutations
An example: reorder 5 books 2 at a time. Here n is 5 and r is 2.
Write a python program YI_permutations.py to calculate this number given n and r. Prompt the user for n and r.
combinations
Write a python program Combinations_YI.py to calculate this number given n and r. Prompt the user for n and r.

Conditionals: Nested if/else structures

Test for multiple cases by placing if/else structures inside other if/else selection structures.
Here is a good example using pseudocode:
Print A for exam grades greater than or equal to 90, B for grades between 80 and 89, C for grades between 70 and 79, D for grades between 60 and 69 and F for all other grades.

if student's grade is greater than or equal to 90
        print "A"
   else
        if student's grade is greater than or equal to 80 
             print "B"
        else
             if student's grade is greater than or equal to 70
                  print "C"
             else
                  if student's grade is greater than or equal to 60
                       print "D"
                  else
                       print "F"

Here is a program snippet:

if grade >= 90:
   print ("A")
else:
   if grade >= 80:
      print ("B")
   else:
   ...

It can also be written in this format:

if grade >= 90:
   print ("A")
elif grade >= 80:
   print ("B")
elif ...

Question:

1. Would the program still work as intended if the symbol >= was changed to <= ???

2. Can I write this program as follows?

if grade >= 90:
   print "A"
if grade >= 80 and grade < 90:
   print "B"
if grade >= 70 and grade < 80:
   print "C"
if ...

3. Can you come up with a different way of writing the program and still in an efficient way?

Here is a flowchart for this structure:

gralNestedIfElseStruct

Here is the starting of the flowchart for the grade assignment:

partialNestedIfElse

Assignments:

  1. Finish the flowchart
  2. Write a program, letter_grade_YI.py. This python program prompts the user for a numeric grade and prints the letter grade.
  3. Write an efficient program, many_letter_grades_YI.py as you discovered in the previous post. This python program prompts the user for a numeric grade and prints the letter grade. Additionally, it continues to prompt the user until the user says “n” to quit.
  4. BEFORE YOU START CODING, DRAW THE FLOWCHART, and don’t start coding until I check it.

Loop: TimesTables.py

1. Write a python program, TimesTables_YI.py to display a two dimensional table of the product of two numbers from 1 to 10. The output should look like this:

 
  1   2   3   4   5   6   7   8   9  10
  2   4   6   8  10  12  14  16  18  20
  3   6   9  12  15  18  21  24  27  30
  4   8  12  16  20  24  28  32  36  40
  5  10  15  20  25  30  35  40  45  50
  6  12  18  24  30  36  42  48  54  60
  7  14  21  28  35  42  49  56  63  70
  8  16  24  32  40  48  56  64  72  80
  9  18  27  36  45  54  63  72  81  90
 10  20  30  40  50  60  70  80  90 100
>>> 

A little challenge:

|   1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10
_____ _____ _____ _____ _____ _____ _____ _____ _____ _____
|   1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10
|   2 |   4 |   6 |   8 |  10 |  12 |  14 |  16 |  18 |  20
|   3 |   6 |   9 |  12 |  15 |  18 |  21 |  24 |  27 |  30
|   4 |   8 |  12 |  16 |  20 |  24 |  28 |  32 |  36 |  40
|   5 |  10 |  15 |  20 |  25 |  30 |  35 |  40 |  45 |  50
|   6 |  12 |  18 |  24 |  30 |  36 |  42 |  48 |  54 |  60
|   7 |  14 |  21 |  28 |  35 |  42 |  49 |  56 |  63 |  70
|   8 |  16 |  24 |  32 |  40 |  48 |  56 |  64 |  72 |  80
|   9 |  18 |  27 |  36 |  45 |  54 |  63 |  72 |  81 |  90
|  10 |  20 |  30 |  40 |  50 |  60 |  70 |  80 |  90 | 100


Conditionals and loops: Rock, paper, scissors

2. Write a pyhton program, RoSciPa_YI.py that plays the rock-paper-scissors game against the computer. When played between two people, each person picks on e of three options (usually shown by a hand gesture) at the same time, and a winner is determined.

In the game, rock beats scissors, scissors beats paper, and paper beats rock. The program should randomly choose one of the three options (without revealing it), then ask for the user’s selection. At that point, the program reveals both choices and prints a statement indicating that the user won, that the computer won, or that it was a tie. Keep playing until the user chooses to stop, then print the number of user wins, losses, and ties.

rock-paper-scissors-freebie

Format: Histogram

# Creating a histogram from a list of values.

int_values = []   # a list of values

# input 8 integers from user
print ("Enter 8 integers between the values of 1 and 10:")

for i in range( len(int_values) ):
   new_value = int( input( "Enter integer %d: " % ( i + 1 ) ) )
   int_values += [ new_value ]

# create histogram
print ("\nCreating a histogram from int_values:")
print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ))

for i in range( len( int_values ) ):
   print ("%7d %10d  %s" % ( i, int_values[ i ], "*" * int_values[ i ] ))

Input/Output:

Enter 8 integers between the values of 1 and 10:
Enter integer 1: 1
Enter integer 2: 3
Enter integer 3: 4
Enter integer 4: 6
Enter integer 5: 5
Enter integer 6: 4
Enter integer 7: 3
Enter integer 8: 2

Creating a histogram from int_values:
Element      Value  Histogram
      0          1  *
      1          3  ***
      2          4  ****
      3          6  ******
      4          5  *****
      5          4  ****
      6          3  ***
      7          2  **
>>> 

Loops – “while” and “if/else” structures

Visit the site below to learn about new topics:
• import statements
• Modules
• The randint() function
• for statements
• Blocks
• The str(), int(), and float() functions
• Booleans
• Comparison operators
• Conditions
• The difference between = and ==
• if statements
• break statements

screen-shot-2016-10-05-at-4-44-45-am

Open the post “Lesson Questions” to submit all the work we learn in class.
Write a new program, guess_num_YI.py based on guess.py but without the “break” instruction. This program plays the game of “guess the number” as follows: Your program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then displays:

I have a number between 1 and 1000.
      Can you guess my number?
      Please type your first guess.

The player then types a first guess. The program responds with one of the following:

 1. Excellent! You guessed the number! You guessed in 4 tries.
       Would you like to play again (y/n)?
    2. Too low. Try again.
    3. Too high. Try again.

If the player’s is incorrect, your program should loop until the player finally gets the number right. Your program should keep telling the player Too high or Too low to help the player “zero in” on the correct answer. After a game ends, the program should report the number of games the player played and prompt the user to enter “y” to play again or “n” to exit the game.

Random numbers:

###################################################################
# Mrs. Elia
# 10/21
# python 3.7
# Description: How to generate pseudorandom numbers
#
###################################################################

import random

yesNo = input("would you like a random number?y/n ")

while yesNo == "y":
    print (random.randrange(1,7))
    yesNo = input("would you like a random number?y/n ")
print ("goodbye")

##>>>
##would you like a random number?y/n y
##5
##would you like a random number?y/n y
##4
##would you like a random number?y/n y
##3
##would you like a random number?y/n

 

For next assignment search in the internet for the Richter magnitude scale and write a program, Richter_Scale_YI.py that prompts for the number scale and prints the description of the earthquake intensity: micro, minor, light, moderate, strong, major and great. Use nested if/else statements.

Loops: Powers of Ten

Assignment:
Write a program, powers_of_ten_YI.py that prints the powers of ten using the “for” loop.

>>> 
What is the exponent for the powers of ten? 20
1.0
10.0
100.0
1000.0
10000.0
100000.0
1000000.0
10000000.0
100000000.0
1000000000.0
10000000000.0
100000000000.0
1000000000000.0
10000000000000.0
100000000000000.0
1000000000000000.0
1e+16
1e+17
1e+18
1e+19
>>> 


Loops: Asterisks

Write a program, Asterisks_YI.py that prints the following pattern separately, one below the other each pattern separated front he next by one blank line. Use nested for loops ONLY to generate the patterns. All asterisks (*) should be printed by a single statement of the form

print(‘*’),

which causes the asterisks to print side by side separated by a space.
Hint: The last two patterns require that each line begin with an appropriate number of blanks.

##a.
##*
##**
##***
##****
##*****
##******
##*******
##********
##*********
##**********
##
##b.
##**********
##*********
##********
##*******
##******
##*****
##****
##***
##**
##*
##
##c.
## **********
##  *********
##   ********
##    *******
##     ******
##      *****
##       ****
##        ***
##         **
##          *
##
##d.
##          *
##         **
##        ***
##       ****
##      *****
##     ******
##    *******
##   ********
##  *********
## **********

Some help:

for i in range(5):
    print('*',end=' ' )
print(' ')
for j in range(5):
    print('*',end=' ')
print('')

not-nested for loops
* * * * *  
* * * * * 

print('nested for loops')
for i in range(5): #outer
    for j in range(5):  #inner
        print('*',end=' ')
    print('')

nested for loops
* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * * 
>>> 

Extra Credit: Combine your code from the four separate problems into a single program that prints all four patterns side by side by making clever use of nested for loops. For all parts of this program – minimize the number of statements that print these characters.

asterisksPatterns

 

Loops: Nested Loops Challenge

Classwork:

Challenge Assignment:

##This program will display the products of two numbers from 1 to 10
##in the form of a two-dimensional table.
##   1 |    2 |    3 |    4 |    5 |    6 |    7 |    8 |    9 |   10 | 
##______ ______ ______ ______ ______ ______ ______ ______ ______ ______ 
##   1 |    2 |    3 |    4 |    5 |    6 |    7 |    8 |    9 |   10 | 
##   2 |    4 |    6 |    8 |   10 |   12 |   14 |   16 |   18 |   20 | 
##   3 |    6 |    9 |   12 |   15 |   18 |   21 |   24 |   27 |   30 | 
##   4 |    8 |   12 |   16 |   20 |   24 |   28 |   32 |   36 |   40 | 
##   5 |   10 |   15 |   20 |   25 |   30 |   35 |   40 |   45 |   50 | 
##   6 |   12 |   18 |   24 |   30 |   36 |   42 |   48 |   54 |   60 | 
##   7 |   14 |   21 |   28 |   35 |   42 |   49 |   56 |   63 |   70 | 
##   8 |   16 |   24 |   32 |   40 |   48 |   56 |   64 |   72 |   80 | 
##   9 |   18 |   27 |   36 |   45 |   54 |   63 |   72 |   81 |   90 | 
##  10 |   20 |   30 |   40 |   50 |   60 |   70 |   80 |   90 |  100 |

For loop and random: Whack a Mole

Assignment:
Write a program, whack_a_mole_YI.py to emulate the arcade game.

kitty-whack-a-mole1

Use the random feature of the python math library to randomly select a number between 1 and 3 inclusive.
screen-shot-2016-10-24-at-12-47-48-pm

Prompt the user for a number between 1 and 3.
screen-shot-2016-10-24-at-12-47-34-pm

You whacked the mole if you guess the right number!!
screen-shot-2016-10-24-at-12-47-20-pm

Keep track of how many times you play and how many times you whack the mole and display them as scores with a good message, “Great”, “Not so good”, “Booooo”.

Hint: Can use this code to get you started?

#>import random
#>for i in range(10):
#   print(random.rantint(1,3))
#
#1
#3
#3
#2
#3
#1
#2
#1
#1
#1

Advanced: Computer Number Systems – Part 1

Computer Number Systems – Part 1

NumberSysConvEx
NumberSysConvEx2

NumberSysExercises

Prof. Joseph J. LaViola Number System Resources

Since binary numbers representing moderate values quickly become rather lengthy, bases eight (octal) and sixteen (hexadecimal) are frequently used as short-hand. Octal numbers group binary numbers in bunches of 3 digits and convert the triplet to a single digit between 0 and 7, inclusive.

Some online help on binary numbers

Classwork:Do the rest of the parts for each exercise.

Homework:
Work on Tic Tac Toe project.

Pi Day Activity

Screen Shot 2014-03-13 at 7.53.55 AM
Monday is Pi Day – We will have a pi-day activity ending on Monday
Starting today we are celebrating Pi day by preparing to write a program to do one of the following:
1. Calculate the digits of Pi to highest possible precision
2. Illustrate how Pi is used in a circle.
3. Illustrate how Pi can be applied.
4. Illustrate how Pi was discovered by telling an interactive story.

The programs will be judge based on ingenuity and/or creativity.
NOTE: You can use online resources to help you develop your program. There are good algorithms online. You can not use already written programs.
Include any links used for your resources.

If you like to memorize some of the digits of pi, there will be a competition on Friday. The student who can write the most digits without any help, get a small trophy.

Homework: Explore and investigate the uses and history of pi.
Tomorrow you will tell me what your program you will work on.

Advanced: Computer Number Systems – Part 2


Computer Number Systems – Part 2

All computers – from large mainframes to hand-held micros – ultimately can do one thing: detect whether an electrical signal is “on” or “off”. Computer programs in BASIC and Pascal are converted by various pieces of systems software into sequences of bits (Binary digITs) which correspond to sequences of on/off (equivalently TRUE/FALSE or 1/0) signals. Proficiency in the binary number system is essential to understanding how a computer works.

The Decimal Number System

NumberSysBase10Brk

NumberSysBase10

The Binary Number System

NumberSysBase2Brk

NumberSysBase2

Convert a Binary Number to Decimal Number

NumberSysConv2to10

The Hexadecimal Number System

NumberSysBase16Brk

The Octal Number System

NumberSysBase8

Converting between different Number Systems.

NumberSysConversion

NumberSysConvEx
NumberSysConvEx2

NumberSysExercises

Prof. Joseph J. LaViola Number System Resources

Since binary numbers representing moderate values quickly become rather lengthy, bases eight (octal) and sixteen (hexadecimal) are frequently used as short-hand. Octal numbers group binary numbers in bunches of 3 digits and convert the triplet to a single digit between 0 and 7, inclusive.

NumberSysExercises2

Some online help on binary numbers

Classwork:Do parts a and b for each exercise.

Work on Tic Tac Toe project.

List: Intro


working with lists

Classwork:
Write a new program, ListClwk_YI.py with the work develop in class.
1. Create a list, aList of 100 integers from 1 through 100.

Some tricks you should know:

total = 0
for i in range( len( aList ) ):
   total += aList[i]
print ("the sum of all items in the list is ", total)

total = 0
for item in aList:
   total += item
print ("the sum of all items in the list is ", total)

print ("the sum of all items in the list is ", sum(aList))


2. Create an empty list and adds to the end of the list 100 random integers from 10 to 500
3. Print the list in 10 rows by 10 columns format. Make sure the columns are lined up.
4. Count the number of integers that are even and odd and displays the values with a message.

List: Basic Assignments


Write a python program, list_basic_assigments_YI.py
1. Create a_list and assign 20 random integer numbers between 50 and 75.
2. Create a new_list with 20 random integer numbers between 61 and 91.
3. Create another list, newer_list whose items are the sum of each item on the lists a_list and new_list
4. Create a histogram from a list of values.

# Creating a histogram from a list of values.

int_values = []   # a list of values

# input 8 integers from user
print ("Enter 8 integers between the values of 1 and 10:")

for i in range( len(int_values) ):
   new_value = int( input( "Enter integer %d: " % ( i + 1 ) ) )
   int_values += [ new_value ]

# create histogram
print ("\nCreating a histogram from int_values:")
print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ))

for i in range( len( int_values ) ):
   print ("%7d %10d  %s" % ( i, int_values[ i ], "*" * int_values[ i ] ))


5. Create and display a histogram from a list of 10 random integer values between 5 and 9.
6. Use a list to solve the following problem: “Read in” 6 numbers. As each number is read, print it only if it is not a duplicate of a number already read.

Required Submission
1. Copy and paste the programs in the Text Entry tab.
2. Submit the list_basic_assigments_YI.py or the repl.it link.
NOTE: Documentation
Header:
a) Assignment description ( you can copy and paste the assignment itself)
b) Author’s name
c) Language and version
d) Date of completion
Input/Output:
Input(If any) and output for each part.

List: python’s basic concepts in lists


python’s basic concepts in lists
Write a python program list_basics_YI.py

  1. Creating a list.
  2. add elements to a list
  3. access a list’s values by iteration
  4. access a list’s values by index
  5. modify elements in a list
  6. add all elements in a list
  7. assign 100 random integer numbers between 1 and 100 to a new empty list, new_list
# 1. Creating a list.

a_list = []    # create empty list

# 2. add elements to a list
for number in range( 1, 11 ):
   a_list += [ number ]

print ("The values of a_list are:", a_list )  

# 3. access a list's values by iteration
print ("\nAccessing values by iteration:")

for item in a_list:
   print (item,end='')
print("\n")

# 4. access a list's values by index
print ("\nAccessing values by index:")
print ("Subscript   Value")

for i in range( len( a_list ) ):
   print ("%9d %7d" % ( i, a_list[ i ] ))

# 5. modify elements in a list
print ("\nModifying a list value...")
print ("Value of aList before modification:", a_list)
a_list[ 0 ] = -100   
a_list[ -3 ] = 19
print ("Value of aList after modification:", a_list)

# 6. add all elements in a list
total = 0
for i in range( len( a_list ) ):
   total += a_list[i]
print ("the sum of all items in the list is ", total)


# 7. assign random integer numbers between 1 and 100 to a new empty list, new_list

Required Submission
1. Copy and paste the programs in the Text Entry tab.
2. Submit the list_basics_YI.py or the repl.it link.
NOTE: Documentation
Header:

a) Assignment description ( you can copy and paste the assignment itself)
b) Author’s name
c) Language and version
d) Date of completion
Input/Output:
Input(If any) and output for each part.

List: Tutorial on list(range(10))

Lists:



More on for-loops and review of previous assignments.

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))

Assignments:
Write code snippets for the following specific sequence of integers using the range function:
NOTE: the lower and upper bounds are included in the lists.
a. A list of even integer numbers from 2 through 24.
b. A list of even integer numbers from 48 through 22.
c. A list of perfect square numbers from 1 through 100.
d. A list of numbers starting from -13 through 0.

Required Submission
Copy and paste the snippets and the output in the Text Entry tab.

NOTE: No need for documentation.

List: sum of all

Sum of all items in a list

More for loops

 

###################################
#
#  tally.py
#  
#  Mrs. Elia
#  12/12
#  for loops: find the sum of all the
#  numbers in the list
#
###################################


aSeq = [8,6,3,2,10]
tally = 0

for i in aSeq:
    tally += i
print ("The total of all the items in the list ", aSeq, "is ", tally)


##>>> 
##The total of all the items in the list  [8, 6, 3, 2, 10] is  29
##>>> 

Class work:

Write a python program, Tally1_YI.py to find the sum of the numbers from x to y where x and y are two numbers the user inputs. Your program should prompt the user for x and y. Make sure your program checks x is smaller than y.

Write a python program, Tally2_YI.py to find the sum and the average of the following list: [45,23,76,18,90,123,56,76,89,22,41,56]
The output should look like this:
The sum of all the items in this list [45,23,76,18,90,123,56,76,89,22,41,56] is xxx and the average is xxx.xx.

 

List: list to calculate salaries

Programming Project: Using a list to calculate salaries

Use a list to solve the following problem: A company pays its salespeople on a commission basis. The salespeople receive $200 per week, plus 9% of their gross sales for that week. For example, a salesperson who grosses $5000 in sales a week receives $200 plus 9% of $5000, or a total of $650. Write a program (using a list of counters) that determines how many of the salespeople earned salaries in each of the following ranges (assume that each salesperson’s salary is truncated to an integer amount):
a. $200-299
b. $300-399
c. $400-499
d. $500-599
e. $600-699
f. $700-799
g. $800-899
h. $900-999
i. $1000 and over
NOTE: DO NOT USE “if” STATEMENTS.

Input Data: (must use this data)
gross_sales_list = [5390, 4850, 5762, 333, 4104, 720, 2854, 5730, 7918, 6582, 7874, 8703, 4006, 2027, 9410, 6294, 6083, 1494, 7337, 8682, 340, 4390, 8900, 3620, 776, 7049, 238, 7415, 9946, 4154, 2109, 6935, 2421, 7448, 9452, 3494, 91, 3702, 9641, 3630, 7291, 8624, 692, 2256, 8121, 6127, 4849, 7830, 570, 8699, 5365, 6325, 8620, 2079, 3331, 2962, 9853, 7798, 4051, 413, 1571, 267, 1954, 5118, 3639, 3215, 2705, 3600, 8949, 3337, 583, 8117, 1867, 810, 8477, 3298, 8705, 9704, 3446, 4812, 2182, 6387, 9933, 8049, 587, 7256, 7898, 4939, 4715, 4323, 2583, 4188, 4567, 6409, 9110, 458, 3187, 9742, 6964, 8245]

Output:
Display the categories as above followed by the frequency for each of them. For example:
$200 – $299 14 **************
$300 – $399 8 *********
$400 – $499 10 **********
$500 – $599 15 ***************

Include in your output
– Any error messages that show why your program doesn’t work.
– An explanation related to the program failure if that is the case.