200 likes | 311 Views
Writing Simple Programs. Chapter Two. # convert.py # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell def main(): celsius = input("What is the Celsius temperature? ") fahrenheit = 9.0 / 5.0 * celsius + 32
E N D
Writing Simple Programs Chapter Two
# convert.py # A program to convert Celsius temps to Fahrenheit # by: Susan Computewell def main(): celsius = input("What is the Celsius temperature? ") fahrenheit = 9.0 / 5.0 * celsius + 32 print "The temperature is", fahrenheit, "degrees Fahrenheit." main() Note that indentation defines statements in main()
Workshop • Change the convert.py program so it converts dollars to Euros. • Find the current rate online • Work in pairs
Names: modules, functions, variables • All names are called identifiers. • Python rules: all identifier smust begin with a letter or underscore (_) • Identifiers are case sensitive • Choose identifiers that describe what is being named • Reserved words cannot be used as identifiers
Reserved Words • and assert break • class continue def • del elif else • except exec finally • for from global • if import in • is lambda not • or pass print • raise return try • while yield
Expressions • Expressions are code fragments which manipulate data • When you “hard code” data or characters into your code, you are creating “literals” • Name Errors are produced when Python can’t find a value associated with an identifer • Spaces don’t matter inside expressions. • Arithmetic operators: + - * / ** (the last one is exponentiation)
Workshop • Using the Python interpreter, create a variable called subtotal equal to 118.45 • Print subtotal • Write an expression which adds a tax of 8% to subtotal • Ask the interpreter to print a variable called item_cost
Printing output • The print command displays output on the screen • Try these examples: • print by itself produces a blank line • Separating values with a comma means you can print multiple values : print 8, 9, 10 • You can print expressions: print (8 * 8) / 2 • You can also print string literals (characters between quotations which the programmer hard codes): print “The area of a circle is “, 4 * 4 * 3.14
Simple assignment statements • <variable> = <expr> • Example: euro = dollar * 1.39 • Assignment is ALWAYS right to left. In other words, the value on the right is “loaded into” the variable on the left. • You can assign a new value to an existing variable. newVar = 21 newVar = 55
Garbage Collection • When you assign a new value to a variable, the old value is still in memory, just without reference. 21 newVar 21 newVar 55
Getting user input • Python makes getting user input really easy. The reserved word input gets data from the user and loads it into a variable. • dollars = input(“Please enter the dollar amount you want converted to euros: ”) • Python evaluates the prompt and displays it on screen. Python pauses and waits for user input.
Simultaneous assignment • Python allows you to simultaneously assign several variables—it’s a shortcut • tax, subtotal, total = .08, 0, 0 • Simultaneous assignment can use expressions as well as literals:sale_price, total = unit_price * .75, subtotal * .08
# avg2.py # A simple program to average two exam scores. # Illustrates use of multiple input. def main(): print "This program computes the average of two exam scores." print score1, score2 = input("Enter two scores separated by a comma: ") average = (score1 + score2) / 2.0 print "The average of the scores is:", average main()
Definite loops • A definite loop just repeats a number of actions (or statements) a definite number of times. Python knows when to stop the loop (because you tell it so) • This is also called iteration, and a definite loop is an iterative loop or iterative control structure • For <var> in <sequence>: <expr> <expr>…
Example of definite loop Loop index; changes value each time the body statements are executed • for i in range(10): x = 3.9 * x * (1-x) print x • range(10) is a built-in Python command which controls the number of times the loop is executed. It will start at 0 and quit after 9 (always by integers) Body
Lists of values as sequencers • The command range(10) is really a convenient shorthand for a list of values:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] • The definite loop changes the value of the loop index to match the progression of values in the sequence. • For x in [7, 14, 21, 28]: print x • And the screen result will be:7142128
Workshop • Have the Python Interpreter print the squares of the odd numbers between 0 and 20, using a definite loop
# futval.py # A program to compute the value of an investment # carried 10 years into the future def main(): print "This program calculates the future value of a 10-year investment." principal = input("Enter the initial principal: ") apr = input("Enter the annual interest rate: ") for i in range(10): principal = principal * (1 + apr) print "The value in 10 years is:", principal main()
Workshop • Alter the futval.py program so that it displays the value of the investment each year • Alter the futval.py program so that the user controls the number of years the investment will accrue