<<

CSC 272 - Software II: Principles of Programming Languages

Python

value1 = int(input("What is the first value?")) value2 = int(input("What is the second value?")) value3 = int(input("What is the third value?")) sum = value1 + value2 + value3 average = sum / 3 print("The average is ", average) payroll.py rate = float( input("What is your hourly pay rate?")) hours = float("How many hours did you work?")) gross = rate * hours print("Your gross pay is $", gross);

Comments

• Our program is a bit longer than our previous programs and if we did not know how to calculate gross pay, we might not be able to determine this from the program alone. • It is helpful as programs get much longer to be able to insert text that explains how the program works. These are called comments . Comments are meant for the human reader, not for the computer. • In Python, anything on a line after a double slash ( #) is considered a comment. payroll.py

# This program calculates the gross pay for an # hourly worker. # Inputs - hourly pay rate and number of hours # worked # Output - Gross pay

# Get the hourly pay rate rate = float( input("What is your hourly pay rate?"))

# Get the number of hours worked hours = float("How many hours did you work?"))

# Calculate and display the gross pay gross = rate * hours print("Your gross pay is $", gross);

if and if-else

• The general form is: if expression ) : statement or if expression : statement Else : statement IsItNegative.py

# Tell a user if a number is negative or # non-negative

# Ask the user for a number number = float(input("Please enter a number?"))

# Print whether the number is negative or # not if number < 0.0 : print(number, " is a negative number") else : print(number, " is a NOT negative number")

The Complete Speed Program

# Calculate the speed that you are traveling # from the distance and time that you have # been driving. # Print a warning if you are going over the # speed limit.

# in the distance in miles and # time driven miles = float(input ("How many miles have you driven?")) hours = float(input("How many hours did it take?"))

# Calculate and print the speed speed = miles / hours print("You were driving at ", speed, "miles per hour.") # Print the warning if appropriate if speed > 55 : print("**BE CAREFUL!**", "You are driving too fast!")

Constants

Python does not allow us to declare values as constant (not subject to further revision), we can give these values names and indicate that their values should not and do change within the program. •Any such constants should appear at the beginning of the program and should have their names in all upper case characters. ConvertPounds3.py

# Convert pounds to kilograms

# Set the pounds per kilogram at 2.2 POUNDS_PER_KG = 2.2

# Get the weight in pounds lbs = float(input("What is the weight in pounds?"))

# Ensure that the weight in pounds is # valid. If it is valid, calculate and # display the weight in kilograms if lbs < 0 : print(lbs, " is not a valid weight.") else : kg = lbs / POUNDS_PER_KG print("The weight is ", kg, " kilograms"

Coding Compound Statements

• We could : if color == blue : print "blue" if color == red : print "red" if color == "yellow" : print “yellow" Coding Compound Statements (continued)

• Instead we can use the reserved word elif to replace else if and avoid the extra indentation if color == blue : print "blue" elif color == red : print "red" elif color == "yellow" : print “yellow"

An Auto Insurance Program • Example - Write a program to determine the cost of an automobile insurance premium, based on driver's age and the number of accidents that the driver has had. • The basic insurance charge is $500. There is a surcharge of $100 if the driver is under 25 and an additional surcharge for accidents: # of accidents Accident Surcharge 1 50 2 125 3 225 4 or more 375 InsureCar.py

# A program to calculate insurance premiums # based on the driver’s age and accident # record. basicRate = 500 ageSurcharge = 0 accidentSurcharge = 0

# Input driver's age and number of # accidents age = int(input("How old is the driver?")) numAccidents = int(input("How many accidents has the driver had?"))

# Determine if there is an age surcharge if age < 25 : ageSurcharge = 100 else : ageSurcharge = 0

