Python: Robert’s Notes – LISTS

source = [‘a’, ‘b’, 0, 1, 2, 3, 4, 5]
target=source ## creates reference to source
target=source[1:5] ## start with the ‘b’ and go to the 5th char (2)
 [mem:char]
target=source[1:-2] ## start with the ‘b’ and go back two spaces from end
target=source[3] ## copies the number 4 into source
target=source[:] ## copies everything – separate instance

my_list = [1, 2, 3, 4, 5]
slice_one = my_list[2: ]
slice_three = my_list[2: ]
print(slice_one) # outputs: [3, 4, 5]
print(slice_two) # outputs: [1, 2]
print(slice_three) # outputs: [4, 5]
 
squares = [x ** 2 for x in range(10)] # X squared
twos = [2 ** i for i in range(8)] # 2 squared, cubed, etc
odds = [x for x in squares if x % 2 != 0 ] # odd numbered squares
 
BUILDS A CHESSBOARD with 64 empty squares

board = [[EMPTY for i in range(8)] for j in range(8)]
TEMPERATURE EVERY HOUR FOR EVERY DAY

temps = [[0.0 for h in range(24)] for d in range(31)]

Python: Key Words and Phrases

Python Overview

Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try…except statement
while To create a while loop
with Used to simplify exception handling
yield To return a list of values from a generator

 

Built-in Exceptions

The table below shows built-in exceptions that are usually raised in Python:

Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Exception Base class for all exceptions
EOFError Raised when the input() method hits an “end of file” condition (EOF)
FloatingPointError Raised when a floating point calculation fails
GeneratorExit Raised when a generator is closed (with the close() method)
ImportError Raised when an imported module does not exist
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete
LookupError Raised when errors raised cant be found
MemoryError Raised when a program runs out of memory
NameError Raised when a variable does not exist
NotImplementedError Raised when an abstract method requires an inherited class to override the method
OSError Raised when a system related operation causes an error
OverflowError Raised when the result of a numeric calculation is too large
ReferenceError Raised when a weak reference object does not exist
RuntimeError Raised when an error occurs that do not belong to any specific exceptions
StopIteration Raised when the next() method of an iterator has no further values
SyntaxError Raised when a syntax error occurs
TabError Raised when indentation consists of tabs or spaces
SystemError Raised when a system error occurs
SystemExit Raised when the sys.exit() function is called
TypeError Raised when two different types are combined
UnboundLocalError Raised when a local variable is referenced before assignment
UnicodeError Raised when a unicode problem occurs
UnicodeEncodeError Raised when a unicode encoding problem occurs
UnicodeDecodeError Raised when a unicode decoding problem occurs
UnicodeTranslateError Raised when a unicode translation problem occurs
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero

 

Built-in Exceptions

https://www.w3schools.com/python/python_ref_exceptions.asp

https://www.w3schools.com/python/python_ref_glossary.asp

The table below shows built-in exceptions that are usually raised in Python:

Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Exception Base class for all exceptions
EOFError Raised when the input() method hits an “end of file” condition (EOF)
FloatingPointError Raised when a floating point calculation fails
GeneratorExit Raised when a generator is closed (with the close() method)
ImportError Raised when an imported module does not exist
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete
LookupError Raised when errors raised cant be found
MemoryError Raised when a program runs out of memory
NameError Raised when a variable does not exist
NotImplementedError Raised when an abstract method requires an inherited class to override the method
OSError Raised when a system related operation causes an error
OverflowError Raised when the result of a numeric calculation is too large
ReferenceError Raised when a weak reference object does not exist
RuntimeError Raised when an error occurs that do not belong to any specific exceptions
StopIteration Raised when the next() method of an iterator has no further values
SyntaxError Raised when a syntax error occurs
TabError Raised when indentation consists of tabs or spaces
SystemError Raised when a system error occurs
SystemExit Raised when the sys.exit() function is called
TypeError Raised when two different types are combined
UnboundLocalError Raised when a local variable is referenced before assignment
UnicodeError Raised when a unicode problem occurs
UnicodeEncodeError Raised when a unicode encoding problem occurs
UnicodeDecodeError Raised when a unicode decoding problem occurs
UnicodeTranslateError Raised when a unicode translation problem occurs
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero

