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


Learn Python – NOTES 31 – 40

Program 31 -Break and Continue

# break – example
print(“The break instruction:”)
for i in range(1, 6):
if i == 3:
break
print(“Inside the loop.”, i)
print(“Outside the loop.”)

# continue – example
print(“\nThe continue instruction:”)  #NOTE: Puts a space between

for i in range(1, 6):
if i == 3:
continue
print(“Inside the loop.”, i)
print(“Outside the loop.”)

Program 32 – Kind of a Bubble Sort one Step at a Time

largest_number = -99999999 # Initialize variable
counter = 0 # Initialize counter

while True:
number = int(input(“Enter a number or type -1 to end program: “))
if number == -1:
break
counter += 1
if number > largest_number:
largest_number = number
# Does not keep all numbers in memory
# only a single number after evaluation

if counter != 0:
print(“The largest number is”, largest_number)
else:
print(“You haven’t entered any number.”)

Program 33 -Same as Program 32, but using CONTINUE

largest_number = -99999999
counter = 0

number = int(input(“Enter a number or type -1 to end program: “))

while number != -1:
if number == -1:
continue
counter += 1

if number > largest_number:
largest_number = number
number = int(input(“Enter a number or type -1 to end program: “))

if counter:
print(“The largest number is”, largest_number)
else:
print(“You haven’t entered any number.”)

Program 34 – Practice program for BREAK

my_word = “xxx”
sentence = “”

print (“xxx to quit\n”)

while True:
one_word = input(“Enter a word: “)
if one_word == “xxx”:
print (“\n” + sentence)
break
sentence = sentence + ” ” + one_word

Program 35 – Practice program for CONTINUE

REDO LABS previous lab (3.1.2.10) AND previous lab (3.1.2.11)
I DO NOT GET CONTINUE AT ALL

Program 36 -Import Sys and Exit and While

import sys

i = 1
while i < 5:
     print(i)
     i += 1
else:
     sys.exit()
     print(“else:”, i)

 

for i in range(5):
print(i)
else:
i+=1
print(“else:”, i)

print (“\nSecond Test\n”)

i = 111
for i in range(2, 1):
print(i)
else:
print(“else:”, i)

Program 37 -Temperature Conversion Program

import sys
MyExit = “Exit”

while MyExit != “X”:
    MyTitle = “Temperature Conversion Program”
    MyInstructions = “Enter C if convertion from C to F.\n”
    MyInstructions = MyInstructions + “Enter F if converting from F to C\n”
    MyInstructions = MyInstructions + “Enter X to Exit”
    print (“\n”,MyTitle,”\n”)
    print (MyInstructions+”\n”)
    MyPath=input(“Enter C or F: “)
    if MyPath == “C”:
       StartTemp=int(input(“Enter temperature: “))
       MyOutput = (StartTemp*1.8)+32
       ResultPath=”F”
    elif MyPath == “F”:
       StartTemp=int(input(“Enter temperature: “))
       MyOutput = (StartTemp-32) * (5/9)
       ResultPath=”C”
    else:
       sys.exit()
    print(StartTemp, MyPath, “is the same as”,MyOutput,ResultPath)

Program 38 – A look at Printing

  • name = input("Enter your name: ") # Your Name
  • print("Hello, " + name + ". Nice to meet you!") #Hello, XXXX. Nice to meet you!
  • print("Hello, ",name ,". Nice to meet you!") # Hello, XXXX . Nice to meet you!
  • print(\nPress Enter to end the program.”)
           input
    ()
           print
    (“THE END.”)
  • num_1 = input(“Enter the first number: “) # Enter 12
    num_2 = input(“Enter the second number: “) # Enter 21
    print(num_1 + num_2) # the program returns 1221

     
  • You can also multiply (* ‒ replication) strings, e.g.:
    my_input = input(“Enter something: “) # Example input: hello
    print(my_input * 3) # Expected output: hellohellohello

Program 39 -using f to format and braces to create dictionary

start_hour = int(input(“Enter the starting hour (0-23): “))
start_minute = int(input(“Enter the starting minute (0-59): “))
duration_minutes = int(input(“Enter the duration in minutes: “))

total_minutes = start_hour * 60
total_minutes = total_minutes + start_minute
total_minutes = total_minutes + duration_minutes
# OR total_minutes = start_hour * 60 + start_minute + duration_minutes

