Author Archives: graceliana@gmail.com

Welcome

Welcome to PHS and to a New School Year!!

In this class you will learn the python programming syntax

######################################
#
# Hello World: most popular program ever written!!
# GE
# 9/7/2055
# python 3.x
#
#####################################


print("Hello world")
print("What is your name?")
myName = input()
print("It is good to meet you, " + myName)


##>>> 
##>>> 
##Hello world
##What is your name?
##Alice
##It is good to meet you, Alice
##>>> 

Write programs to run an application like the one below:

A mail-order house sells five products whose retail prices are as follows:  Product 1, $2.98; product 2, $4.50; product 3, $9.98; product 4, $4.49 and product 5, $6.87. 

Choose from the following:
Product number?: 1
Quantity?: 2
Do you want to continue?(yes/no): yes
Product number?: 2
Quantity?: 5
Do you want to continue?(yes/no): yes
Product number?: 3
Quantity?: 3
Do you want to continue?(yes/no): yes
Product number?: 4
Quantity?: 1
Do you want to continue?(yes/no): no
Total Price: $62

or a program to calculate prime numbers

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

write graphic oriented programs
Screen Shot 2016-09-07 at 1.28.00 PM

and lastly, animations!
atari_pong_anim_np

python program, programming guidelines, and IDLE/repl.it

An introduction to the python shell either in IDLE or https://repl.it/

  1. Run IDLE or in the repl.it window
  2. Assigning a value to a variable
  3. Using the python shell as a calculator
  4. Printing a word
  5. Printing a number
  6. Printing the content of a variable
  7. Comparing two numbers
  8. comparing two variables

Writing your first python program:

  1. If you are using IDLE, create “My_Python_Programs” folder in Documents”
  2. If you are using IDLE or repl.it, create a new “Basic_Progrmas” folder in the “My_Python_Programs”
  3. Open a “new window”
  4. Write your first program using the algorithm to find the smallest and largest numbers in a set of 2 integer numbers. Program name: BasicInstructions_YI.py.
     
    NOTE: YI_ represents Your Initials.

Guidelines for writing programs
Every program has to have a header:

  1. Assignment description
  2. Author’s name
  3. Date
  4. Input and output as comments if they are part of the assignment
  5. If the program doesn’t run successfully, write a short paragraph as part of the program header explaining the problem.

Set of instructions:

  1. Comparing two numbers
  2. Deciding which number smaller and which one is larger

Let’s turn the English instructions into computer instructions:
 

###################################################################
# Mrs. Elia
# python 3.x
# Description: Basic instructions
###################################################################

name = input("Enter your name ")              # prompting the user 
print("Hello", name)                          # displaying a message

x = input("Enter a number ")                  # Assignment operator 
print ("The first number you entered is ",x ) # Why green and black?
y = input("Enter another number ")            # prompting for another number

print ("The two numbers you entered are",x,"and", y)  # printing multiple items

# Anything inside quotes is a "string" or text

###################################################################
#
#  Turn the "string" numbers into "integer" numbers to compare them
#
###################################################################

x = int(x)                                     # convert to string and assign
y = int(y)                                     # convert to string and assign

if x > y:                                   # compare x to y
    print (x, " is bigger than ",y)            # the comparison is true
else:
    print (y, " is bigger than ",x)            # the comparison is false

# end of program

What about if they are both equal to each other?
if x == y:
    print("They are both equal")
else:
if x > y:
        print (x, " is bigger than ",y)
    else:
        print (y, " is bigger than ",x)

simplestFlowChart

 

Concepts you learned
1. Variables as place holders
2. Keeping an eye on only two variables at a time

More concepts to learn
3. Pseudocode
4. Flowchart

More on “ordering”

Install python and IDLE in your home computer videos or work on repl.it:
Write English instructions (pseudocode) to order 3 numbers from small to large.
Use the following data to “trace” your algorithm.
89 101 2
Explain your strategy in a short paragraph.
 
Videos From the “Resources Tab” above:
Python programming using repl.it

 
Python Programming using IDLE

 
Creating a file in repl.it

 
Creating python file in IDLE

 

 
Introduction to Python and IDLE

 
Some help on running python programs in mac os x

 
Some help from Al Sweigart’s video using pc.

Basic Concepts: Sort3Nums

Classwork:

Preparing for assessment.
1. Trace your program YI_StandarDeviation.py using these numbers: 56, 43, 13, 2, 25
2. Trace your program YI_BasicInstructions4.py ( finding the range ) using these numbers: 3, 21, 65, 88
3. Trace your program YI_Sort3Nums.py using these numbers: 3, 21, 65
4. Trace your program YI_Sort3Nums.py using these numbers: 3, 65, 21
5. Trace your program YI_Sort3Nums.py using these numbers: 21, 65, 3

How to trace:

  1. Drawing a table of code and values as they change.
    trace 1
  2. Writing notes showing the values as they change.
  3. Drawing a diagram with the changes.

Designing an algorithm

Classwork:

Designing an algorithm

Activity:
Work with a partner to design an algorithm: How to draw a picture given a set of instructions.
One student has a blank paper and the other student has a picture that will keep hidden.

Rules of the game:

  1. Don’t let your partner see the drawing.
  2. Your partner will draw the same shape on his/her paper by following your “set of instructions”.
  3. Write down the instructions as you give them.
  4. You can not use direct words that describes the image.
  5. Once finished, both look at the drawings and compare them.
  6. If the drawings don’t match, go back to your instructions and change them until you are satisfied.
  7. You and your partner reverse roles with a different picture though.
  8. Do the instructions need to be revised?

Homework:
Read the following articles linked bellow

Privacy violations – the dark side of social media
Screen Shot 2014-09-04 at 6.12.33 PM

Digital Explosion: Why Is It Happening, and What Is at Stake?
Screen Shot 2014-09-04 at 6.27.26 PM

Find the largest and the smallest in a set of numbers

Click on the Home tab above.

Today’s discussions:
What is python programming language?

What is computer programming? What is an algorithm?

    You need paper and pen/pencil.

  • Work with a partner to do the following activity: Find the largest and the smallest in a set of numbers.
  • Your teacher will hand you a handful of folded papers with a number on each of them.
  • Open only two papers at a time while the rest of them should stayed folded.
  • minmax5

  • Write down the steps or draw a diagram to show how you calculate both numbers.
  • Switch your paper with a different group.
  • Can you follow the steps? Write comments and suggestions about it.
  • Summarize your strategy in one short paragraph in edmodo.com (You can do this part for homework).

Homework:

  1. Send me an email with your parents email address: the email subject should have student name, class period and class name:
    Example:
    Subject: 6th period – Python – Your Name
  2. Discuss the class policy with your parents.
  3. Visit edmodo.com and reply to the “Introduce yourself” post.

What is computer programming? What is an algorithm?

What is computer programming? What is an algorithm?

  1. Find the most popular pop singer in the list below. Write down the steps you take to figure out both.
    Explain your strategy.
  2. Find the least popular pop singer in the list below. Write down the steps you take to figure out both.
    Explain your strategy.

Homework: Use the data from yesterday to find the mean of the set of numbers. Write down the steps you take to figure out the value. Explain the strategy. Type your work in edomod.com

 

Pop singer list:
Daft Punk
Justin Timberlake
Kanye West
Daft Punk
Kanye West
Waxahatchee
Jessie Ware
Robin Thickefeat
Justin Timberlake
Jessie Ware
Phosphorescent
Daft Punk
James Blake
Daft Punk
Jessie Ware
Justin Timberlake
Kanye West
Daft Punk
Daft Punk
James Blake
Daft Punk
Jessie Ware
Justin Timberlake
Kanye West
Daft Punk
Kanye West
Waxahatchee
Jessie Ware
Robin Thickefeat

Basic: Review on Basic Concepts

Review on Basic Concepts

Dynamic Typing: in shell

>>>  x = input("enter a number ")
>>> enter a number 56
>>> print ("x ", type(x))
x  
>>> x = int(x)
>>> print("x ", type(x))
x  
>>> x = "HI"
>>> print ("x ", type(x))
x  

Floating-point type

3**5
243
5//2   # truncates the decimal part
2
5.0/2
2.5
x = 5
x/2
2.5
x = float(x)
x/2
2.5

Arithmetic Operators

arithmeticOps

Question: Can you guess what the modulus operator does?

5%2
1
25%3
1
55%6
1
48%6
0
8%3
2
8%5
3

Rules of operator precedence:

opPrecedenceTable

 