Learn Python – NOTES 61 – 70

Program 61 – Exchanging Values

variable_1 = 1
variable_2 = 2
variable_1, variable_2 = variable_2, variable_1

OR

variable_1 = “Good”
variable_2 = “job”
variable_1, variable_2 = variable_2, variable_1
print(variable_1,variable_2)
variable_1, variable_2 = variable_2, variable_1
print(variable_1,variable_2)

FOR LONG LISTS

my_list = [10, 1, 8, 3, 5, 7, 34, 4, 76]
length = len(my_list)
for i in range(length // 2):
my_list[i], my_list[length – i – 1] = my_list[length – i – 1], my_list[i]
print(my_list)

length = len(my_list)
for i in range(length // 2):
my_list[i], my_list[length – i – 1] = my_list[length – i – 1], my_list[i]
print(my_list)

Program 62 – Finding a Value in a List

Now let's find the location of a given element inside a list:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
to_find = 5
found = False
for i in range(len(my_list)):
    found = my_list[i] == to_find
    if found:
        break
if found:
    print("Element found at index", i)
else:
    print("absent")

Program 63 -Is this number prime?

def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

for i in range(1, 61):
if is_prime(i):
print(i)

 

Program 64 –

 

Program 65 –

 

Program 66 –

 

Program 67 –

 

Program 68 –

 

Program 69 –

 

Program 70 –

 

Learn Python – NOTES 51 – 60

This follows the lesson plan at https://edube.org

Program 51 – Conjunctions, Disjunctions, and Negations

not (p and q) == (not p) or (not q)
not (p or q) == (not p) and (not q)

can be used in the abbreviated form known as op=
    & (ampersand) - bitwise conjunction;
    | (bar) - bitwise disjunction;
    ~ (tilde) - bitwise negation;
    ^ (caret) - bitwise exclusive or (xor)

Let's make it easier:

    & requires exactly two 1s to provide 1 as the result;
    | requires at least one 1 to provide 1 as the result;
    ^ requires exactly one 1 to provide 1 as the result.

Program 52 – Arrays / Lists

numbers = [10, 5, 7, 2, 1]
print("List content:", numbers)  # Printing original list content.
numbers[0] = 45
print("List content:", numbers)  # Printing original list content.
print(len(numbers))
del numbers[3]
print(numbers)
print(numbers[3])
      
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers)  # Printing original list content.

numbers[0] = 111
print("\nPrevious list content:", numbers)  # Printing previous list content.

numbers[1] = numbers[4]  # Copying value of the fifth element to the second.
print("Previous list content:", numbers)  # Printing previous list content.

print("\nList's length:", len(numbers))  # Printing previous list length.

###

del numbers[1]  # Removing the second element from the list.
print("New list's length:", len(numbers))  # Printing new list length.
print("\nNew list content:", numbers)  # Printing current list content.

###

print(numbers[-1])
This will print the LAST number in a list.
print(numbers[-2])
Similarly, the element with an index equal to -2 is the
next to the last element in the list.

Program 53 – More on Lists

hat = [1, 2, 3, 4, 5]
print(hat)
q = int(input("Change number 3 to any other number: "))
hat[2] = q
del(hat[4])
print(hat)
print(len(hat))
print(hat)

Program 54 – Functions and Methods

result = function(arg) # Passes something back to the data
result = data.method(arg) # Method does something to create a value

list.append(value) # appends to the END of the list
list.insert(location, value) # inserts SOMEWHERE in the list

numbers = [111, 7, 2, 1]
print(len(numbers))
print(numbers)

###

numbers.append(4)

print(len(numbers))
print(numbers)

###

numbers.insert(0, 222) # NOTE:  This does not use brackets
print(len(numbers))
print(numbers)
numbers.insert(1, 333) # NOTE:  This does not use brackets
print(numbers)

Program 55 – Working with Lists

my_list = []  # Creating an empty list.

for i in range(5):
    my_list.append(i + 1)
 # appends to the end
    print(my_list)

my_list2 = []  # Creating an empty list.

for i in range(5):
    my_list2.insert(0, i + 1) # inserts as first char
    print(my_list2)

Program 56 – USING len() or just for loop

my_list = [10, 1, 8, 3, 5]
total = 0
for i in my_list:
    total += i
print(total)

my_list = [10, 1, 8, 3, 5]
total = 0
for i in range(len(my_list)):
    total += my_list[i]
print(total)

Program 57 – Append, Delete, Insert


# step 1
beatles = []
print("Step 1:", beatles)


# step 2
beatles.append("John")
beatles.append("Paul")
beatles.append("George")
print("Step 2:", beatles)

# step 3
for i in range(2):
    beatles.append(input("Names Stu and Pete: "))
print("Step 3:", beatles)

# step 4
del beatles[4] 
del beatles[3] 
print("Step 4:",beatles)

# step 5
beatles.insert(0, "Ringo") # inserts as first char
print("Step 5:", beatles)

# testing list legth
print("The Fab", len(beatles))

# Ad Hoc Test
print(beatles[3])  # outputs: George

# Ad Hoc Test
beatles.insert(0, "Steve")
beatles.append("Bob")
print(beatles)  

Program 58 – Bubble Sort


my_list = [8, 10, 6, 2, 4, 9, 15, 22, 3, 5]  # list to sort
swapped = True  # It's a little fake, we need it to enter the while loop.
print(my_list)
while swapped:
    swapped = False  # no swaps so far
    for i in range(len(my_list) - 1):
        if my_list[i] > my_list[i + 1]:
            swapped = True  # a swap occurred!
            my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]

