#================================================================
# IS340 In-Class Coding chapters 1 and 2 =
# - Declaring variables =
# - Getting input from the user =
# - Displaying data / Formatting the print() data =
# August 26, 2024 =
#================================================================
# DECLARE AN INTEGER VARIABLE CALLED numStudents
numStudents = 40
print("The Number of Students is ", numStudents)
# GET INPUT FORM THE USER
print("What is your name? ")
myName = input()
print("Hello, ", myName)
# USER INPUT IS A String BY DEFAULT
myAge_string = input("What is your Age? ")
# type() WILL TELL YOU WHAT TYPE OF DATA A VARIABLE IS
print("Data type is ", type(myAge_string))
# CONVERT String DATA TO Integer DATA using int()
myAge_integer = int(myAge_string)
print("Data type is ", type(myAge_integer))
# ONCE YOU HAVE AN INTEGER VARIABLE, YOU CAN DO ARITHMETIC + - * /
print("Original value is ", myAge_integer)
myAge_integer = myAge_integer + 7 # ADD 7 TO myAge_integer
print("New value is ", myAge_integer)
# DECLARE 3 Integer VARIABLES, AND CALCULATE THEIR AVERAGE
Score1 = 99
Score2 = 86
Score3 = 72
AverageScore = (Score1 + Score2 + Score3) / 3
# DIVISION CREATES A Float TYPE WITH DECIMAL DATA
print("Avg Score is ", AverageScore)
# FORMAT THE Float DATA TO 5 PLACES AFTER THE DECIMAL
print(f"Avg Score is {AverageScore:.5f} ")
print( type(AverageScore) )
# YOU CAN ADD NEWLINES WO A STRING USING \n
print("Hello\nWorld\n\n\nGoodbye")
# YOU CAN ADD TABS TO A STRING USING \t
print("\n\n Here \t are \t\t\t\tTabs! \n\n\n")
# IF YOU WANT A SLASH CHARACTER IN A String, USE \\
print("\n this is a slash \\ character \n\n")
# CONVERT AN INPUT String TO A Float VARIABLE
HoursWorked = float( input("Your Hours Worked? ") )
HourlyRate = float( input("Your Hourly Rate? ") )
Paycheck = HoursWorked * HourlyRate
# FORMAT HoursWorked TO DISPLAY 2 DECIMALS
print(f"Worked {HoursWorked:>2} ", end= ' ')
# FORMAT HourlyRate TO DISPLAY 3 DECIMALS
print(f"Rate {HourlyRate:>3}", end= ' ')
print(f"Paycheck ${Paycheck:.2f}") # DISPLAY 2 DECIMALS
print("\n\n\n GOODBYE! \n\n\n")
#=============================================================
# IS340 EXAMPLES OF USING MODULES Ch2.8 SEPT 9, 2024
#=============================================================
import datetime
currentTime = [Link]()
print([Link])
# PRINT A TIMESTAMP YEAR-MONTH-DAY HOUR-MINUTE-SECOND
print(f" {[Link]():%Y-%m-%d %H:%M:%S} ")
#===================================================
import calendar
yy = int( input("What year were you born? ") )
mm = int( input("What month were you born? ") )
print( [Link](yy, mm) ) # [Link]()
#===================================================
import math
print( [Link] )
print(f"{[Link]:.5f} ")
valA = 3
valB = 5
result = [Link](valA, valB) # [Link]()
print(f"result is {result} \n\n\n\n\n")
#===================================================
# Random Number Demo
#
import random
print([Link]()) # [Link]()
for i in range(5):
dice1 = [Link](1, 6) # generates 1 thru 6
dice2 = [Link](1, 7) # Also generates 1 thru 6
print("You rolled a ", dice1 + dice2 )
#===============================================================
====
# turtle is a module with tools for drawing graphics on the
screen
#
import turtle
[Link]("black")
# the turtle MODULE has a Turtle method that creates a drawing
tool
# In this case we are assigning to drawing tool to a variable
called "pencil"
pencil = [Link]()
[Link](20)
[Link]("red")
for i in range(400): # This code creates a "for" loop that
repeats multiple times
[Link](i)
[Link](71)
[Link]("yellow")
for i in range(400): # This code creates a "for" loop that
repeats multiple times
[Link](i)
[Link](91)
#=================================================
# Python also has built-in Modules that are ALWAYS imported
automatically.
# These provide functionality for Strings, Integers and other
data types.
# In the example below, we are using string methods, but notice
that we
# did not import a String module.
#
# ASSIGN A STRING VALUE TO THE VARIABLE phrase
phrase = "The quick brown fox jumps over the lazy dog"
print( phrase )
print( [Link]() ) # .upper() is a String method
print( [Link]() ) # .title() is a String method
print("Num Characters = ", len(phrase)) # .len() works on
Strings and other data types
#========================================================
# IS340 In Class Sept 16. Concepts from Ch2, 3, and 4
=
#========================================================
#—————————————————————————————
# LISTS OF STRINGS
girls = ["Monica", "Pheobe", "Rachel"]
boys = ["Ross", "Chandler", "Joey"]
friends = girls + boys # JOIN THE LISTS
print(friends)
[Link]("Lee")
[Link]("Monica")
newFriends = boys + girls
print(newFriends[4])
print(min(newFriends))
print(max(newFriends))
#—————————————————————————————
# A LIST OF NUMBERS
nums = [12, 56, 82, 9, 15, 53, 42, 21, 8]
average = sum(nums) / len(nums)
print(f"Avg of all numbers is {average:.4f} ")
newNum = int( input("Enter a number: ") )
[Link](newNum)
print(nums)
[Link](8) # removes a value
[Link](3) # removes whatever is at the index
print(nums)
print(f"There are {len(nums)} numbers \n")
print(f"The min number is {min(nums)}")
print(f"The max number is {max(nums)}")
print(f"The sum of all numbers is {sum(nums)}\n")
#—————————————————————————-------------————-
# A LIST WITH DIFFERENT TYPES OF DATA
student = ["Mike", 24, 19.55, "123 Main Street Apt C"]
print( len(student) )
print( student[0] )
print( student[1] )
print( student[2] )
print( student[3] )
print( student[4] ) # Causes an error - out of bounds
#—————————————————————————————
# STRING METHODS
# A VERY LONG STRING CAN'T BE DECLARED ON A SINGLE LINE OF CODE
someString = "I feel like throughout my career, \
I’ve done everything that’s been asked of me \
to do and now it’s my turn to do what I want do, \ # Backslash \
continues this onto another line
Hudson said. the main things I wanted to do. \
I’m a holiday fanatic. I love the holidays, \
and I just want to share, which is why..."
print("String length = ", len(someString))
print(f"the word do occurs {[Link]('do')} times\n")
print("the word do occurs ", [Link]('do'), "times\n”)
newString = [Link]('do', 'do NOT')
print(newString)
anotherString = [Link]()
print(anotherString)
anotherString2 = [Link]()
print(anotherString2)
# CONCATENATING STRINGS
myString = "The Quick Fox"
myString2 = "the Lazy Dog"
newString = myString + myString2
print(myString)
print(myString2)
print(newString)
print("Num Characters = ", len(myString) )
print(len(myString))
print(myString[8])
print(min(myString))
print(max(myString))
#—————————————————————————————
# MATH OPERATOR DEMO +=
score1 = 75
score2 = 88
totalScore = score1 + score2
print("ORIGINAL Total Score = ", totalScore)
score3 = 99
totalScore += score3
print("NEW Total Score = ", totalScore)
#—————————————————————
# USING A DICTIONARY
# KEY : VALUE
tvChannels = { "CBS" : 2,
"NBC" : 4,
"ABC" : 7,
"FOX" : 11 }
print(f"Channel ABC is {tvChannels['ABC']} ")
print(f"Channel CBS is {tvChannels['CBS']} ")
print(f"Channel NBC is {tvChannels['NBC']} ")
prices = { "apples" : ".25",
"oranges" : ".50",
"grapes" : ".65",
"bananas" : ".85" }
print(prices)
print("Oranges cost ", prices["oranges"])
prices["grapes"] = ".75" # Assign a new value to grapes
print(prices)
#—————————————————————————————
# TESTING DATA WITH if - elif
myAge = int( input("How old are you? ") )
if myAge < 13:
print("Just a Kid!")
print("Go to school")
elif myAge < 18:
print("In High School")
elif myAge < 30:
print("In College")
else:
print("Go play golf")
x = 0 # ZERO Is “False”. Any Non-Zero value is “True”
if x:
print(x)
else:
print("zero")
print("Goodbye")
#==========================================================
# IS340 In-Class Sept 16, 2024 =
# Bank Account demo using if-elif in a while loop =
#==========================================================
Balance = 100.00
amt = 0.00
loopAgain = True # This is a 'Loop control'
while loopAgain: # this code will continue processing until loopAgain
is False
# DISPLAY A MENU OF OPTIONS
print("\nD - Deposit")
print("W - Withdrawl")
print("B - Show Balance")
print("Q - Quit")
choice = input("Make a selection: ").upper() # Get Input and
convert it to UPPERCASE
if choice not in ['B', 'W', 'D', 'Q']: # Did the User enter a valid
choice ?
print("Oops! Please re-enter your choice.")
elif choice == 'Q': # Quit
loopAgain = False
elif choice == 'D': # Deposit
amt = float( input("Enter Deposit Amount: ") )
if amt > 0:
Balance += amt
elif choice == 'W': # Withdrawl
if Balance > 0:
amt = float( input("Enter Withdrawl Amount: ") )
if amt > Balance:
print("Cant withdraw more than Balance.")
else:
Balance -= amt
else: # Only remaining choice is Show Balance
print(f"Balance is ${Balance:.2f} \n\n") # Display currency
format for 2 decimal places
print("Goodbye")
#===================================================================
# IS340 Misc Strings, Lists, Loops in-Class Sept 23, 2024 =
#===================================================================
print("09234874351354610".isdigit()) # Check if a string has ONLY
Integers in it
print("601df5123had*&$606".isdigit()) # Check if a string has ONLY
Integers in it
#######################################################
# Make One For-Loop Nested inside another For-Loop
#######################################################
colors = ['Red', 'Green', 'Blue' ]
fruit = ['Apples', 'Oranges', 'Grapes']
for x in colors: # x IS THE OUTER LOOP
for y in fruit: # y IS THE INNER (NESTED) LOOP
print(f"\t({x},{y})")
###################################################
# USING LOOP-CONTOL x TO MANAGE A while LOOP
###################################################
x = 0
while x < 5 :
print("X is ", x)
x += 1
else:
print("All done \n")
###########################################
# Calculate interest using a for loop
###########################################
initial_savings = 10000
interest_rate = 0.05
savings = initial_savings
print(f"Initial savings of ${initial_savings}")
print(f"at {interest_rate*100:,.2f}% yearly interest")
years = int( input("How many years do you want to invest? ") )
for i in range(years):
print(f"Savings at beginning of year {i} = ${savings:.2f}")
savings += (savings * interest_rate)
#=============================================
# IS340 Chapter 6 FUNCTIONS. examples. =
#=============================================
# This is a “random conversation” function
import random
import time
food = ["pizza", "candy", "cereal", "hot dogs", "popcorn", "apples"]
person = ["Rachel", "Phoebe", "Monica", "Chandler", "Ross", "Joey"]
weather = ["sunny", "cloudy", "rainy", "windy", "hot", "cold"]
idea = ["lets watch a movie",
"lets play a game",
"lets go to the park",
"lets call somebody"]
reply = ["Thats a great idea",
"that sounds like fun",
"we did that yesterday",
"I dont feel like it today",
"maybe later"]
def say1(P, F, W):
print(f"{P} was eating {F} on a {W} day.")
def say2(anotherPerson, theIdea):
print(f"Then {anotherPerson} said {theIdea}.")
def say3(thePerson, theReply):
print(f"{theReply}, replied {thePerson}.")
def main():
for x in range(10):
person1 = person [ [Link](6) ]
randFood = food [ [Link](6) ]
randWeather = weather[ [Link](6) ]
say1(person1, randFood, randWeather)
person2 = person1
while person2 == person1:
person2 = person [ [Link](6) ]
someIdea = idea [ [Link](4) ]
say2(person2, someIdea)
say3(person1, reply[[Link](5) ])
print("\n")
[Link](.75)
main() # This "calls" the main() function
################################################
## FUNCTION “STUBS” ARE EMPTY FUNCTIONS ##
## THAT HAVEN”T BEEN CODED YET. ##
## THEY ARE ON YOUR CODING TO-DO LIST. ##
################################################
def newFile():
pass # Do Nothing, return nothing
def openFile():
pass # Do Nothing, return nothing
def saveFile():
print("In Progress...") # An alternative to pass
def printFile():
print("In Progress...") # An alternative to pass
###############################################
## PASSING DATA (someData) TO A FUNCTION ##
###############################################
def myFunction(someData):
print(f"Hello {someData} from myFunction") # RETURNING A Hello
STRING FROM THE FUNCTION
#########################################
## PASSING 3 NUMBERS TO A FUNCTION ##
#########################################
def getAverage(x, y, z): # DECLARING THE FUNCTION
return (x + y + z) / 3
value = getAverage(99, 76, 54) # CALLING THE FUNCTION
print(f"Value is {value:.2f} \n")
###################################################
## A FUNCTION THAT CONVERTS MINUTES TO HOURS ##
###################################################
def minutesToHours( theMinutes ):
if theMinutes < 1:
return 0,0
hours = int(theMinutes / 60)
minutes = theMinutes % 60 # % is Modulo (Remainder)
return hours, minutes # This function returns TWO values
for x in range(3):
myMinutes = int( input("How many minutes? ") )
h, m = minutesToHours(myMinutes) # Assign the TWO returned
values to h, m
print(f"{h} hours and {m} minutes \n\n\n\n")