Category Archives: Class work

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

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
 

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
>>> 

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
##>>> 

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.

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


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: 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