We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25
Conditionals and recursion
Floor division and modulus
• floor division operator, //, divides two numbers and rounds down to an integer • Conventional division returns a floating-point number: Example1: minutes = 105 minutes / 60 Example2: minutes = 105 minutes // 60 modulus operator % -divides two numbers and returns the remainder. remainder = minutes % 60 remainder Format function Format n = float(input()) print("{:.2f}".format(n)) Or n=float(input()) print("The price is %.2f" %n) Boolean expressions • Returns either true or false • Example: 5 == 5 5 == 6 True and False are special values that belong to the type bool; they are not string type(True) Relational operators x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y Logical operators: and, or, and not • x > 0 and x < 10 • n%2 == 0 or n%3 == 0 either or both of the conditions is true Conditional execution • Ability check conditions and change the behavior of the program accordingly • if statement: • Example if x > 0: print('x is positive’) • If it is true, the indented statement runs. If not, nothing happens. Alternative execution • two possibilities and the condition determines which one runs if x % 2 == 0: print('x is even') else: print('x is odd') Chained conditionals • more than two possibilities and we need more than two branches if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal’) • elif is an abbreviation of “else if”. Nested conditionals • One conditional can also be nested within another if x == y: print('x and y are equal') else: if x < y: print('x is less than y’) else: print('x is greater than y') Nested conditionals if 0 < x: if x < 10: print('x is a positive single-digit number.’) or if 0 < x and x < 10: print('x is a positive single-digit number.’) Or if 0 < x < 10: print('x is a positive single-digit number.') Recursion • A function that calls itself is recursive; the process of executing it is called recursion def countdown(n): if n <= 0: print('Blastoff!’) else: print(n) countdown(n-1) countdown(3) Output: 3 2 1 Blastoff! Stack diagrams for recursive functions • the top of the stack is the frame for _ _main_ _ • Main is empty because no variables in _ _main_ _ • four countdown frames have different values for the parameter n • bottom of the stack, where n=0, is called the base case. Infinite recursion • If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. def recurse(): recurse() Keyboard input Python provides a built-in function called input to get input from user text = input() Fruitful functions Return values • Returns the area of a circle with the given radius def area(radius): a = math.pi * radius**2 return a • Fruitful function the return statement includes an expression. • Return immediately from this function and use the following expression as a return value def area(radius): return math.pi * radius**2 Iteration • ability to run a block of statements repeatedly • Reassignment: : Assigning a new value to a variable that already exists. • Updating variables: x=x+1 while statement def countdown(n): while n > 0: print(n) n=n-1 print('Blastoff!') • flow of execution for a while statement • 1.Determine whether the condition is true or false. • 2. If false, exit the while statement and continue execution at the next statement. • 3. If the condition is true, run the body and then go back to step 1 Strings • string is a sequence of characters • access the characters one at a time with the bracket operator • Example: fruit = 'banana’ Print(fruit[1]) Print(fruit[1.5]) • len is a built-in function that returns the number of characters in a string • len(fruit) Traversal with a for loop • while loop: • For loop index = 0 for letter in fruit: while index < len(fruit): print(letter) letter = fruit[index] Example: print(letter) index = index + 1 prefixes = 'JKLMNOPQ’ suffix = 'ack’ for letter in prefixes: print(letter + suffix) String slices • segment of a string is called a slice. Selecting a slice is similar to selecting a character s = 'Monty Python’ s[0:5] s[6:12] • operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character • Including the first but excluding the last • fruit = 'banana’ • fruit[:3] • fruit[3:] • fruit[3:3] • fruit[:] Strings are immutable • greeting = 'Hello, world!’ • greeting[0] = 'J’ • TypeError: 'str' object does not support item assignment • can’t change an existing string • create a new string that is a variation on the original greeting = 'Hello, world!' new_greeting = 'J' + greeting[1:] new_greeting O/P: 'Jello, world!' Searching def find(word, letter): index = 0 while index < len(word): if word[index] == letter: return index index = index + 1 return -1 Looping and counting • program counts the number of times the letter a appears in a string word = 'banana' count = 0 for letter in word: if letter == 'a’: count = count + 1 print(count) String method • method is similar to a function—it takes arguments and returns a value,but the syntax is different • function syntax upper(word) • method syntax word.upper() • word = 'banana’ • word.upper() • word.find('a’) # find starts at the beginning of the string and return the index • word.find(‘na’) # find substrings, not just characters • word.find('na', 3) # a second argument represent the index where it should start • name.find('b', 1, 2) # third argument optional argument represents the index where it should stop • name = 'bob’ • name.find('b', 1, 2) • O/P: -1 in operator • 'a' in 'banana’ • O/P: True • 'seed' in 'banana’ • O/P:False String comparison • The relational operators work on strings. To see if two strings are equal: if word == 'banana’: print('All right, bananas.') • Other relational operations are useful for putting words in alphabetical order: if word < 'banana’: print('Your word, ' + word + ', comes before banana.') elif word > 'banana’: print('Your word, ' + word + ', comes after banana.') else: print('All right, bananas.’) Note: uppercase letters come before all the lowercase letters Eg:Your word, Pineapple, comes before banana.