240 likes | 351 Views
COMPSCI 101 S1 2014 Principles of Programming. 11 Conditions within Loops. Learning outcomes. At the end of this lecture, students should be able to: Write a program that combines a for loop and an if statement. Examples and Exercises Exercise 1: Printing Even Numbers
E N D
COMPSCI 101 S1 2014Principles of Programming 11 Conditions within Loops
Learning outcomes • At the end of this lecture, students should be able to: • Write a program that combines a for loop and an if statement. • Examples and Exercises • Exercise 1: Printing Even Numbers • Exercise 2: Counting 3-letter Words • Case Study 1: Counting Alphabetic Letters • Case Study 2: Counting Vowel Letters • Case Study 3: Comparing Strings COMPSCI101
11.1 ReviewConditions • Simple Conditions • The statements involve tests or conditions • Simple if Statements • A one-way if statement executes the statements if the condition is true • The general Python syntax for a simple if statement is x == 11 x > 10 if condition : indented_Code_Block if weight > 50: print("There is a $25 charge for luggage that heavy.") print("Thank you for your business.") COMPSCI101
11.1 ReviewConditions • if-else Statements • A two-way if-else statement decides which statements to execute based on whether the condition is true or false. • The general Python if-else syntax is • Example: if condition : indented_Code_Block_For_True_Condition else: indented_Code_Block_For_False_Condition if temperature > 70: print('Wear shorts.') else: print('Wear long pants.') print('Get some exercise outside.') COMPSCI101
11.1 Review Grade Test Demo 02 • Using nested if-else statements to convert a numerical mark to a letter grade defscore_to_grade(score): if score >= 90: letter = 'A' else: # grade must be B, C, D or F if score >= 80: letter = 'B' else: # grade must be C, D or F if score >= 70: letter = 'C' else: # grade must D or F if score >= 60: letter = 'D' else: letter = 'F' return letter COMPSCI101
11.1 Review Grade Test V2 Demo 03 • Using if-elif statements to convert a numerical mark to a letter grade • Exactly one of the indented blocks is executed! defscore_to_grade_v2 (score): if score >= 90: letter = 'A' elif score >= 80: letter = 'B' elif score >= 70: letter = 'C' elif score >= 60: letter = 'D' else: letter = 'F' return letter COMPSCI101
11.1 ReviewConditions (con’t) • Nested if and Multi-way if-elif-else Statements • The general Python if-elif-else syntax is if condition1 : indented_Code_Block_For_True_Condition_1 elif condition2 : indented_Code_Block_For_True_Condition_2 elif condition3 : indented_Code_Block_For_True_Condition_3 else: indented_Code_Block_ForEachCondition_False COMPSCI101
11.1 ReviewCommon Errors SyntaxError: invalid syntax IndentationError: expected an indented block • What is wrong? if x = 0: print (x) if weight > 50: print("There is a $25 charge for luggage that heavy.") D if score >= 60: letter = 'D' elif score >= 70: letter = 'C' elif score >= 80: letter = 'B' elif score >= 90: letter = 'A' else: letter = 'F' D D COMPSCI101
11.1 Review The for loop Demo 01 • A Python for loop iterates through each value in a sequence. • The general Python syntax is • Example: for item in sequence: indented_Code_Block for count in [1, 2, 3]: print(count) print('Done counting.') 1 2 3 Done counting. red blue green for colour in ['red', 'blue', 'green']: print(colour) COMPSCI101
11.1 ReviewCommon Errors • What is wrong? IndentationError: expected an indented block for count in [1, 2, 3]: print (count) ‘red’ ‘red’ ‘red’ for colourin ['red', 'blue', 'green']: print('red') COMPSCI101
11.2 Conditions within LoopsConditions within Loops • for and if statements can be nested inside each other’s indented blocks • The general Python if-elif-else syntax is If no more items in sequence Item from sequence for item in sequence: if condition : indented_Code_Block Non_indented_statement Next item Condition? True Execute statements False COMPSCI101
11.2 Conditions within Loops Printing Positive Numbers Demo 04 • Task: • Complete the print_positive() function which prints positive numbers in a list • Arguments: a list of integers print_positive([-1, 2, 3]) 2 3 Item from sequence for number in number_list: If no more items in sequence Next item if number > 0 : >0 ? Print item print (number) COMPSCI101
Exercise1: Printing Even Numbers • Task: • Complete the print_evens() function which prints even numbers in a list. • Arguments: a list of Integers • Information produced: prints all even numbers in the list COMPSCI101
Case Study 1:Counting Alphabetic Letters • Task: • Complete the count_alphas() function which counts the number of alphabetic letters in a string • Arguments: a string • Returns: the number of alphabetic letters in a string • Cases: A, B…Z a, b, … z 0 count_alphas('123') 10 count_alphas('Hello world') 11 len('Hello world') COMPSCI101
Try Demo 5 Case Study 1: Counting Alphabetic Letters • Algorithm: for letter in word: if letter.isalpha(): COMPSCI101
Case Study 2:Counting Vowel Letters • Task: • Complete the count_vowels() function which counts the number of vowels in a string • Arguments: a string • Returns: the number of vowel letters • Cases: A, E, I, O, U, a, e, i, o, u 0 count_vowels('123') 3 count_vowels('Hello world') 11 len('Hello world') 10 count_alphas('Hello world') COMPSCI101
Case Study 2: Counting Vowel Letters • Algorithm: COMPSCI101
Case Study 2: Membership operators • The In Operator • Evaluates to true if it finds a variable in the specified sequence and false otherwise. a = 10 b = 2 list = [1, 2, 3, 4, 5 ] if ( a in list ): print ('a is a member of list') else: print ('a is not a member of list') if ( b in list ): print ('b is a member of list') else: print ('b is not a member of list') a is not a member of list b is a member of list COMPSCI101
Try Demo 6 Case Study 2:Counting Vowel Letters • Algorithm: for letter in word: if letter in vowels: COMPSCI101
Exercise 2Counting 3-letter words • Task: • Complete the count_3letters() function which counts the number of three-letter words in a list • Information Required: a list of strings • Information produced: the number of 3-letter words in a list • Cases: 2 ['dog','letter', 'stop' ,'see'] 0 ['stop', 'input'] 0 ['happy'] COMPSCI101
Exercise 2Counting 3-letter words • Algorithm: for word in words if len(word) == 3: count += 1 COMPSCI101
Case Study 3Comparing Strings • Task: • Complete the words_after()function which finds all the words in a list which are alphabeticallylater than the given parameter • Arguments: a string and a list of strings • Returns: a sub list • Cases: words_after('b', ['a', 'alien', 'b', 'banter', 'class', 'classic', 'zebra']) ['banter', 'class', 'classic', 'zebra'] words_after('z', ['zebra', 'a', 'alien', 'b', 'banter', 'class', 'classic'] ['zebra'] COMPSCI101
Try Demo 7 Case Study 3Comparing Strings • Algorithm: new_words = [] if word > another_string: new_words.append(word) COMPSCI101
Summary • A Boolean type variable can store a True or False value. • The relational operators (<, <=, ==, !=, >, >=) which work with numbers and strings, yield a Boolean value. • The part of the loop that contains the statements to be repeated is called the loop body • In designing loops, you need to consider both the loop-control structure and the loop body. • Examples: for word in words: if word > another_string: new_words.append(word) for letter in word: if letter.isalpha(): count += 1 COMPSCI101