#!/usr/bin/env python # coding: utf-8 # In[5]: # Section 4.4 -- calculating a running total # Example program -- sum 5 numbers from a user # set the max summands MAX=5 #define my accumulator variable total=0.0 for counter in range(MAX): numbertoadd=float(input("What is your next number?")) total=total+numbertoadd print("The sum of the numbers is",total) # In[6]: # Another option for updating variables # so-called augmented assignment operators # Operator Equivalent to Result using x=6 # += x=x+3 --- x+=3 x==9 # -= x=x-2 --- x-=2 x==4 # *= x=x*2 --- x*=2 x==12 # /= x=x/2 --- x/=2 x==3 # %= x=x%4 --- x%=4 x==2 # # In[11]: # Section 4.5 - sententials # Definition: A sentential is a special symbol that marks # the end of a sequence of values. # # Situation: use this when you're writing code and you don't # know how many times to loop # # Options for the situation: # 1. ask user if they want another value (downside: could be cumbersome) # 2. ask user how many loops to do at beginning (downside: painful for user) # 3. use a senential! # # Height of patients - program will calculate the average # weight of patients given to the computer. We will write # a prompt "Enter weight or 0 if done." # 0 is a good value because: no one weights 0 pounds # # Average of n items: (sum of the n items)/n # # we will need two accumulators: one for the total weight # inputted by the user and one for how many weights are # included # define accumulators # count variable count=0 #for the denominator of the average sum_of_weights=0.0 new_weight=float(input("Enter the weight or 0 to stop.")) while(new_weight != 0): sum_of_weights+=new_weight count+=1 new_weight=float(input("Enter the weight or 0 to stop.")) if(count!=0): print("The average weight is",sum_of_weights/count) # In[ ]: # Annual tax on property # Goal -- write program that calculates the tax on a list of properties received that day # Each property in the county is assigned a lot number. # Turns out: in an interview with client, you discover that lot numbers start at 1 # magic number TAX_FACTOR=0.0065 lot_num=int(input("What lot number? Enter 0 if done.")) print("Lot Number\t Tax") while lot_num!=0: value_of_property=float(input("What is the value of lot?")) tax=value_of_property*TAX_FACTOR print(lot_num,"\t","$",tax,sep='') lot_num=int(input("What lot number? Enter 0 if done.")) # unexpectedly: the program doesn't make a nice list in the # end because it keeps asking for new info which screws up # the list -- we COULD get around this by making a list of # the data collected -- but we don't technically know how yet # -- we will see later # In[29]: # Formatting floats to 2 decimal places var=1232132131.234534324324 #var="abcd" print(var) print(format(var,',.2f'),format(var,'.5f')) print(var)