print(total_minutes)
print(total_minutes/60)
end_hour = total_minutes // 60 # Drops the remainder
print(end_hour)
end_minute = total_minutes % 60 # Leaves only the remainder
print(str(end_minute)+”\n”)
print(f”The event will end at {end_hour % 24}:{end_minute:02d}”)
# print({end_hour % 24}:{end_minute:02d}) # THIS GENERATES AN ERROR
# print(f{end_hour % 24}:{end_minute:02d}) # THIS GENERATES AN ERROR
print(“{end_hour % 24}:{end_minute:02d}”) # {} PRINTS EVERYTHING IN QUOTES
print(f”{end_hour % 24}:{end_minute:02d}”) # {} CREATES A DICTIONARY

Program 40 – True False ==    !=    <=     >=

n = int(input(“Enter a number:”))
print(n>=100)

 

Learn Python – NOTES 21 – 30

Program 21 – Evaluate for Leap Year

# if the year number isn’t evenly divisible by four, it’s a common year;
# otherwise, if the year number isn’t divisible by 100, it’s a leap year;
# otherwise, if the year number isn’t divisible by 400, it’s a common year;
# otherwise, it’s a leap year.

# output one of two possible messages, which are Leap year or Common year,
# depending on the value entered.

# verify if the entered year falls into the Gregorian era,
# and output a warning otherwise: Not within the Gregorian
# calendar period. Tip: use the != and % operators.

# == Evaluate of two values are equal
# % Modulus – Returns remainder ONLY – Discards value to left
# /= ?
# != Is not equal to
# // Truncates and disposes of any remainder
# ** Exponent

year = int(input(“Enter a year: “))
evaluation = “Not yet evaluated”

# Write your code here.
# Sample input: 2000 – – – Expected output: Leap year
# Sample input: 2015 – – – Expected output: Common year
# Sample input: 1999 – – – Expected output: Common year
# Sample input: 1996 – – – Expected output: Leap year
# Sample input: 1580 – – – Expected output: Not within the Gregorian calendar
# Robert Test Data – – – – 1111, 2222, 2224, 15555, 15556

if year <= 1580:
evaluation = “Not a Gregorian Date”
elif year%4 > 0:
evaluation = “This is a common year”
elif year%4 == 0:
evaluation = “This is a leap year”
elif year%2000 == 0:
evaluation = “This is a leap year”
elif year%100 == 0:
evaluation = “This is a leap year”
elif year%400 == 0:
evaluation = “This is a common year”
else:
evaluation = “ERROR DETECTED”

print (evaluation)

 

Program 22 – Send multiple values to multiple variables

x, y, z = 5, 10, 8

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

You can also do: 
x, y, z = 5, 10, 8
x, y, z = z, y, x

Program 23 – Else and Elif

If  True
   Executes
If  False
   Does not execute
If  True
   Executes

Elif will exit if True

Program 24 –  Endless While Loops

while True:
print(“I’m stuck inside a loop.”)
 
Exit with ^C
 

Program 25 – Equivalent expressions

Try to recall how Python interprets the truth of a condition, and note that these two forms are equivalent:
       while number != 0: and while number:.
The condition that checks if a number is odd can be coded in these equivalent forms, too:
             if number % 2 == 1: and if number % 2:.

Program 26 – Incrementing a Counter – Similar to C 

 counter -= 1   is the same as   counter = counter-1
 counter += 1   is the same as   counter = counter+1

Program 27 – Hurkle – A Game by Robert Andrews

NOTE:  This program works with valid entries.  It will return an error if you enter anything that is not between 1 and 99.

import random
secret_number = random.randint(1, 99)

import sys
# Multi Line Print

print(
“””
+============================+
| Welcome to Robert’s Hurkle.|
| Guess the Secret Number. |
+============================+
“””)
print (“The Secret Number is ” + str(secret_number))

MyGuess = 0
guesses = 0

while MyGuess != secret_number:
MyGuess = int(input(“Enter your secret number guess: “))
if MyGuess > secret_number: hint=”Lower”
else: hint= “Higher”

if MyGuess == secret_number:
print (“Congratulations. You guessed correctly.”)
print (“The number is ” + str(MyGuess))
print (“it took you ” + str(guesses+1) + ” guesses to get it right.”)
print()
elif MyGuess == 0:
print (“The number was ” + str(secret_number) + “.”)
sys.exit()   # You can also use break
else:
print (“Wrong. ” + str(MyGuess) + ” is not the number.”)
print (“Enter ZERO to give up.”)
guesses += 1
print (“So far, you guessed ” + str(guesses) + ” times.”)
print (“The secret number is ” + hint)
print()

 

