DOC PREVIEW
UNI CS 1520 - Lecture Notes

This preview shows page 1-2-3 out of 10 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 10 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 10 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 10 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 10 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Control Statements:if statements: An if statement allows code to be executed or not based on the result of a comparison. If thecondition evaluates to True, then the statements of the indented body is executed. If the condition is False,then the body is skipped. The syntax of if statements is:if <condition>: statementT1 statementT2elif <condition2>: statement statementelse: statementF1 statementF2if <condition>: statementT1 statementT2else: statementF1 statementF2if <condition>: statement1 statement2 statement3 Typically, the condition involves comparing “stuff” using relational operators ( <, >, ==, <=, >=, != ). Complex conditions might involve several comparisons combined using Boolean operators: not, or, and.For example, we might want to print “Your grade is B.” if the variable score is less than 90, but greater than orequal to 80. if score < 90 and score >= 80: print “Your grade is B.”The precedence for mathematical operators, Boolean operators, and comparisons are given in the table.. for loop: the for loop iterates once for each item in some sequence type (i.e, list, tuple, string). for character in 'house': print characterfor value in [1, 3, 9, 7]: print valueOften the for loop iterates over a list generated by the built-in range function which has the syntax of:range([start,] end, [, step]), where [ ] are used to denote optional parameters. Some examples: range(5) generates the list [0, 1, 2, 3, 4] range(2,7) generates the list [2, 3, 4, 5, 6] range(10,2,-1) generates the list [10, 9, 8, 7, 6, 5, 4, 3]Since the list generated by the range function needs to be stored in memory, a more efficient xrangefunction is typically using in for loops to generate each value one at a time for each iteration of the loop. Forexample:for count in xrange(1,6): print count, " " ,print "\nDone"Name:_________________________Python Summary Page 1 = (assignment)orandnot<, >, ==, <=, >=, !=, <>, is, is not +, - (add, sub)*, /, % (remainder) +, - (unary pos. & neg.) ** (exponential)Operator(s)highestlowest1 2 3 4 5Donewhile loop: A while statement allows code to be executed repeated (zero or more times) as long as thecondition evaluates to True. The syntax of a while statement is:while <condition>: statement1 statement2 statement3An infinite loop is one that would loop forever. (FYI, in a Python shell ctrl-c (^c)can be used to kill the running program.) Most infinite loops are caused by programmer error, but sometimesthey are intentional. The following “sentinel-controlled” code uses an infinite loop and a break statement thatimmediately causes control to exit the loop.total = 0counter = 0while True: # an infinite loop score = input("Enter a score (or negative value to exit): ") if score < 0: break total += score counter += 1print "Average is", float(total)/counterStrings: Strings in Python are sequential collections of only characters. Strings are immutable (i.e., cannot bechanged), so new strings are generated by string operations. Operations on strings (or any sequence collection)include:8len( myString )How many items are in thestring?len(string)LengthTrue‘ell’ in myStringAsk whether a substring is ina stringinMembership‘catcatcat’aString * 3Concatenate a repeatednumber of times*Repetition‘Hello!!!cat’myString + aStringCombine strings together+Concatenation‘ello’myString[ 1:5 ]Extract a part of the string[ : ]Slicing‘e’myString[1]Access the element specifiedby the index[ <index> ]IndexingResult ofExampleExamplemyString = “Hello!!!”aString = “cat”ExplanationOperatorOperationIndexing of strings starts with 0 on the left end, and -1 on the right end: 1111 01234567890123cheer = ‘GO Panthers!!!’ -4-3-2-1Omitted indexes in a slice means “from the end.” For example, cheer[:4] generates ‘GO P’.Omitted indexes in a slice means “from the end.” For example, cheer[-4:] generates ‘s!!!’.Name:_________________________Python Summary Page 2Is condition true? Statements in loop bodyFalseTrueString objects also have the following methods: (the string module can be imported to provide moreoperations.)Returns a string with all occurrences of substring old replaced bysubstring new. An additional integer parameter can specify thenumber of replacements to perform, e.g.,myString.replace(old,new,3)myString.replace(old,new)replaceReturns the starting index of the first occurrence of sub.(Optional parameters: myString.find(sub [, start [, end] ] )myString.find(sub)findReturns a list of substrings of myString splits at whitespacecharacters.An optional string parameter can supply characters to split on.myString.split( )splitReturns True if myString contains only letters; otherwise it returnsFalsemyString.isalpha( )isalphaReturns True if myString contains only digits; otherwise it returnsFalsemyString.isdigit( )isdigitReturns True if myString starts with the substring sub; otherwise itreturns False myString.startswith(sub)startswithReturns True if myString ends with the substring sub; otherwise itreturns False myString.endswith(sub)endswithReturns number of occurrences of sub in myString(Optional parameters: myString.count(sub [, start [, end] ] ) myString.count(sub)countReturns a string with leading and trailing whitespace (space, tab,new-line) chars. removed. An optional string parameter can beused to supply characters to strip instead of whitespace.myString.strip( )stripReturns a string with myString in all lower-case charactersmyString.lower( )lowerReturns a string with myString in all upper-case charactersmyString.upper( )upperReturns a string with myString right-justified in a field of size wmyString.rjust(w)rjustReturns a string with myString left-justified in a field of size wmyString.ljust(w)ljustReturns a string with myString centered in a field of size wmyString.center(w)centerExplanationUsageMethodLists: A Python list is also a sequence collection, but a list can contain items of any type (e.g., character,strings, integers, floats, other lists, etc. ), and lists are mutable. Lists are represented by comma-separated valuesenclosed in square brackets (‘[’, ‘]’). Operations on lists (or any sequence collection, e.g., strings) include:4len( myList )How many items are inthe list?len(list)LengthFalse3 in myListAsk whether an item isin a listinMembership[8,


View Full Document

UNI CS 1520 - 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?