pythonExpression1

Question: What would happen if you omit the parentheses?

pythonExpression2

Expression with the modulus operator:

modulusExpression

Question: What would the value of z be if
p = 10
r = 2
q = 7
w = 5
x = 2
y = 1

Let’s trace the following expression:

order1

when
a = 2
x = 5
b = 3
c = 7

order2

Classwork:

Screen Shot 2013-09-17 at 11.27.04 PM

Trace the following expressions

a) x = 7 + 3 * 6 / 2 – 1

b) x = 2 % 2 + 2 * 2 – 2 /2

c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) )

Programming Assignments for homework:

1. Write a program, AlgeCalculator.py that requests the user to enter two numbers and prints with an user friendly message the sum, product, difference and quotient of the two numbers.
 

 

Again good programming practices:
Each program should have a header.
A header is made up of the following information as comments:
1. Your name
2. Date
3. A good description of the assignment
4. Make sure your program includes the input/output from at least one execution.

Basic: Instructions 4 and Standard Deviation

Basic Instructions 4
Classwork:

This assignments can be done with the most basic set of instructions:

#######################################
#
#   G Elia
#   Program to calcualte the range of a
#   set of numbers
#   9/21
#   python 3.4
#
########################################

yesNo ="y"
smallest =int(input("Enter number: "))

while yesNo == "y":
    y=int(input("Enter another: "))
    if smallest > y:
        smallest = y
    yesNo = input("Would you like to continue? (y/n) ")
    
print("The smallest number is",smallest)

Make the change to the brain according to the different assignments.

If you are finished with the previous assignments, work on YI_BasicInstructions4.py to calculate the range of a set.

Homework: Write a program YI_StandarDeviation.py to calculate the standard deviation of a set of numbers.
The standard deviation for a set of 5 numbers is calculated with this formula:

Screen Shot 2013-09-17 at 9.13.22 AM

where N is the total number of values entered,in this case 5,  Screen Shot 2013-09-17 at 9.15.27 AM  is each value and  Screen Shot 2013-09-17 at 9.15.11 AM  is the mean of all the values.

Look into the Documentation page to find out how to find the square root.

screen-shot-2016-09-22-at-10-43-37-pm

NOTE: import math at the top of your program

What is computer programming? What is an algorithm?

What is computer programming? What is an algorithm?

    You need paper and pen/pencil.

  • Find a partner to work on the following activity: Find the largest and the smallest in a set of numbers.
  • Your teacher will hand you a handful of folded papers with a number on each of them.
  • Open only two papers at a time.
  • minmax5

  • Write down the steps or draw a diagram to show how you calculate both numbers.
  • Summarize your strategy in one short sentence.
  • Switch your paper with a different group.
  • Can you follow the steps? Write a short conclusion and suggestions about it.

 

Basic: BasicInstructions.py – BasicInstructions2/3.py and greetings.py

Click on the image to get to the download page
Screen Shot 2014-09-09 at 9.30.37 AM

Writing your first python programs

Basic Instructions 2:

Write a program, YI_BasicInstructions2.py with the following:

  1. Prompt the user for name and grade
  2. Reply with a message about the name and grade
  3. Assign the value of “54” to variable “x”
  4. Assign the value of “23” to variable “y”
  5. Display the result of multiplying the two variables with a message
  6. Prompt the user for two more numbers, find the sum of the two numbers and display the result in a message.
  7. Prompt the user for two more numbers, find the smallest and display it with a message.

Basic Instructions 3:
Write a program, YI_BasicInstructions3.py with the following:

  1. Asking for a number: input
  2. Storing a number
  3. Comparing a number
  4. Repeating the process: copy and paste?????
  5. Find the min
yesNo = "y"
while yesNo == "y":
    inputX = input("Enter an integer ")
            # 1. asking for a number: input and store the
            #  number in variable x
    x = int(inputX) # convert input to integer
    inputY = input("Enter another integer ")
            # 1. asking for another number: input and
            # store the number in variable y
    y = int(inputY) # convert input to integer
    if x > y:
         print (x, " is bigger than ", y)
    else:
         print (y, " is bigger than ", x)
    yesNo = input("Would you like to compare more numbers? y/n ")

print "Goodbye"

firstProgramFlowchart,,,,