Program 28 – Loops – If and For

  1. i = 0
  2. while i < 100:
  3.      # do_something()
  4.      i += 1

 

  1. for i in range(100):
  2.      # do_something()
  3. pass
  • for i in range(10):
  •      print(“The value of i is currently”, i)   
  •      # Note, space added automatically with comma

Starts with zero and ends with 9

You can also specify a range by two integers

for i in range(2, 8):

     print(“The value of i is currently”, i)

Program 29 -Hurkle – IMPROVED

import random
secret_number = random.randint(1, 99)

import sys

print(
“””
+============================+
| Welcome to Robert’s Hurkle.|
| Guess the Secret Number. |
+============================+
“””)
print (“The Secret Number is ” + str(secret_number))

MyGuess = 0
guesses = 0

while MyGuess != secret_number:
MyGuess = int(input(“Enter your secret number guess: “))
if MyGuess > secret_number: hint=”Lower”
else: hint= “Higher”

if MyGuess == secret_number:
print (“Congratulations. You guessed correctly.”)
print (“The number is ” + str(MyGuess))
print (“it took you ” + str(guesses+1) + ” guesses to get it right.”)
print()
elif MyGuess == 0:
print (“The number was ” + str(secret_number) + “.”)
sys.exit()
else:
print (“Wrong. ” + str(MyGuess) + ” is not the number.”)
print (“Enter ZERO to give up.”)
guesses += 1
print (“So far, you guessed ” + str(guesses) + ” times.”)
print (“The secret number is ” + hint)
print()

Program 30 – Time Delay and For Loops

import time
FindMe = “Ready or not. Here I come.”

# Write a for loop that counts to five.
i=1
while i<6:
print (i,”Mississippi”)
time.sleep(1)   # DELAYS PROGRAM 1 SECOND
# Body of the loop – print the loop iteration number and the word “Mississippi”.
i += 1
# Write a print function with the final message.
print (FindMe)

 

Learn Python – INDEX

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

  • Notes 1 – 10
    • Enter and echo your name and age
    • Using commas and the Print Sep command
    • Using Print End and Sep
    • Octals and Hexidecimals
    • Forcing quotes using      \”
    • Using the  **  operator
    • Mathematical expression priorities
    • Significant Digits
  • Notes 11 – 20
    • Simple math with variables
    • Simple Do While
    • Shortcut operators
    • Input data from keyboard
    • Input of strings
    • Repetition of strings
    • Mathematical expression priorities (revisited)
    • If Elif Else
    • Equal and Not Equal and Is it Equal?
    • Thaler Tax Program (complete – mid range programming)
  • Notes 21 – 30
    • Leap year evaluation:     =     !=     //
    • Send multiple values to multiple variables
    • More on If  Elif  and Else
    • Endless While Loops
    • Equivalent Expressions – Time savers
    • Incrementing a Counter
    • FIRST GAME:  HURKLE
    • If and For Loops
    • HURKLE – Improved
    • Time delay and FOR Loops
  • Notes 31 – 40
  • X

Learn Python – NOTES 11 – 20

 

# Sample Python Program 11 – Simple Math with Variables

john=3
mary=5
adam=6
print(john,mary,adam,sep=”, “)
total_apples=john+mary+adam
print (“Total Apples; “, total_apples)

# Sample Python Program 12 – Simple DO WHILE

sheep=1
while sheep<=20:
print (sheep)
sheep = sheep + 1
# END

# Sample Python Program 13 – Shortcut Operators

  • print (i = i + 2 * j      ⇒      i += 2 * j)
  • print (var = var / 2      ⇒      var /= 2)
  • print (rem = rem % 10      ⇒      rem %= 10)
  • print (j = j – (i + var + rem)      ⇒      j -= (i + var + rem))
  • print (x = x ** 2      ⇒      x **= 2)

# Sample Python Program 14 – Input Data from keyboard

print(“Tell me anything…”)
anything = input()
print(“Hmm…”, anything, “… Really?”)

or

anything = input(“Tell me anything…”)
print(“Hmm…”, anything, “…Really?”)

THIS IS A TEXT STRING

anything = input("Enter a number: ")

something = anything ** 2.0
print
(anything, "to the power of 2 is", something)

MUST BE CODED LIKE THIS

anything = input("Enter a number: ")

something = anything ** 2.0
print
(anything, "to the power of 2 is", something)

OR

anything = float(input(“Enter a number: “))

# Sample Python Program 15 – Input of Strings