print(my_list)

# OR

simple_sort = [8, 10, 6, 2, 4, 9, 15, 22, 3, 5]
print(simple_sort)
simple_sort.sort()
print(simple_sort)
simple_sort.reverse()
print(simple_sort)

Program 59 – SORT STORED IN MEMORY SPACE – CAUTION

list_1 = [1]
list_2 = list_1
list_1[0] = 2
print(list_2) # PRINTS OUT A 2

You could say that:
1. the name of an ordinary variable is the name of its content;
2. the name of a list is the name of a memory location where the list is stored.

list_1 = [1]
list_2 = list_1[:]
list_1[0] = 2
print(list_2) # PRINTS OUT A 1

This is called a slice. It copies the contents, not the memory location.

new_list = my_list[:] # Copies entire list contents
my_list[0:end] is the same as my_list[:end]
my_list[:3] copies data from 0, 1, and 2, but not 3
my_list[start:] is the same as my_list[start:len(my_list)]
new_list = my_list[3:] copies everything from the 4th value to the end

omitting both start and end makes a copy of the whole list:
my_list = [10, 8, 6, 4, 2]
new_list = my_list[:]

You can delete with slices as well
my_list = [10, 8, 6, 4, 2]
del my_list[1:3]
print(my_list)

Deleting all the elements at once is possible too:
my_list = [10, 8, 6, 4, 2]
del my_list[:]
print(my_list)
The list becomes empty, and the output is: []

Program 60 – Does a list contain X Y Z

elem in my_list #  returns True
elem not in my_list # returns False

my_list = [0, 3, 12, 8, 2]
print(5 in my_list)
print(5 not in my_list)
print(12 in my_list)

# Find largest value in a list
my_list = [17, 3, 11, 34, 5, 1, 9, 7, 15, 13]
largest = my_list[0]
for i in range(1, len(my_list)):
    if my_list[i] > largest:
        largest = my_list[i]
print(largest)

Learn Python – NOTES 41 – 50

This follows the lesson plan at https://edube.org

Program 41 – If Else

if the_weather_is_good:
      go_for_a_walk()
elif tickets_are_available:
      go_to_the_theater()
elif table_is_available:
      go_for_lunch()
else:
      play_chess_at_home()

elif and else are both optional.  You can have simply an if.
If I get bit by a dog: see a doctor()

Program 42 – max() function – Also min() function