Homework:
Write a python program, YI_greetings.py, to
1. prompt the user for name and grade
2. reply with, How are you feeling today, name?
3. reply with a comment about his or her grade using the name and he or she is feeling.

Basic: CompoundInterestCalc_YI.py

Class work:

Calculate compound interest using the for loop.

Yesterday you learned how to use a for loop to calculate the amount of money that builds up after applying compound interest. Assuming that all the interest is left on deposit, calculate and print the amount of money in the account at the end of each year over a period of 10 years. Prompt the user for principal and rate in decimal format.

To determine these amounts, use the following formula:

amount = principal  * ( 1 + rate )** year

where

pincipal is the original amount invested ( i.e. , the principal )

rate is the annual interest rate ( e.g., .05 stands for 5% )

year is the number of years

amount is the amount on deposit at the end of the nth year.

Write a python program YI_compoundInterestCalc.py to calculate the money that remains on deposit for n number of years.

Basic: Concepts – CricketTemp_YI.py

Can Crickets Really Tell the Temperature? | Don’t Be Dumb

Classwork:
cricket1
You can tell the current temperature by counting the chirps of a cricket! The formula for calculating the current (Fahrenheit) temperature is:

(Number of Chirps per 60 seconds / 4) + 40

Write a program CricketTemp_YI.py that prompts the user for the number of cricket chirps per 15 seconds and displays the temperature.
Unless you know “loops” you will not be able to do the following) Keep on prompting the user for more input while the response is “y”.

NOTE: Make sure you have a goodbye message when the program ends.

Homework:
Complete the assignment if you have not finished it in class.

Basic: Concepts – Midpoint and more

Classwork/Homework:

  1. Write a program, MidPoint_YI.py that calculates the midpoint between two points on the number line.
    Example: Let’s say x1 = 5 and x2 = 8, the midpoint on the number line is the point 6.5
  2. Write a program, IsItRight_YI.py that determines if the three values given make up the angles of a right triangle.

In all your programs, make sure to include the following:
1. The header
2. A welcome message to the user
3. Be clear when prompting the user
4. Print the results with a message
5. At exit, print a goodbye message.

Homework:
A mortgage calculator program, YI_mortgage.py prompts the user for:
1. The amount to be borrowed
2. The number of years to pay it back
3. The rate charge for borrowing the money
Then prints back what each payment will be. An added feature would be to calculate how much the total amount paid would be at the end of the years the money was borrowed.

This is an example of what a GUI mortgage calculator would look like. You can not implement a GUI at this point but your program can have the same functionality.
MortgageCalc

Formula:
loanPaymentFormula
 

Topics covered so far


Review Part 1

Concepts we covered
if/else
Flowchart
nested if/else
range
for loop
definitions
lists
upper and lower

Basic Instructions, Control Statements and Definitions Review Documents

Programming Assignments you should know:
palindrome
compound interest
asterisk shapes
tally and tally2
times table
permutations and combinations
mail order
temperature conversions

Basic: Concepts

More Basic Concepts

Dynamic Typing: in shell

>>>  x = input("enter a number ")
>>> enter a number 56
>>> print ("x ", type(x))
>>> x = 76
>>> print ("x ", type(x))
x  
>>> x = "HI"
>>> print ("x ", type(x))
x  

>>> 
Question: 
x = input("enter a number ")
How can you convert x to an integer?

Floating-point type

3**5
243
5//2   # truncates the decimal part
2
5.0/2
2.5
x = 5
x/2
2.5
x = float(x)
x/2
2.5

Arithmetic Operators

arithmeticOps

Question: Can you guess what the modulus operator does?

5%2
1
25%3
1
55%6
1
48%6
0
8%3
2
8%5
3

Rules of operator precedence:

opPrecedenceTable

 

pythonExpression1

Question: What would happen if you omit the parentheses?

pythonExpression2

Expression with the modulus operator:

modulusExpression

Question: What would the value of z be if
p = 10
r = 2
q = 7
w = 5
x = 2
y = 1

Let’s trace the following expression:

order1

when
a = 2
x = 5
b = 3
c = 7

order2

Class work and homework:

Screen Shot 2013-09-17 at 11.27.04 PM

Trace the following expressions

a) x = 7 + 3 * 6 / 2 – 1

b) x = 2 % 2 + 2 * 2 – 2 /2

c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) )

Programming Assignments:

1. Write a program, AlgeCalculator_YI.py that requests the user to enter two numbers and prints with a user-friendly message the sum, product, difference, and quotient of the two numbers.
 

Conditionals: The Richter_Scale_YI.py Flowchart

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, RichterScale_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.

The flowchart for the Richter_Scale_YI.py assignment – Use google docs: drawing or draw.io

flowchart-1

lowchartup

Conditionals: Control Structures & Flowcharts

A) What does the program for this flowchart do?

  1. Finish the flowchart.
  2. Write the full program.

Screen Shot 2014-10-15 at 12.51.31 PM
Flowchart maker: https://app.diagrams.net/
complete-flowchart

B) Next answer, explain, and/or write code snippets:

  1. What is a pseudorandom number?
  2. In the game of “guess a number”, when does the user exit the program?
  3. In the game of “guess a number”, how many loops are needed? Explain.
  4. How do you use the range function to print the integers from 34 through 41 inclusive?
  5. How do you add all the integers from 34 through 41 inclusive? Show code.
  6. Write the code to prompt the user for an integer, N. Your program will display a square pattern of asterisks N by N
  7. Write the code to print all even integers from 36 through 12 inclusive.
  8. Write the code for a while loop to prompt the user if he or she wants to continue to input more integers.

C) The following questions are related to this flowchart:

Screen Shot 2014-10-15 at 12.51.23 PM

  1. What is the oval shape used for?
  2. What is the code for each instruction in the flowchart?
  3. Draw the flowchart to find the two digits in the middle of a 4-digit integer.

D) Write the code to calculate and display:

 “     1        1”  
 “     2        4” 
 “     3        9”  
 “     4       16”  
 “     5       25”      

E) What does this program do?

import random
for i in range( 1, 22 ): 
   print ("%6d" % ( random.randrange( 1, 7 ) ), end = ""),
   
   if i % 3 == 0:  # print newline every ?? rolls
    print("")

F) What does this program do?

nterms = int(input("Enter a number "))

# first two terms
n1, n2 = 0, 1
count = 0
if nterms <= 0:
   print("Enter a positive number ")
elif nterms == 1:
   print(n1)
else:
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1

What is the output?

G) Two more

  1. What structure can be used to repeat a block of statements when the termination of the loop is not known? Explain your answer.
  2. What structure can be used to repeat a block of statements when the termination of the loop is known? Explain your answer.

Conditionals: Richter Scale

Classwork/Homework:
Search the internet for the Richter magnitude scale and write a program, RichterScale_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.

boolean

9.4. Chaining comparison operators
Comparison operators can be chained. Consider the following examples:

>> x = 2
>> 1 < x < 3
True
>> 10 < x < 20
False
>> 3 > x <= 2
True
>> 2 == x < 4
True
The comparison is performed between each pair of terms to be evaluated. For instance in the first example, 1
The flowchart for the Richter scale program – Use google docs: drawing or draw.io

flowchart-1

lowchartup

Basic: Concepts Content Review

Classwork:
NOTE: Use python shell to confirm your answers for syntax questions


1. Write the code to assign the numerical value 54 to x.
2. Write the code to assign the string 54 to y.
3. What is the difference between questions 1 and 2?
4. What is the code to prompt the user for name and assign it to variable name?
5. Write a code snippet to compare two integer variables x and y. It should display the larger of the two.
6. What is the flowchart shape for a condition?
7. How many arrows point to any one flowchart shape?
8. How many arrows leave a rectangular flowchart shape?
9. Up to how many arrows leave a conditional flowchart shape? Explain your answer.
10. What is the instruction to display a numerical variable age and a string ” years old”?
11. What is the code to prompt the user for a real number amount and assign it to variable amount?
12. Write the python instruction to find the average of the integer variables x1, x2, and x3.
13. Write the python instruction to find the standard deviation of the integer variables x1, x2, and x3. What do you need to import?
Screen Shot 2013-09-17 at 9.13.22 AM
14. What is the result of executing the following python instruction? Explain how python solves the expression.
x = 5 – 2 * 10 + 5
15. How should you write the statement to get 35?
16. What is a boolean variable?
17. Write an instruction to assign the value of pi to variable myPi with relative high precision.
18. Write two different statements to display two variables, one is a integer and the other a string.
19. Given that number is a 4-digit integer, what is it displayed after execution?

