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