fnam = input(“May I have your first name, please? “)
lnam = input(“May I have your last name, please? “)
print(“Thank you.”)
print(“\nYour name is ” + fnam + ” ” + lnam + “.”)

# Sample Python Program 16 – Repetition of a String

print (string * number)

# Sample Python Program 17 – Order of Operations

priority table

Priority Operator  
1 +, - unary
2 **  
3 *, /, //, %  
4 +, - binary
5 <, <=, >, >=  
6 ==, !=

# Sample Python Program 18 – IF / ELSE / ELIF

if x=0:
    do this
else: # This is done with a single possible outcome
    do this
elif:  # This replaces the Select Case conditional
    do this or several other Elifs – Exits after first positive
else:

Shortcut

If x=0: do this
Else: do this instead

 # Sample Python Program 19 – Example Code

x = input(“Enter dog’s name: “)
if x == “Jasmine”:dog_name=”Horray for Jasmine”
elif x == “jasmine”:dog_name=”I want an upper case Jasmine.”
else: x=”This is not Jasmine.” # ALL OTHER CONDITIONS

print(dog_name)

 # Sample Python Program 20 – Thaler Tax Program#
cap = 85528
target_tax=14839.02
currency = “Thalers”

income = float(input(“Enter income: “))
if income >= cap:
print(“Tax is due @ target_tax+32% of excess”)
diff=(income-cap)
perc=(diff*.32)
print(perc)
tax=(target_tax + perc)
else:
print(“Tax is due at 18% – 556.02”)
perc=(income*.18)
tax=(perc-556.02)

tax = round(tax, 0)
if tax<0: tax=0
print(“The tax is:”, tax, currency)

 

Learn Python – NOTES 1 – 10

https://edube.org/login – Python 3 or CPython
Programming tool is IDLE

https://docs.python.org/3/library/functions.html

# Sample Python Program 01

# Get user input for name
name = input(“Enter your name: “)
# Get user input for age
age = input(“Enter your age: “)
# Convert age to an integer
age = int(age)
# Print a personalized greeting
print(f”Hello, {name}! You are {age} years old.”)

# Sample Python Program 02

# Using the f function
print(f”Hello, {second}! You are {first} years old.”)
print(“Hello, {second}! You are {first} years old.”)

# Sample Python Program 03

# Using the end and sep functions within print()
print(“Programming”,”Essentials”,”in”,sep=”***”,end=”…”)
print(“Python”)
# THIS WILL DISPLAY – Programming***Essentials***in…Python

# Sample Python Program 04

# PLAYING AROUND WITH end and sep
print(” *”)
print(” * *”)
print(” * *”)
print(” * *”)
print(‘*** ***’)
print(” * *”)
print(” * *”)
print(” *****”)
# *
# * *
# * *
# * *
# *** ***
# * *
# * *
# *****

# Sample Python Program 05

# Octals and Hexidecimals and Base 10
print(0o123)
print(0x123)
print (123)
print (“123”)

# Sample Python Program 06

# Forcing quotes to appear in print
print("I like \"Monty Python\"")
print("I like 'Monty Python'")
print('I like "Monty Python"')
print("I like \'Monty Python\'")

# Sample Python Program 07

# print three lines with a single line of code

“I’m” ,
“”learning”” ,
“””Python”””

One long string
print(” \”I\’m\”      \n \”\”learning\”\”       \n \”\”\”Python\”\”\” “)
Three shorter strings
print(“\”I’m\”” , “\n\”\”learning\”\”” , “\n\”\”\”Python\”\”\””)
Using the SEP function
print(“\”I’m\”” , “\”learning\”\”” , “\”\”Python\”\”\””,sep=”\n”)

# Sample Python Program 08

# Try to understand the ** operator
print ((2**0) + (2**1) + (2**3))
print (2**0)
print (2**1)
print (2**3)

print ((2**0) + (2**1) + (2**2) + (2**3))
print (2**0)
print (2**1)
print (2**2)
print (2**3)

# Sample Python Program 09

# Mathematical Operators
+    -    *    /    //    %    **

# Sample Python Program 10
#Significant digits

print(2 ** 3) # this results in an integer
print(2 ** 3.) # this results in a float
print(2. ** 3) # this results in a float
print(2. ** 3.) # this results in a float

Division is always a float, unless…
print(6 / 3)
print (int(6 / 3))   # or
print(6 // 3)     # (forces integer as a result – TRUNCATES – does not round
print(6 / 3.)
print(6. / 3)
print(6. / 3.)