Python Control Structure by S P Siddique Ibrahim
Python Control Structure by S. P. Siddique Ibrahim AP/CSE Kumaraguru College of Technology Coimbatore 1
- id() and type() functions id() returns address of object in memory type() used to identify type of object >>> x = 12**2 - The ** operator is used for exponentiation (i. e raising of one no to the power of another) 2
Type Conversion
print statement • Syntax print(argument) print(argument, end=‘ ‘) • User input in python Name=input(“Enter your name”) print(“Hello”, Name, ”welcome to python programming”)
Introduction Says the control flow of the statement in the programming language. Show the control flow 5
Control Structures 3 control structures ◦ Sequential structure Built into Python ◦ Decision/ Selection structure The if statement The if/else statement ◦ Repetition structure / Iterative The while repetition structure The for repetition structure 6
7
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) 8
Sequence Control Structure add grade to total = total + grade; add 1 to counter = counter + 1; Fig. 3. 1 Sequence structure flowchart with pseudo code. 9
Decision Control flow There will be a condition and based on the condition parameter then the control will be flow in only one direction. 10
11
12
13
14
if Selection Structure true Grade >= 60 print “Passed” false Fig. 3. 3 if single-selection structure flowchart. 15
16
17
18
19
20
Control Structures 21
>>> 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 22
>>> if x and y: # Falsy . . . >>> if 'aul' in 'grault': . . . yes >>> if 'quux' in ['foo', 'bar', 'baz']: # Falsy . . . print('yes') # Truthy print('yes') 23
If else: 24
if/else Structure false true Grade >= 60 print “Failed” Fig. 3. 4 print “Passed” if/else double-selection structure flowchart. 25
26
27
28
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 and also checks the zero inside the positive value(Get the input from the user)-Nested If 29
num =3 # Try these two variations as well. # num = -5 # num = 0 if num >= 0: print("Positive or Zero") else: print("Negative number") 30
Contd. , 31
Class Activity 4 Write a python program to prompt a user to enter two numbers. Find the greater number. 32
Solution 33
Class Activity 5 Write a program to calculate the salary of a food delivery representative considering the sales bonus and incentives offered to him are based on the total sales. If the sales exceed (or) equal to Rs. 1, 000 follow the particulars of column 1, else follow column 2. 34
35
36
if/else Selection Structure if statement condition a true case a action(s) false first elif statement true condition b case b action(s) false. . . last elif statement true condition z case z action(s) false else statement Fig. 3. 5 default action(s) if/else multiple-selection structure. 37
syntax 38
Example Python code 39
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 40
Class Activity 6 Write a program to prompt a user to read the marks of five different subjects. Calculate the total marks and percentage of the marks and display the message according to the range of percentage given in table 41
42
43
44
Control Structures 45
46
3. 7 while Repetition Structure true Product <= 1000 Product = 2 * product false Fig. 3. 8 while repetition structure flowchart. 47
When we login to our homepage on Facebook, we have about 10 stories loaded on our newsfeed As soon as we reach the end of the page, Facebook loads another 10 stories onto our newsfeed This demonstrates how ‘while’ loop can be used to achieve this 48
49
50
51
Listing ‘Friends’ from your profile will display the names and photos of all of your friends To achieve this, Facebook gets your ‘friendlist’ list containing all the profiles of your friends Facebook then starts displaying the HTML of all the profiles till the list index reaches ‘NULL’ The action of populating all the profiles onto your page is controlled by ‘for’ statement 52
3. 13 for Repetition Structure The for loop ◦ Function range is used to create a list of values range ( integer ) Values go from 0 up to given integer (i. e. , not including) range ( integer, integer ) Values go from first up to second integer but increases in intervals of the third integer ◦ This loop will execute howmany times: for counter in range ( howmany ): and counter will have values 0, 1, . . howmany-1 53
for counter in range(10): print (counter) Output? 54
55
56
57
58
59
# Prints out 0, 1, 2, 3, 4 count = 0 while True: print(count) count += 1 if count >= 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) 60
61
Example for Pass 62
Expression values? Python 2. 2 b 2 (#26, Nov 16 Type "help", "copyright", >>> if 0: . . . print "0 is true". . . else: . . . print "0 is false". . . 0 is false >>> if 1: . . . print "non-zero is. . . non-zero is true >>> if -1: . . . print "non-zero is. . . non-zero is true >>> print 2 < 3 1 2001, 11: 44: 11) [MSC 32 bit (Intel)] on win 32 "credits" or "license" for more information. true" Expressions have integer values. No true, false like in Java. 0 is false, non-0 is true. 63
3. 16 Logical 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 64
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” 65
Example 66
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 *, **, /, % 67
Keywords Can’t use as identifiers 68
keyword pass : do nothing Python 2. 2 b 2 (#26, Nov 16 2001, 11: 44: 11) [MSC 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> if 1 < 2: . . . pass . . . Sometimes useful, e. g. during development: if a <= 5 and c <= 5: print “Oh no, both below 5! Fix problem” if a > 5 and c <= 5: pass # figure out what to do later if a <= 5 and c > 5: pass # figure out what to do later if a > 5 and c > 5: pass # figure out what to do later 69
1 # Fig. 3. 10: fig 03_10. py 2 # Class average program with counter-controlled repetition. 3 4 # initialization phase 5 total = 0 6 grade. Counter = 1 # number of grades entered 7 # sum of grades The total and counter, set to zero and one respectively A loop the continues as long as the counter does not go past 10 Program Output 8 # processing phase 9 while grade. Counter <= 10: # loop 10 times 10 grade = raw_input( "Enter grade: " ) # get one grade 11 grade = int( grade ) # convert string to an integer 12 total = total + grade 13 grade. Counter = grade. Counter + 1 14 15 # termination phase 16 average = total / 10 17 print "Class average is", average # integer division Adds one to the counter to eventually break the loop Divides the total by the 10 to get the class average Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 70
Another example Program Output 1 # Fig. 3. 22: fig 03_22. py 2 # Summation with for. 3 4 sum = 0 5 6 7 for number in range( 2, 101, 2 ): Loops from 2 to 101 in increments of 2 sum += number 8 9 print "Sum is", sum Sum is 2550 A sum of all the even numbers from 2 to 100 71
1 # Fig. 3. 23: fig 03_23. py 2 # Calculating compound interest. 3 4 principal = 1000. 0 # starting principal 5 rate =. 05 # interest rate 6 7 print "Year %21 s" % "Amount on deposit" 8 9 for year in range( 1, 11 ): Program Output 10 amount = principal * ( 1. 0 + rate ) ** year 11 print "%4 d%21. 2 f" % ( year, amount ) Year 1 2 3 4 5 6 7 8 9 10 Starts the loop at 1 and goes to 10 1. 0 + rate is the same no matter what, therefore it should have been calculated outside of the loop Amount on deposit 1050. 00 1102. 50 1157. 63 1215. 51 1276. 28 1340. 10 1407. 10 1477. 46 1551. 33 1628. 89 72
1 # Fig. 3. 24: fig 03_24. py 2 # Using the break statement in a for structure. 3 4 for x in range( 1, 11 ): 5 6 if x == 5: 7 break 8 9 10 print x, The loop will go from 1 to 10 When x equals 5 the loop breaks. Only up to 4 will be displayed Program Output Shows that the counter does not get 11 print "n. Broke out of loop at x =", x to 10 like it normally would have 1 2 3 4 Broke out of loop at x = 5 73
continue skips rest of body but continues loop Program Output 1 # Fig. 3. 26: fig 03_26. py 2 # Using the continue statement in a for/in structure. 3 4 for x in range( 1, 11 ): 5 6 7 if x == 5: continue 8 9 10 The loop will continue if the value equals 5 print x, The value 5 will never be output but all the others will 11 print "n. Used continue to skip printing the value 5" 1 2 3 4 6 7 8 9 10 Used continue to skip printing the value 5 74
Advantage of Python 75
76
- Slides: 76