DOC PREVIEW
UW CSE 142 - Lecture Notes

This preview shows page 1-2-3-4-5-6 out of 17 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 17 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 17 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 17 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 17 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 17 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 17 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 17 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Unit 4If/else, return, user input, stringsSpecial thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides.Except where otherwise noted, this work is licensed under:http://creativecommons.org/licenses/by-nc-sa/3.02Math commandsfrom math import *convert degrees to radiansradians(value)convert radians to degreesdegrees(value)square rootsqrt(value)logarithm in any baselog(value, base)rounds downfloor(value)rounds upceil(value)nearest whole numberround(value)tangenttan(value)sine, in radianssin(value)smaller of two (or more) valuesmin(value1, value2, ...)larger of two (or more) valuesmax(value1, value2, ...)logarithm, base 10log10(value)cosine, in radianscos(value)absolute valueabs(value)DescriptionFunction name3.1415926...pi2.7182818...eDescriptionConstant3Returning valuesdef name(parameters):statements...return expression– Python doesn't require you to declare that your function returns a value; you just return something at its end.>>> def ftoc(temp):... tempc = 5.0 / 9.0 * (temp - 32)... return tempc>>> ftoc(98.6)37.04input : Reads a string from the user's keyboard.– reads and returns an entire line of input ** NOTE: Older v2.x versions of Python handled user input differently. These slides are about the modern v3.x of Python and above.input>>> name = input("Howdy. What's yer name?")Howdy. What's yer name? Paris Hilton>>> name'Paris Hilton'5• to read numbers, cast input result to an int or float– If the user does not type a number, an error occurs.– Example:age = int(input("How old are you? "))print("Your age is", age)print(65 - age, "years to retirement")Output:How old are you? 53Your age is 5312 years to retirementinput6ifif condition:statements– Example:gpa = float(input("What is your GPA? "))if gpa > 2.0:print("Your application is accepted.")7if/elseif condition:statementselif condition:statementselse:statements– Example:gpa = float(input("What is your GPA? "))if gpa > 3.5:print("You have qualified for the honor roll.")elif gpa > 2.0:print("Welcome to Mars University!")else:print("Your application is denied.")8if ... inif value in sequence:statements– The sequence can be a range, string, tuple, or list (seen later)– Examples:x = 3if x in range(0, 10):print("x is between 0 and 9")letter = input("What is your favorite letter? ")if letter in "aeiou":print("It is a vowel!")9Logical Operatorsnot (2 == 3)(2 == 3) or (-1 < 5)(2 == 3) and (-1 < 5) ExamplenotorandOperatorTrueTrueFalseResultTrue5.0 >= 5.0greater than or equal to>=False126 <= 100less than or equal to<=True10 > 5greater than>False10 < 5less than<True3.2 != 2.5does not equal!=True1 + 1 == 2equals==ResultExampleMeaningOperator10Exercise• Write a program that reads two employees' hours and displays each employee's total and the overall total.– Cap each day at 8 hours.Employee 1: How many days? 3Hours? 6Hours? 12Hours? 5Employee 1's total hours = 19 (6.33 / day)Employee 2: How many days? 2Hours? 11Hours? 6Employee 2's total hours = 14 (7.00 / day)Total hours for both = 3311Strings• Accessing character(s):variable [ index ]variable [ index1:index2 ]– index2 exclusive– index1 or index2 can beomitted (goes to end of string)-1-2-3-4-5-6-7-8orcharacterindex 2yddiD.P7654310>>> name = "P. Diddy">>> name[0]'P'>>> name[7]'y'>>> name[-1]'y'>>> name[3:6]'Did'>>> name[3:]'Diddy'>>> name[:-2]'P. Did'12String Methods>>> name = "Martin Douglas Stepp">>> name.upper()'MARTIN DOUGLAS STEPP'>>> name.lower().startswith("martin")True>>> len(name)20striptrimupper, lower,isupper, islower,capitalize, swapcasetoLowerCase, toUpperCaselen(str)lengthfindindexOfstartswith, endswithstartsWith, endsWithPythonJava13for Loops and Strings• A for loop can examine each character in a string in order.for name in string:statements>>> for c in "booyah":... print c...booyah14Formatting Text"format string" % (parameter, parameter, ...)•Placeholders insert formatted values into a string:– %d an integer– %f a real number– %s a string– %8d an integer, 8 characters wide, right-aligned– %08d an integer, 8 characters wide, padding with 0s– %-8d an integer, 8 characters wide, left-aligned– %12f a real number, 12 characters wide– %.4f a real number, 4 characters after decimal– %6.2f a real number, 6 total characters wide, 2 after decimal>>> x = 3; y = 3.14159; z = "hello">>> print "%-8s, %04d is close to %.3f" % (z, x, y)hello , 0003 is close to 3.14215Strings and Integers• ord(text) - Converts a string into a number.– ord("a") is 97– ord("b") is 98– Uses standard mappings such as ASCIIand Unicode.• chr(number) - Converts a number into a string.– chr(97) is "a"– chr(99) is "c"16Basic cryptography• Rotation cipher - shift each letter by some fixed amount– Caesar cipher - shift each letter forward by 3"the cake is a lie" becomes"wkh fdnh lv d olh"• Substitution cipher - transform each letter into another– not a linear shift; uses some kind of letter mapping– similar to "cryptogram" or "cryptoquip" games in newspaper17Exercise• Write a program that "encrypts" a secret message with a Caesar cipher, shifting the letters of the message by 3:– e.g. "Attack" when rotated by 1 becomes "cwwcfn"– If you have time, make the program able to undo the cipher.– Can you write a function that works for a substitution


View Full Document

UW CSE 142 - Lecture Notes

Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?