x = number % 10
y = number // 10 % 10
z = number // 100 % 10
print (x, " ", y , " ", z)

  1. Can you guess the next one?
  2. What does this code snippet do?
x = int(input("Enter first number "))
y = int(input("Enter second number "))

if x < y:
    t = x
    x = y
    y = t
if x % y == 0:
    print("True")
else:
    print("False")


Homework:

1. Write a python program, YI_TimesTables.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
>>> 

Basic: Concepts – CircleCalc_YI.py and isMultiple_YI.py

Programming Assignments for claswork/Homework:

  1. Write a program, CircleCalc_YI.py that reads in the radius of a circle and prints with an user friendly message the circle’s diameter, circumference and area.
    After your header:

    import math # on first line
    piVariable = math.pi

  2. circle

  3. Write a program, isMultiple_YI.py that reads in two integers and determines and prints with an user friendly message whether the first is a multiple of the second. ( Hint: Use the modulus operator. )

multiple

Basic: Concepts – Palindrome

Interesting resource:
Screen Shot 2014-09-25 at 8.49.06 AM

Palindromes

A 5-digit palindrome number is a number than if read from right to left is the same as if it is read from left to right.

Some examples are: 12321, 74947 and 21812.

Classwork: write a python program, Palindrome_YI.py to prompt the user for a 5-digit number and print if it is a palindrome or not.

Homework:
Write the program for this flowchart:
Screen Shot 2014-09-25 at 9.33.01 AM

Conditionals: Sort 3

Classwork

  1. Discussion on YI_Largest.py
  2. THE WHITE BOARD

    Do you remember what you did the firs or second day of school?
    minmax5

  3. Write a program, YI_Sort3Nums.py to order 3 numbers from small to large.
    Use the following data to trace your algorithm:

89 101 2

Explain your strategy in a short paragraph.

Format: Output

#f. Output format
12 spaces between the first letter of “Name” and “Grade”

print("Name %12s" % "Grade")
print("123456789012345678901234567890")
>>> 
Name        Grade
123456789012345678901234567890
>>> 

The firs %10s is for “Name” right justified.
The second %10s is for “Grade” also right justified.

print("%10s%10s" % ("Name","Grade"))
print("123456789012345678901234567890")
>>> 
      Name     Grade
123456789012345678901234567890
>>> 

The number 18129.06 has to fit in 10 spaces including the decimal
period, the two decimal digits after the period and right justified.

print("%10.2f" % (400.2 * 45.3))
print("123456789012345678901234567890")
>>> 
  18129.06
123456789012345678901234567890
>>> 

The two floating point numbers has to fit in 10 spaces and right justified.

print("%10.2f%10.2f" % (400.2 * 45.3, 55*123.2))
print("123456789012345678901234567890")
>>> 
  18129.06   6776.00
123456789012345678901234567890
>>> 

Let’s make use of the for loop, the range and the output formatting:

#g. Calculating compound interest

principal = 1000.00  # starting principal
rate = 0.5           # interest rate

print ("Year %21s" % "Amount on deposit:")

## 1234123456789012345678901
## Year    Amount on deposit:

for year in range (1,11):
    amount = principal * ( 1.0 + rate ) ** year # amount = principal * ( 1 + rate )^year
    print ("%4d%21.2f" % (year,amount))         # cool format to display a table 
##   %4d    is for a number of 4 digits for variable year
##   %21.2f is for a number of 21 positions: 18 digits, a decimal period and 2 decimal places

####################################################################################
# %21.2f indicates that variable amount is printed as a float-point value with a 
# decimal point.
# The column has a total field width of 21 character positions and two digits of
# precision to the right of the decimal point; the total field width includes the 
# decimal point and the two digits to its right, hence 18 of the 21 positions appear 
# to the left of the decimal point.
####################################################################################

print("1234123456789012345678.90")

##
##Year    Amount on deposit:
##   1              1500.00
##   2              2250.00
##   3              3375.00
##   4              5062.50
##   5              7593.75
##   6             11390.62
##   7             17085.94
##   8             25628.91
##   9             38443.36
##  10             57665.04
##1234123456789012345678.90


Loops: “for” loop – “range” function

The range function and the for loop
visualizing
The range function:

###################################################################
# Mrs. Elia
# 10/25
# python 3.x
# Description: the range function
#
###################################################################