# Determine if there is a surcharge if numAccidents == 0 : accidentSurcharge = 0 elif numAccidents == 1 : accidentSurcharge = 50 elif (numAccidents == 2): accidentSurcharge = 125 elif numAccidents == 3 : accidentSurcharge = 225 elif numAccidents >= 4 : accidentSurcharge = 375 # Print the charges print("The basic rate is $", basicRate) print("The age surcharge is $", ageSurcharge)

print("The accident surcharge is $", accidentSurcharge)

rate = basicRate + ageSurcharge + accidentSurcharge print("The total charge is $", + rate)

Counting Loops • We use a for loop to write basic counting loops • In Python, it looks like this: for count in range( size ) : statements • or for count in range(start , size ) : statements • or for count in range(start , size, increment ) : statements • or for count in range(size , increment ) : statements Counting Loops (continued)

for count in range( start , size , increment ) : statement(s) variable used to count number of times through the loop loops

initial value increment of the counter of the counter

for Loops - Examples

for i in range(3) : print(i, " ", end="") print()

for i in range(1, 3) : print(i, " ", end="") print()

for i in range(1, 6, 2) : print(i, " ", end="") print() Output 0 1 2 1 2 1 3 5 HelloAgain

# HelloAgain3 - Write "Hello, again" as many times # as the user wants totalTimes = int(input ("How many times do you want to say \"hello\"?")) for count in range(totalTimes) : print("Hello, again")}

The AverageN Program

# AverageN - Find the average of N values

# Find out how many values there are numValues = int(input ("How many values are you going to enter?"))

# Read in each value and add it to the sum sum = 0.0; for currentValue in range(numValues) : value = float(input("What is the next value?")) sum = sum + value

# Calculate and print out the average average = sum / numValues print("The average is ", average) Formatted Output With print()

• The method print() gives us a way to write output that is formatted, i.e., we can control its appearance. • We write: print( ControlString , %( Arg1 , Arg2 , ... )) • The control string is a template for our output, complete with the text that will appear along with whatever values we are printing.

Integer Division

• In Python, the / / operator produces n integer quotient for integer division. • If you want the remainder from integer division, you want to use the % operator Final Compound Interest Program

# Calculate the interest that the Canarsie # Indians could have accrued if they had # deposited the $24 in an bank account at # 5% interest. present = 2015; rate = 0.05;

# Set the initial principle at $24 principle = 24;

# For every year since 1625, add 5% interest # to the principle and print out # the principle for year in range(1625, present) : interest = rate * principle principle = principle + interest

# Print the principle for every 20th year if year % 20 == 5 : print("year = %4d\tprinciple = $%13.2f" %(year, principle))

# Print the values for the last year print("year = %4d\tprinciple = $%13.2f" % (year, principle)) While Loops

• The most common form of conditional loops are while loops. • In Python, they have the form: while condition : statement(s)

A simple example – PickPositive.py

# A simple example of how while works

# Get your first number number = int(input("Hi there. Pick a positive integer"))

# Keep reading number as long as they are # positive while number > 0 : number = int(input("Pick another positive integer")) print(number, " is not a positive integer") The TestAverage Program

# Calculates the average test grade and # converts it to a letter grade assuming that # A is a 90 average, B is an 80 average and so # on. sentinelGrade = -1

# Initially the number of test is 0 numTests = 0

# Initially, the total is 0 total = 0

# Get the first grade print("What grade did you get on your first test ?") print("Enter -1 to end") thisGrade = int(input ())

# Add up the test grades while thisGrade != sentinelGrade : # Make sure that the grades are valid percentages total = total + thisGrade numTests = numTests + 1 thisGrade = int(input("What grade did you get on this test ?"))

# Find the average testAverage = total/numTests

# Find the letter grade corresponding to the average if testAverage >= 90 : courseGrade = 'A' elif testAverage >= 80 : courseGrade = 'B' elif testAverage >= 70 : courseGrade = 'C' elif testAverage >= 60 : courseGrade = 'D'; else : courseGrade = 'F' # Print the results print("Your test average is ", testAverage) print("Your grade will be ", courseGrade);