# Read three numbers.
number1 = int(input(“Enter the first number: “))
number2 = int(input(“Enter the second number: “))
number3 = int(input(“Enter the third number: “))
# Check which one of the numbers is the greatest
# and pass it to the largest_number variable.
largest_number = max(number1, number2, number3)
# Print the result.
print(“The largest number is:”, largest_number)

Program 43 – Sending a series of numbers to multiple variables.

x, y, z = 5, 10, 8

print(x > z)
# False
print((y - 5) == x) # True

Program 44 – While and For

i = 0
while i < 100: # do_something() i += 1 print(i) for i in range(100): # do_something() pass print(i) for i in range(10): print("The value of i is currently", i) for i in range(2, 8): print("The value of i is currently", i) An example: my_word = input("Enter a word: ") for letter in my_word: # Complete the body of the for loop. if letter=="a":pass elif letter=="e":pass elif letter=="i":pass elif letter=="i":pass elif letter=="u":pass else: print(letter) pass print(my_word) Program 45 – One Second Delay in print
import time
i = 0
for i in range(1,6):
print(i,”Mississippi”)
time.sleep(1)
pass
print(“Here I come.”)

Program 46 – Block Counting Program

import sys
import signal

blocks = int(input("Enter the number of blocks: "))
blocks_used=0
row_count=1
blocks = blocks - row_count

while blocks > blocks_used:
    if blocks<1:
        print("I exited here.")
        sys.exit()
    else:
#        print(row_count)
        blocks_used = blocks_used+row_count
        row_count += 1
        blocks = blocks - row_count
        print("         ( Blocks",blocks,")")
        if blocks < row_count:
            print("Pyramid is",row_count,"high.")
            Unused_blocks = blocks
            print("Blocks used: ",blocks_used+row_count)
            print("Unused blocks: ",(blocks))
            print("\n\n")
            sys.exit()
pass

Program 47 - Lothar Collatz Hypothesis

#    take any non-negative and non-zero integer number and name it c0;
#    if it's even, evaluate a new c0 as c0 ÷ 2;
#    otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1;
#    if c0 ≠ 1, skip to point 2.
import sys
    
mem_break = 0
iteration = 0
odd_even = "nothing"

c0 = int(input("Enter any value: "))

while mem_break < 100:
    mem_break += 1
    iteration += 1

    if c0 % 2 == 0:
        c0 = c0 / 2
        odd_even = "even"
    else:
        c0 = 3 * c0 + 1
        odd_even = "odd"
    print(iteration, c0, odd_even)
    if c0 == 1.0:
        print("iterations",iteration)
        print("\n\n")
        sys.exit()

Program 48 - for letter in word


import sys
    
mem_break = 0
iteration = 0


while mem_break < 100:
    mem_break += 1
    iteration += 1

    word = "Python"
    for letter in word:
        print(letter, end="*")
    
#       print("\n\n")



# sys.exit()

Program 49 - More examples


import sys
    
mem_break = 0
iteration = 0

# output:  P*y*t*h*o*n* etc

while mem_break < 100:
    mem_break += 1
    iteration += 1

    word = "Python"
    for letter in word:
        print(letter, end="*")

# output: 2 4 6 8 - no remainder

for i in range(1, 10):
    if i % 2 == 0:
        print(i)
    
# output:  OpenEDG - evaluation terminates with P

text = "OpenEDG Python Institute"
for letter in text:
    if letter == "P":
        break
    print(letter, end="")

# output:  prints pypypy right next to Open EDG without line feed

text = "pyxpyxpyx"
for letter in text:
    if letter == "x":
        continue
    print(letter, end="")

# sys.exit()

Program 50 - More reference - While Else


import sys
    
mem_break = 0
iteration = 0

# output:  P*y*t*h*o*n* etc
n = 0

while mem_break < 20:
    mem_break += 1
    iteration += 1


    while n != 3:
        print(n)
        n += 1
    else:
        print(n, "else")

    print()

    for i in range(0, 3):
        print(i)
    else:
        print(i, "else")


for i in range(3):
    print(i, end=" ")  # Outputs: 0 1 2

for i in range(6, 1, -2):
    print(i, end=" ")  # Outputs: 6, 4, 2