UNI CS 1520 - Lecture Notes (10 pages)

Previewing pages 1, 2, 3 of 10 page document View the full content.
View Full Document

Lecture Notes



Previewing pages 1, 2, 3 of actual document.

View the full content.
View Full Document
View Full Document

Lecture Notes

81 views


Pages:
10
School:
University of Northern Iowa
Course:
Cs 1520 - Data Structures
Unformatted text preview:

Name Control Statements if statements An if statement allows code to be executed or not based on the result of a comparison If the condition 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 statement1 statement2 statement3 if condition statementT1 statementT2 else statementF1 statementF2 if condition statementT1 statementT2 elif condition2 statement statement else statementF1 statementF2 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 or equal 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 Operator s exponential highest unary pos neg remainder add sub is is not not lowest and or assignment for loop the for loop iterates once for each item in some sequence type i e list tuple string for value in 1 3 9 7 print value for character in house print character Often 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 xrange function is typically using in for loops to generate each value one at a time for each iteration of the loop For example for count in xrange 1 6 1 2 3 4 5 print count Done print nDone Python Summary Page 1 Name while loop A while statement allows code to be executed repeated zero or more times as long as the condition evaluates to True The syntax of a while statement is while condition statement1 statement2 statement3 Is condition true False True Statements in loop body An 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 sometimes they are intentional The following sentinel controlled code uses an infinite loop and a break statement that immediately causes control to exit the loop total 0 counter 0 while True an infinite loop score input Enter a score or negative value to exit if score 0 break total score counter 1 print Average is float total counter Strings Strings in Python are sequential collections of only characters Strings are immutable i e cannot be changed so new strings are generated by string operations Operations on strings or any sequence collection include Operation Operator Explanation Example Result of myString Hello Example aString cat Access the element specified myString 1 index e Indexing by the index myString 1 5 ello Slicing Extract a part of the string myString aString Hello cat Concatenation Combine strings together Concatenate a repeated aString 3 catcatcat Repetition number of times Ask whether a substring is in ell in myString in True Membership a string How many items are in the len string len myString 8 Length string Indexing of strings starts with 0 on the left end and 1 on the right end 1111 01234567890123 cheer GO Panthers 4 3 2 1 Omitted 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 Python Summary Page 2 Name String objects also have the following methods the string module can be imported to provide more operations Method Usage Explanation center myString center w Returns a string with myString centered in a field of size w ljust myString ljust w Returns a string with myString left justified in a field of size w rjust myString rjust w Returns a string with myString right justified in a field of size w upper myString upper Returns a string with myString in all upper case characters lower myString lower Returns a string with myString in all lower case characters strip myString strip Returns a string with leading and trailing whitespace space tab new line chars removed An optional string parameter can be used to supply characters to strip instead of whitespace count myString count sub Returns number of occurrences of sub in myString Optional parameters myString count sub start end endswith myString endswith sub Returns True if myString ends with the substring sub otherwise it returns False startswith myString startswith sub Returns True if myString starts with the substring sub otherwise it returns False isdigit myString isdigit Returns True if myString contains only digits otherwise it returns False isalpha myString isalpha Returns True if myString contains only letters otherwise it returns False Returns a list of substrings of myString splits at whitespace split myString split characters An optional string parameter can supply characters to split on find myString find sub Returns the starting index of the first occurrence of sub Optional parameters myString find sub start end replace myString replace old new Returns a string with all occurrences of substring old replaced by substring new An additional integer parameter can specify the number of replacements to perform e g myString replace old new 3 Lists 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 values enclosed in square brackets Operations on lists or any sequence collection e g strings include Operation Operator Explanation Example Result of Example myList 5 6 7 8 ListB 8 9 Access the element Indexing index myList 2 7 specified by the index Slicing Extract a part of the list myList 1 3 6 7 Concatenation Combine lists together myList ListB 5 6 7 8 8 9 Concatenate a repeated Repetition ListB 3 8 9 8 9 8 9 number of times Ask whether an item is Membership in 3 in myList False in a list How many items are in Length len list len myList 4 the list Python Summary Page 3 Name The following list methods are provided by Python Method Usage Explanation myList append item append Adds item to the end of myList extend myList extend otherList Extends myList by adding all items in otherList to myList s end myList insert i item Insert


View Full Document

Access the best Study Guides, Lecture Notes and Practice Exams

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 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?