Magic Number Problem • The magic number game involves guessing a number and with each wrong guess, the player is told “too high” or “ too low”. The goal is to guess the number in the smallest number of tries. • We need a method for having the computer pick a number at random for the player to guess. • We will need to learn about how to use “library functions” to provide us with the magic number. import and Python Modules

• It is frequently helpful to be able to use software routines that have already been written for common tasks. • A library is a collection of code that someone else wrote and translated. • A standard library is a library that is part of the language. Standard libraries are expected to be included with a Python system. • Python’s standard libraries are organized into modules. Each of these must be imported before its components can be used in a program.

import and the Random Module

• To use the random number function, we need to include import random • This tells the computer it needs to use the random module. • A module will include data types and procedures that we will need to use. We make it available by writing import random at the beginning of the program • The name of the random number function that we want is randint( start , finish ) – it will provide a random integer value in the range start to finish. • In our program, the range will be 1 to 100 . The Magic Number Program import random

# The magic number game has the user trying to # guess which number between 1 and 100 the # computer has picked tries = 1;

# Use the random number function to pick a # number magic = random.randint(1, 100) # Let the user make a guess guess = int(input("Guess ?"))

while guess != magic : # Otherwise tell him whether it's too high # or too low if guess > magic : print(".. Wrong .. Too high\n") else : print(".. Wrong .. Too low\n") # Let the user make another guess

guess = int(input("Guess ?")) tries = tries + 1

# If the user won, tell him/her print("** Right!! ** ") print(magic, " is the magic number\n");

# Tell the user how many guesses it took print("You took ", tries, " guesses\n"); Declaring Boolean Constants • If we want to work with true and false we can work with bool variables. • We can write: married = True … … … … if married : print("The employee is married")

! operator

• Sometimes we want to test to see if a condition is not true. • We can do this by using the not operator, which is written as !: if (!married) System.out.println( "Do you" + " want to bring a" + " date? "); and and or Operators

• Sometimes there may be two or more conditions to consider.For this reason we have the and and or operators. • If we have two variables, p, q : – Both p and q must be true for p and q to be true. – p or q is true unless both p and q are false.

What are Strings?

• A collection of characters that are read and written together to form words, numbers and so on are called strings . • Strings have certain methods that can be used to manipulate them. At the same time, they can be used in some ways that are like the basic data type in Python, such as int and float . • Individual characters in Python are considered string of length 1. Assigning a Value to String

• A value can be assigned to a string by putting the characters inside single or double quotes: >>> s = "This is the first" >>> print (s) This is the first >>> t = 'This is the second' >>> print(t) This is the second >>>

