CSC 272 - Software II: Principles of Programming Languages
Total Page:16
File Type:pdf, Size:1020Kb
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. # Read 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 write: 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.