print ("This program demonstrates how to use the range function from python")

print ("range(10) creates a sequence or list of integers from 0 to 10-1 \n", list(range (10)))


This program demonstrates how to use the range function from python
range(10) creates a sequence or list of integers from 0 to (10-1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print ("These are both equivalent")
print("range(0,10): ", list(range (0,10)))
print( "and range(0,10,1): ", list(range(0,10,1)))

These are both equivalent
range(0,10): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
and range(0,10,1): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The for loop

a. numbers from 1 to 10 in increments of 1

###################################################################
# Mrs. Elia
# 10/25
# python 3.x
# Description: some uses of the for loop
#
#  The for loop
#
###################################################################

for counter in range (1,11):
    print ("value containded in counter is ",counter)   # counter --> 1 2 3 4 ... 10
    

value containded in counter is 1
value containded in counter is 2
value containded in counter is 3
value containded in counter is 4
value containded in counter is 5
value containded in counter is 6
value containded in counter is 7
value containded in counter is 8
value containded in counter is 9
value containded in counter is 10

b. from 10 to 2 in increments of -1 (decrement of 1)

for counter in range (10,1, -1):
    print (counter) # counter takes on the value of each item on the list

c. from 7 to 77 in steps of 7

for counter in range (7,78,7):
    print (counter)  # counter takes on the value of each item on the list

d. Summation

suma = 0
for number in range (1,11):
    suma += number
print ("The sum of all integers from 1 to 10 is ", suma)

The sum of all integers from 1 to 10 is 55

e. Summation

suma = 0
for number in range (2,101,2):
    suma += number
print ("The sum of all even integers from 2 to 100 is ", suma)

The sum of all even integers from 2 to 100 is 2550

Python Data Structures

Assignment: Write a program, factorial_YI.py. Use the “for” loop to calculate the factorial of a given number. Prompt the user for a number. (Look for the post)

Loops: while – random – Roll one Die

More on The Random Module

Screen Shot 2014-10-05 at 12.13.00 PM

Write a program, random_module_YI.py with this short program to understand how random.randrange works.

# Show the randrange range with the "while" loop

import random

i = 0
counter1 = 0
counter8 = 0

print("This program is silently counting the number of times")
print("the numbers 1 and 8 randomly come up with the following ")
print("instruction: randNumber = random.randrange(1,8)") 


while i < 1000:
    i += 1
    randNumber = random.randrange(1,8)
    if randNumber == 1:
            counter1 += 1
    if randNumber == 8:
            counter8 += 1

print("\nThe number 1 showed up ", counter1, " number of times")
print("The number 8 showed up ", counter8, " number of times")


>>> 
This program is silently counting the number of times
the numbers 1 and 8 randomly come up with the following 
instruction: randNumber = random.randrange(1,8)

The number 1 showed up  141  number of times
The number 8 showed up  0  number of times

Answer these questions on the corresponding post:
1. What is needed to import to be able to use the randrange function?
2. What does the body of the loop do?
3. What are the two “arguments” used in randrange?
3. What can you say about the second “argument” in randrange

Assignment:
Write a program, one_die_YI.py that prompts the user how many times to roll a six-sided die and a number on the die. Then it displays how many times the numbers come up.

The output should look like this:

>>> 
User friendly introduction... 

How many times do you want to roll a six-sided die? 500
What number would you like to know how many times it comes up? 3
The number  3  showed up  61  number of times in  500  of rolls

User friendly exit ... 
>>> 

Assignment:
Write a program, one_die_all_YI.py that prompts the user how many times to roll a six-sided die. Then it displays how many times all the numbers come up.
How many times should a die be rolled to validate the theoretical probability for each face to come up?

Format: print format practice

Printing format review:

## Print format practice
## 1. add a new field: total = 500322.789856341 with 15 spaces and 4 decimals
## 2. change the field format for amount to be just 10 spaces long and 3 decimals
## 3. add a new field: name = "Tuesday" to be 8 spaces long

##       Question # 8 of 2nd review day

name = "Tuesday"
total = 500322.789856341
year = 23
amount = 567.435643231
print ("%4d%21.2f" % (year, amount))
print ("0000123456789012345678901234567890")
##
##>>> 
##  23               567.44
##0000123456789012345678901234567890
##>>>