How does Python handle input and output? • In Python, it is very easy to read in data is as a string. • All input read using the input functions are initially strings; if they are some other data type, we use the appropirate function to convert the data to that type: s = input("Enter the next string") x = int(input("Enter another number") Python String Input/Output - An Example s = input(("Enter your string")) print("Your string is \"", s, "\".")

>>> Enter your string This is the first Your string is " This is the first ". >>>

Concatenation and Repetition

• Concatenation is the operation where we join two strings together into one longer string. s = "The " + "Second" print(s) will print "The Second" • Repetition is the operation where we create a string that contains the same sequence of characters multiple times. s = "my" * 3 print(s) will print "mymymy" The Python String Functions • The way in which you specify a string’s function is to write: objectName.methodName(); • len(s) - Returns the number of characters in s • s.strip() - Returns s with loading and trailing white space characters removed. • s[] - Returns a substring of s • s.indexOf() - Returns the starting position of the first occurrence of a substring within s.

len(s)

• len(s) returns the number of characters that s contains: s = "This Is The First" print(len(s)) • This program prints 17 s.strip()

• Returns s with leading and trailing white space characters removed. s = " This Is The First " s = s.strip(); print("My String is \'", s, "\'") print ("It has ", len(s), " character.")

The output is: My String is 'This Is The First' It has 17 character.

s[]

• s[] returns a substring of s. • s[i] will return the ith character in the string. • s[i:j] will return characters i through j. s[12] - An Example s = "The quick brown fox jumped over the lazy dogs" t = s[12] print("My String is \'", t, "\'")

• Output >>> My String is ' o ' >>>

s[12, 17] - An Example s = "The quick brown fox jumped over the lazy dogs" t = s[12:17] print("My String is \'", t, "\'") • Output >>> My String is ' own f' >>> s.find()

• s.find() can be used to find where a substring appears within s. • Example s = "John Francis Xavier Smith" i = s.find("Fran"); t = s[i:i+7] print(t, "\'begins at position", i) Output Francis 'begins at position 5

Comparing Strings

• We can compare strings in the same way that we compare numbers; using the standard operators == , != , >, >= , <, <= Collating Sequence

• The order in which characters are assumed to appear is called the collating sequence. • For now, we are most concerned with the following facts about the collating sequence: – Digits (0-9) come before letters. – All 26 upper case letters come before the lower case letters. – Within upper case and within lower case, the letters all fall within alphabetical order.

CompareStrings.py s = "First" t = "first" u = "Second" if s == t : print("\'", s, "\' and \'", t, "\' are the same.") else : print("\'",s, "\' and \'", t, "\' are different.") if s > t : print("\'", s + "\' goes after \'", t, "\'.") else : print("\'", s + "\' comes before \'", t, "\'.") if s == u : print("\'", s, "\' and \'", t, "\' are the same.") else : print("\'",s, "\' and \'", t, "\' are different.") if s > u : print("\'", s + "\' goes after \'", t, "\'.") else : print("\'", s + "\' comes before \'", t, "\'.")

Other String Functions

• There are other string functions that can be useful:

– s.replace(t 1,t 2) – s.upper() – s.lower() – s.capitalize() – s.count() s.replace(t 1,t 2)

• s.replace(t1,t2) replaces each occurrence of t1 in the string s with t2 • Example s = "The quick brown fox" s.replace("brown", "blue") print("\"", s, "\"") • Output " The quick brown fox "

s.upper()

• s.upper() changes all the characters in the string to upper case. • Example >>> s = "This is a test" >>> t = s.upper() >>> print(t) THIS IS A TEST >>> s.lower()

• s.lower() changes all the characters in the string to lower case. • Example >>> s = "Barry yelled, \"OVER HERE!!!\"" >>> t = s.lower() >>> print(t) barry yelled, "over here!!!" >>>

s.capitalize()

• s.capitalize() places the first character of the string in upper case and the remainder of the string in lower case. • Example >>> s = "i like SoHo, TriBeCa and iPhones" >>> t = s.capitalize() >>> print(t) I like soho, tribeca and iphones >>> s.count()

• s.count(t) returns the number of occurences of the string t in s that do not overlap. • Example >>> s = "Aiiieie!" >>> i = s.count("ii") >>> print(i) 1 >>>

Example: Writing Changing a Form Letter

• Let’s write a program to read a file and change every occurrence of the name “John” to “Robert” • Initial algorithm: 1. Instruct the user 2. Change every occurrence on each line of “John” to “Robert Example: ChangeLetter.py

# Change every occurrence of "John" in the # text of a form letter to "Robert"

# Prompt the user and instruct him.her how # to indicate the end of the letter inString = input("Please begin typing. " + "End by typing \'The End\'\n")

# Keep changing as long as (s)he didn't # type "the end" while inString != "The End" : outString = inString.replace("John", "Robert") print(outString)

inString = input("Next line?\n")

Math Library

• The Math library in Python provides programmers with a large range of mathematical functions. Basic Math Functions

• math.ceil(x) – returns a float equal to the smallest integer greater than x • math.floor(x) - returns a float equal to the largest integer less than x • math.trunc() – truncates the float to an integer (similar to floor) • math.fabs(x) – absolute value of x • math.factorial(x) – the product of every integer from 1 to x (x must be positive)

Basic Math Functions – An Example

# We need to import the math library import math

# Our two sample values x = 2.718281828 y = - 3.14159

# Let's write the values print("x = ", x, "\ty = ", y) # Ceiling, floor and truncation print("ceil(x) = ", math.ceil(x), "\tceil(y) = ", math.ceil(y)) print("floor(x) = ", math.floor(x), "\tfloor(y) = ", math.floor(y)) print("trunc(x) = ", math.trunc(x), "\ttrunc(y) = ", math.trunc(y))

# Absolute value and factorial print("fabs(x) = ", math.fabs(x), "\tfabs(y) = ", math.fabs(y)) print("factorial(trunc(x)) = ", math.factorial(math.trunc(x)))

Basic Math Functions – The Output

>>> x = 2.718281828 y = -3.14159 ceil(x) = 3 ceil(y) = -3 floor(x) = 2 floor(y) = -4 trunc(x) = 2 trunc(y) = -3 fabs(x) = 2.718281828 fabs(y) = 3.14159 factorial(trunc(x)) = 2 >>> Power and Logarithm Functions

• math.exp(x) – ex – x raised to the e power

• math.log(x) = ln x = log e x – natural logarithm of x

• math.log(x, base) = log base x = logarithm of x using the specified base

• math.log10(x) = log 10 x = common logarithm of x • math.pow(x, y) = xy = x to the y power • math.sqrt(x) = √x = square root of x

Exponent and Logarithm Functions An Example

# We need to import the math library import math

# Our two sample values x = 2 y = 3

# Let's write the values print("x = ", x, "\ty = ", y) # Exponential and logarithm functions print("exp(x) = ", math.exp(x), "\texp(y) = ", math.exp(y)) print("log(x) = ", math.log(x), "\tlog(y) = ", math.log(y)) print("log(x, y) = ", math.log(x, y)) print("log(x, 10) = ", math.log(x, 10), "\tlog(y, 10) = ", math.log(y, 10)) print("log10(x) = ", math.log10(x), "\tlog10(y) = ", math.log10(y))

# power and square root functions print("pow(x, y) = ", math.pow(x, y), "\tfabs(y, x) = ", math.pow(y, x)) print("sqrt(x) = ", math.sqrt(x), "\tsqrt(y) = ", math.sqrt(y)) Trigonometric Functions – An Example

# We need to import the math library import math

# Our two sample values x = 3.14159/2 y = 3.14159/3

# Let's write the values print("x = ", x, "\ty = ", y)

# Trigonometric functions print("sin(x) = ", math.sin(x), “\n\tsin(y) = ", math.sin(y)) print("cos(x) = ", math.cos(x), “\n\tcos(y) = ", math.cos(y)) print("tan(x) = ", math.tan(x), “\n\ttan(y) = ", math.tan(y)) Trigonometric Functions - Output

>>> x = 1.570795 y = 1.0471966666666666 sin(x) = 0.9999999999991198 sin(y) = 0.8660249615191342 cos(x) = 1.3267948966775328e-06 cos(y) = 0.5000007660251953 tan(x) = 753695.9951408089 tan(y) = 1.732047269454573 >>>

Inverse Trig Functions – An Example

# We need to import the math library import math

# Our two sample values x = 0 y = 1

# Let's write the values print("x = ", x, "\ty = ", y) # Inverse Trigonometric functions print("asin(x) = ", math.asin(x), "\n\tasin(y) = ", math.asin(y)) print("acos(x) = ", math.acos(x), "\n\tacos(y) = ", math.acos(y)) print("atan(x) = ", math.atan(x), "\n\tatan(y) = ", math.atan(y))

Constants and Angle Conversions

• math.pi = 3.14159265358979… • math.e = 2.718281728… • math.degrees(x) – converts x degrees to radians • math.radians(x) – converts x radians to degrees Angle Conversion – An Example

# We need to import the math library import math

# Our two sample values x1 = 45 x2 = 60 y1 = math.pi/3 y2 = math.pi/2

# Let's write the constant values print("pi = ", math.pi, "\n\t\te = ", math.e)

Constants and Angle Conversion – An Example

# Let's write the values print("x1 = ", x1, "\n\t\tx2 = ", x2) print("y1= ", y1, "\n\t\ty2 = ", y2)

# Inverse Trigonometric functions print("radians(x1) = ", math.radians(x1), "\n\t\tradians(x2) = ", math.radians(x2)) print("degrees(y1) = ", math.degrees(y1), "\n\t\tdegrees(y2) = ", math.degrees(y2)) Constants and Angle Conversions - Output

>>> pi = 3.141592653589793 e = 2.718281828459045 x1 = 45 x2 = 60 y1= 1.0471975511965976 y2 = 1.5707963267948966 radians(x1) = 0.7853981633974483 radians(x2) = 1.0471975511965976 degrees(y1) = 59.99999999999999 degrees(y2) = 90.0 >>>

TrigTable.py # We'll need the math library import math

# x will go from 0 degrees to 90 degrees for x in range(0, 91) : #convert degrees to radians radians = x*math.pi/180.0

# calculate sine, cosine and tangent # for x sinx = math.sin(radians) cosx = math.cos(radians) # tan 90 degrees is infinite # so just write "infinity" # Inboth cases print the values if x != 90 : tanx = math.tan(radians) print(" %2d %7.5f\t%7.5f\t%9.5f" %(x, sinx, cosx, tanx)) else : tanx = "infinity" print(" %2d %7.5f\t%7.5f %s" %(x, sinx, cosx, tanx))

Rewriting the Payroll Program

# A simple payroll progam that uses a method # to calculate the gross pay def main() : # Ask the user for payrate rate = float(input("What is rate of pay for the employee?"))

# Enter the hours worked hours = float(input("Enter the hours worked?"))

# Get the gross pay pay = gross(hours, rate) print("Gross pay is $%4.2f" % (pay)) # gross() - Calculate the gross pay. def gross(hours, rate) : # If hours exceed 40, pay time and a half if hours > 40 : pay = 40*rate + 1.5*rate*(hours-40) else : pay = rate * hours; return pay main()

Average3d.py

# Find the average of three numbers using a # function def main() : # Get the inputs value1 = getValue() value2 = getValue() value3 = getValue()

# Call the function that calculates the # average average = findAverage(value1, value2, value3) print("The average is ", average) # getValue() - Prompt the user and read a value def getValue() : x = int(input("Enter a value ?")) return x

# findAverage() - Find the average of three # numbers def findAverage(x, y, z) : sum = x + y + z average = sum / 3 return average main()

What Are Lists?

• A list is an ordered sequence of data items. • We can construct a list by simply writing its contents enclosed by brackets [] and separated by commas. • Examples ["Jets", 2014, "Joe Namath"] [14, 18, 23,28, 34, 42] Declaring a List

• To have a variable name represent a list means that we have to assign a list to it. myList = []

List Operations

• len – number of items in the list • count – number of occurrences of a given data item on the list • clear – clear the list of all values • append – insert a data item at the end of the list List Operations

• extend – add the items on another list to the end of the list • remove – remove the first occurrence of an item from the list • insert – insert a new item into a particular spot on the list

len() • len() – returns the number of items on the list. • Example >>> words = ["green", "eggs", "ham", "sam"] >>> x = len(words ) >>> print(x) 4 >>> count()

• l.count(x) returns the number of times that x occurs on the list l. • Example >>> words = ["green", "eggs", "ham", "sam", "ham"] >>> x = words.count("ham") >>> print(x) 2 >>>

clear()

• l.clear() removes everything from list l, which is now empty. • Example >>> words = ["green", "eggs", "ham", "sam"] >>> words.clear() >>> print(words) [] >>> append()

• l.append() places an additional item at the end of list l • Example >>> words = ["green", "eggs", "ham", "sam"] >>> words.append("iam ") >>> print(words) ['green', 'eggs', 'ham', 'sam', 'iam']

extend()

• l.extend() inserts additional elements on the end of list l • Example >>> words = ["green", "eggs", "ham", "sam"] >>> words.extend(["i", "am"]) >>> print(words) ['green', 'eggs', 'ham', 'sam', 'i', 'am'] >>> remove()

• l.remove() removes the first occurrence of a data item from the list. • Example >>> words = ["green", "eggs", "ham", "sam", "i", "am", "i"] >>> words.remove("i") >>> print(words) ['green', 'eggs', 'ham', 'sam', 'am', 'i'] >>>

insert()

• l.insert(x, myItem)inserts new item myItem before item in position x. • Example >>> words = ["green", "eggs", "ham", "sam"] >>> words.insert(1, "and") >>> print(words) ['green', 'and', 'eggs', 'ham', 'sam'] >>> Using A List

• We usually use lists to store homogeneous data items, i.e, data items of the same type. • We can use individual data items by specifying its position in the list: >>> words = ["green", "eggs", "ham", "sam"] >>> print(words[4]) sam >>> print(words[0]) green >>>

Lists and Indices

• A list of n items will have those items indexed from 0 to n-1. lowest index x[0] = 87 x[1] = 90 … … … x[9] = 93 highest index Using A List

• An index can be any integer literal, variable or expression: x[6] = x[5] + 4; x[five] = 34; x[i+1] = x[i] + 3; • This is really useful, because we do not want to have to write separate statement to assign values to each list element.

Reading Values Into A List

• First, we need to declare x as a list by writing: x = [] • Then we can read values and then append them to the list: for i in range(10) : a = int(input("Enter a value?")) x.append(a) Using a Counting Loop To Set An Array • Counting loops are really useful when manipulating arrays: for i in range(10) : print(x[i])

for Loop Revisited

• We have seen for loops with the syntax: – for i in range( n) : – statement(s) • What range(n) returns is the list [0, 1, 2, .., n-1] • In reality, the for statement’s syntax is: for i in [ listitems ] : statement(s) for Loops - Example states = ["New York", "New Jersey", “Delaware"] for thisState in states : print("I\'ve visited ", thisState)

for number in [2, 3, 5, 7, 11, 13] : print(number, "is a prime number.")

The Guest Attendance Program # Putting together a guest list and keeping # track of who is and isn't coming def main() : # We let Python know that nameList is a list nameList = []

# Get the names of the invited guests numNames = getNames(nameList)

# Find out who is and isn't attending attendingList = getAttendance(nameList)

# Print the results printAttendance(numNames, nameList, attendingList) def getNames(nameList) : # Initially there are no guest numNames = 0

# Get the first name nextName = input("Enter another name")

# As long as we haven't found the sentinel # value get another name while nextName.lower() != "done" : # Add the name to the list nameList.append(nextName)

# Get the next name nextName = input("Enter another name")

# Add one to the count of names numNames = numNames + 1 return numNames def getAttendance(nameList) : # Let Pythonknow that attendList is a list attendingList = []

# For each guest, find out if they are attending for name in nameList : attending = input ("Is " + name + " coming to the party?")

# If they do not respopnd with yes or no, # ask again while attending.lower() != "yes" and attending.lower() != "no" : attending = input("Is " + name + " coming to the party?")

attendingList.append(attending) return attendingList # Print whether each guest us attending or not def printAttendance(numNames, nameList, attendingList) : for i in range(numNames) : if attendingList[i].lower() == "yes" : print(nameList[i], "is attending.") else : print(nameList[i], "is not attending.") main()