Category Archives: Lessons

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.

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

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

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.

 

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.

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

 

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.

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

Functions: an Introduction

Using definitions to write better style programs

 

###################################
#  Re-write this program using functions 
#  happy1_GE.py
#  
#  Mrs. Elia
#  python 3.9
#  10/8
#
###################################

name = input("what is your name? ")
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear ", name + "!")
print("Happy Birthday to you!")

##/My_Python_Programs/Unit2/happy1_GE.py
##what is your name? grace
##Happy Birthday to you!
##Happy Birthday to you!
##Happy Birthday, dear grace!
##Happy Birthday to you!
##>>> 

Let’s re-write it with functions:

###################################
#
#  happy2_GE.py
#  Using functions to design your program
#  Mrs. Elia
#  python 3.9
#  10/8
#
###################################

def happy():
   print("Happy Birthday to you!")

def sing(person):
   print("Happy Birthday, dear ", person + "!")
   
def main():
   name = input("what is your name? ")
   happy()
   happy()
   sing(name)
   happy()

main()



##/My_Python_Programs/Unit2/happy2_GE.py
##what is your name? grace
##Happy Birthday to you!
##Happy Birthday to you!
##Happy Birthday, dear grace!
##Happy Birthday to you!
##>>> 

Functions: Say Hello

Complete this assignment.

 

###################################################################
# Description: improve this program by using functions 
# Mrs. Elia
# 10/7
# python 3.9
#
###################################################################
aName = input("Hi! What is your name? ")
print "Hello ",aName, "! I hope you are enjoying your day!"

##>>> 
##Hi! What is your name? grace
##Hello grace! I hope you are enjoying your day!
##>>> 

Here is an outline of the changes:

#from
aName = input("Hi! What is your name? ")
print "Hello ",aName, "! I hope you are enjoying your day!"

# to functional programming
def hello(aName): # it prompts the user for a name
                  # it prints a message with the name

def main():       # it calls the only one function

main()  # execute by calling it

Read this article: Fostering Tech Talents in School. All of it.