Python Control Structures Lecture Notes PDF
Document Details
![SpellbindingRococo7161](https://quizgecko.com/images/avatars/avatar-12.webp)
Uploaded by SpellbindingRococo7161
Kumaraguru College of Technology
S.P. Siddique Ibrahim
Tags
Summary
This document is a set of lecture notes on Python control structures. It covers sequential, decision (if/else), and iterative (while, for) structures, along with examples. Examples include the uses of if statements, loops, and logical operators in Python.
Full Transcript
Python Control Structure by S.P. Siddique Ibrahim AP/CSE Kumaraguru College of Technology Coimbatore 1 Introduction Says the control flow of the statement i...
Python Control Structure by S.P. Siddique Ibrahim AP/CSE Kumaraguru College of Technology Coimbatore 1 Introduction Says the control flow of the statement in the programming language. Show the control flow 2 Control Structures 3 control structures ◦ Sequential structure Built into Python ◦ Decision/ Selection structure The if statement The if/else statement The if/elif/else statement ◦ Repetition structure / Iterative The while repetition structure The for repetition structure 3 4 Sequential Structure Normal flow/sequential execution of the statement. Line by line/Normal execution If you want to perform simple addition: A=5 B=6 Print(A+B) 5 Sequence Control Structure add grade to total total = total + grade; add 1 to counter counter = counter + 1; Fig. 3.1 Sequence structure flowchart with pseudo code. 6 Decision Control flow There will be a condition and based on the condition parameter then the control will be flow in only one direction. 7 8 9 10 11 if Selection Structure true Grade >= 60 print “Passed” false Fig. 3.3 if single-selection structure flowchart. 12 13 14 15 16 17 Control Structures 18 >>> x = 0 >>> y = 5 >>> if x < y: # Truthy ... print('yes') ... yes >>> if y < x: # Falsy ... print('yes') ... >>> if x: # Falsy ... print('yes') ... >>> if y: # Truthy ... print('yes') ... yes >>> if x or y: # Truthy ... print('yes') ... yes 19 >>> if x and y: # Falsy ... print('yes') ... >>> if 'aul' in 'grault': # Truthy ... print('yes') ... yes >>> if 'quux' in ['foo', 'bar', 'baz']: # Falsy ... print('yes') 20 If else: 21 if/else Structure false true Grade >= 60 print “Failed” print “Passed” Fig. 3.4 if/else double-selection structure flowchart. 22 23 Class Activity # Program checks if the number is positive or negative and displays an appropriate message # Program checks if the number is positive or negative –Get the input from the user also checks the zero inside the positive value 24 num =3 # Try these two variations as well. # num = -5 # num = 0 if num >= 0: print("Positive or Zero") else: print("Negative number") 25 Contd., 26 if/elif/else Selection Structure true if statement condition a case a action(s) false true first elif condition b case b action(s) statement false... last elif true condition z case z action(s) statement false else default action(s) statement Fig. 3.5 if/elif/else multiple-selection structure. 27 syntax 28 Example Python code 29 Example with Python code # get price from user and convert it into a float: price = float( raw_input(“Enter the price of one tomato: “)) if price < 1: s = “That’s cheap, buy a lot!” elif price < 3: s = “Okay, buy a few” else: s = “Too much, buy some carrots instead” print s 30 Control Structures 31 32 3.7 while Repetition Structure true Product = 5: break # Prints out only odd numbers - 1,3,5,7,9 for x in range(10): # Check if x is even if x % 2 == 0: continue print(x) 46 47 Example for Pass 48 Expression values? Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> if 0:... print "0 is true"... else:... print "0 is false"... 0 is false >>> if 1:... print "non-zero is true"... non-zero is true >>> if -1:... print "non-zero is true"... non-zero is true >>> print 2 < 3 1 Expressions have integer values. No true, false like in Java. 0 is false, non-0 is true. 49 3.16 Logical Operators Operators ◦ and Binary. Evaluates to true if both expressions are true ◦ or Binary. Evaluates to true if at least one expression is true ◦ not Unary. Returns true if the expression is false Compare with &&, || and ! in Java 50 Logical operators and, or, not if gender == “female” and age >= 65: seniorfemales = seniorfemales + 1 if iq > 250 or iq < 20: strangevalues = strangevalues + 1 if not found_what_we_need: print “didn’t find item” # NB: can also use != if i != j: print “Different values” 51 Example 52 3.11 Augmented Assignment Symbols Augmented addition assignment symbols ◦ x = x + 5 is the same as x += 5 ◦ Can’t use ++ like in Java! Other math signs ◦ The same rule applies to any other mathematical symbol *, **, /, % 53 Keywords Python keywords and continue else for import not raise assert def except from in or return break del exec global is pass try class elif finally if lambda print while Fig. 3.2 Python keywords. Can’t use as identifiers 54 keyword pass : do nothing Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> if 1 < 2:... pass... Sometimes useful, e.g. during development: if a 5: pass # figure out what to do later 55 1 # Fig. 3.10: fig03_10.py 2 # Class average program with counter-controlled repetition. 3 4 # initialization phase The total and counter, set to 5 total = 0 # sum of grades 6 gradeCounter = 1 # number of grades entered zero and one respectively 7 A loop the continues as long as 8 9 10 Program Output # processing phase while gradeCounter