PYTHON PROGRAMMING UNIT – II CONTROL STATEMENTS & DECISION CONTROL STATEMENTS -Rajesh Kone.

Similar presentations


Presentation on theme: "PYTHON PROGRAMMING UNIT – II CONTROL STATEMENTS & DECISION CONTROL STATEMENTS -Rajesh Kone."— Presentation transcript:

1 PYTHON PROGRAMMING UNIT – II CONTROL STATEMENTS & DECISION CONTROL STATEMENTS -Rajesh Kone

2 Decision-making Decision-making is the anticipation of conditions occurring during the execution of a program and specified actions taken according to the conditions. Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the outcome. You need to determine which action to take and which statements to execute if the outcome is TRUE or FALSE otherwise. Python programming language assumes any non- zero and non-null values as TRUE, and any zero or null values as FALSE value. Python Programming by Rajesh Kone 2

3 Python programming language provides the following types of decision-making statements. Python Programming by Rajesh Kone3

4 IF Statement The if statement contains a logical expression using which the data is compared and a decision is made based on the result of the comparison. If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. In Python, statements in a block are uniformly indented after the : symbol Python Programming by Rajesh Kone 4

5 5

6 IF...ELIF...ELSE Statements An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at the most only one else statement following if. Python Programming by Rajesh Kone 6

7 Net payable: 1080.0 Python Programming by Rajesh Kone 7

8 The elif Statement The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the most one statement, there can be an arbitrary number of elif statements following an if. Python Programming by Rajesh Kone8

9 9

10 10

11 Nested If Statements There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct. In a nested if construct, you can have an if...elif...else construct inside another if...elif...else construct. Python Programming by Rajesh Kone 11

12 Python Programming by Rajesh Kone12

13 Example: Write a Python program check whether given number is divisible by 2 and 3 (or) not Outputs : Python Programming by Rajesh Kone 13

14 Loops In general, statements are executed sequentially- The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. A loop statement allows us to execute a statement or group of statements multiple times. Python Programming by Rajesh Kone14

15 while Loop A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. Syntax while : statement(s) statement(s) may be a single statement or a block of statements with uniform indent. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. Python Programming by Rajesh Kone15

16 Counter Controlled & Condition Controlled Loops Counter Controlled Loop: When we know in advance the No. of times the loop should be executed, we use Counter Controlled Loop The Counter Variable that must be initialized, tested and updated for performing the loop executions Example for Counter Controlled Loop: Python Programming by Rajesh Kone16

17 Condition Controlled Loop: When we do not know in advance the No. of times the loop should be executed, we use Condition Controlled Loop In such loop a special value is called sentinel value is used to change the loop control expression from True to False Example: Python Programming by Rajesh Kone17

18 Python Programming by Rajesh Kone 18

19 Python Programming by Rajesh Kone19

20 Python Programming by Rajesh Kone 20

21 The Infinite Loop A loop becomes infinite loop if a condition never becomes FALSE. This results in a loop that never ends. Such a loop is called an infinite loop Python Programming by Rajesh Kone21

22 For loop A for loop is used for iterating over a sequence (list, tuple, dictionary, set, string, range()). Python Programming by Rajesh Kone22

23 Python Programming by Rajesh Kone23

24 Nested Loops Python programming language allows the use of one loop inside another loop. Python Programming by Rajesh Kone24

25 else Statement with Loops If the else statement is used with a while loop, the else statement is executed when the condition becomes false. Example: Python Programming by Rajesh Kone25

26 If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. Python Programming by Rajesh Kone26

27 Python range() function range() is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times. range() in Python(3.x) is just a renamed version of a function called xrange() in Python(2.x).xrange The range() function is used to generate a sequence of numbers. Most common use of range() function in Python is to iterate sequence type (List, string etc.. ) with for and while loop. Python Programming by Rajesh Kone27

28 Syntax: range( [start], [stop],[step]) start: integer starting from which the sequence of integers is to be returned stop: integer before which the sequence of integers is to be returned. The range of integers end at stop – 1. step: integer value which determines the increment between each integer in the sequence  range(stop) takes one argument. Ex: range(10)  range(start, stop) takes two arguments.Ex: range(0,10)  range(start, stop, step) takes three arguments. Ex: range(0,10,2) Ex: for i in range(0, 50, 5): print(i, end = " ") Output: 0 5 10 15 20 25 30 35 40 45 Python Programming by Rajesh Kone 28

29 Break Statement : break statement we can stop the loop before it has looped through all the items If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop. Python Programming by Rajesh Kone 29

30 Break Statement : The Break statement provides us with opportunity to exit out of the loop when an external condition is triggered. Break will be there in if condition Continue statement: It gives us the option to skip over the part of loop where an external condition is triggered, but to go on to complete the rest of the loop. That is the current iteration of the loop will be disrupted, but the program will run to the top of the loop. Pass Statement: When an external condition is triggered the pass statement allows us to handle the condition without the loop being impacted in anyway. All other code will continue to be read unless a break or other statement occurs Python Programming by Rajesh Kone30

31 Continue statement: we can stop the current iteration of the loop, and continue with the next. The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. Python Programming by Rajesh Kone 31

32 The pass statement is a null operation; nothing happens when it executes. Python Programming by Rajesh Kone 32

33 Math Module Python Programming by Rajesh Kone33 FunctionDescription ceil(x) Returns the smallest integer greater than or equal to x. copysign(x, y) Returns x with the sign of y fabs(x) Returns the absolute value of x factorial(x) Returns the factorial of x floor(x) Returns the largest integer less than or equal to x fmod(x, y) Returns the remainder when x is divided by y frexp(x) Returns the mantissa and exponent of x as the pair (m, e) fsum(iterable) Returns an accurate floating point sum of values in the iterable isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a Number) isinf(x) Returns True if x is a positive or negative infinity

34 isnan(x) Returns True if x is a NaN ldexp(x, i) Returns x * (2**i) modf(x) Returns the fractional and integer parts of x trunc(x) Returns the truncated integer value of x exp(x) Returns e**x expm1(x) Returns e**x - 1 log(x[, b]) Returns the logarithm of x to the base b (defaults to e) log1p(x) Returns the natural logarithm of 1+x log2(x) Returns the base-2 logarithm of x log10(x) Returns the base-10 logarithm of x pow(x, y) Returns x raised to the power y sqrt(x) Returns the square root of x degrees(x) Converts angle x from radians to degrees radians(x) Converts angle x from degrees to radians Python Programming by Rajesh Kone34

35 acos(x)Returns the arc cosine of x asin(x)Returns the arc sine of x atan(x)Returns the arc tangent of x atan2(y, x)Returns atan(y / x) cos(x)Returns the cosine of x hypot(x, y)Returns the Euclidean norm, sqrt(x*x + y*y) sin(x)Returns the sine of x tan(x)Returns the tangent of x acosh(x)Returns the inverse hyperbolic cosine of x asinh(x)Returns the inverse hyperbolic sine of x atanh(x)Returns the inverse hyperbolic tangent of x cosh(x)Returns the hyperbolic cosine of x sinh(x)Returns the hyperbolic cosine of x tanh(x)Returns the hyperbolic tangent of x Python Programming by Rajesh Kone35

36 Python Programming by Rajesh Kone36 erf(x)Returns the error function at x erfc(x)Returns the complementary error function at x gamma(x)Returns the Gamma function at x lgamma(x) Returns the natural logarithm of the absolute value of the Gamma function at x pi Mathematical constant, the ratio of circumference of a circle to it's diameter (3.14159...) emathematical constant e (2.71828...) tauReturns tau (6.2831...)

37 Python Programming by Rajesh Kone37

38 Python Programming by Rajesh Kone 38

39 Python Programming by Rajesh Kone39

40 Python Programming by Rajesh Kone40

41 Python Programming by Rajesh Kone41

42 Python Programming by Rajesh Kone42

43 Python Programming by Rajesh Kone43

44 Random module FunctionDescription seed(a=None, version=2)Initialize the random number generator getrandbits(k) Returns a Python integer with k random bits randrange(start, stop, [step]) Returns a random integer from the range randint(a, b) Returns a random integer between a and b inclusive choice(seq) Return a random element from the non- empty sequence shuffle(seq)Shuffle the sequence random() Return the next random floating point number in the range [0.0, 1.0) uniform(a, b) Return a random floating point number between a and b inclusive Python Programming by Rajesh Kone44

45 Python Programming by Rajesh Kone45

46 Python Programming by Rajesh Kone46

47 Python Date and time Python provides the datetime module work with real dates and times. In real-world applications, we need to work with the date and time. The datetime classes are classified in the six main classes. date - It is a naive ideal date. It consists of the year, month, and day as attributes. time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour, minute, second, microsecond, and tzinfo as attributes. datetime - It is a grouping of date and time, along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo. timedelta - It represents the difference between two dates, time or datetime instances to microsecond resolution. tzinfo - It provides time zone information objects. timezone - It is included in the new version of Python. It is the class that implements the tzinfo abstract base class. Python Programming by Rajesh Kone47

48 Tick: In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of the module time returns the total number of ticks spent since 12 AM, 1st January 1970. A tick can be seen as the smallest unit to measure the time. Python Programming by Rajesh Kone48

49 How to get the current time The localtime() functions of the time module are used to get the current time tuple. Python Programming by Rajesh Kone49 time.struct_time(tm_year=2021, tm_mon=6, tm_mday=3, tm_hour=13, tm_min=16, tm_sec=43, tm_wday=3, tm_yday=154, tm_isdst=0 )

50 Getting formatted time: The time can be formatted by using the asctime() function of the time module. It returns the formatted time for the time tuple being passed. Output: Struct_time = time.struct_time(tm_year=2021, tm_mon=6, tm_mday=3, tm_hour=19, tm_min=50, tm_sec=12, tm_wday=3, tm_yday=154, tm_isdst=0) 'Thu Jun 3 19:50:12 2021' Python Programming by Rajesh Kone50

51 FunctionDescription time() Returns the number of seconds that have passed since epoch ctime() Returns the current date and time by taking elapsed seconds as its parameter sleep() Stops execution of a thread for the given duration time.struct_time Class Functions either take this class as an argument or return it as output localtime() Takes seconds passed since epoch as a parameter and returns the date and time in time.struct_time format gmtime() Similar to localtime(), returns time.struct_time in UTC format mktime() The inverse of localtime(). Takes a tuple containing 9 parameters and returns the seconds passed since epoch pas output asctime() Takes a tuple containing 9 parameters and returns a string representing the same strftime() Takes a tuple containing 9 parameters and returns a string representing the same depending on the format code used strptime() Parses a string and returns it in time.struct_time format Python Programming by Rajesh Kone51

52 AttributeValue tm_year0000,.., 2019, …, 9999 tm_mon1-12 tm_mday1-31 tm_hour0-23 tm_min0-59 tm_sec0-61 tm_wday0-6 (Monday is 0) tm_yday1-366 tm_isdst0, 1, -1 (daylight savings time, -1 when unknown) Python Programming by Rajesh Kone52

53 Format Codes: CodeDescriptionExample %aWeekday (short version)Mon %AWeekday (full version)Monday %bMonth (short version)Aug %BMonth (full version)August %cLocal date and time versionTue Aug 23 1:31:40 2019 %dDepicts the day of the month (01-31)07 %fMicroseconds000000-999999 %HHour (00-23)15 %IHour (00-11)3 %jDay of the year235 %mMonth Number (01-12)07 %MMinutes (00-59)45 Python Programming by Rajesh Kone53

54 Python Programming by Rajesh Kone54 CodeDescriptionExample %p AM / PMAM %S Seconds (00-59)57 %U Week number of the year starting from Sunday (00-53)34 %w Weekday number of the weekMonday (1) %W Week number of the year starting from Monday (00-53)34 %x Local date06/07/19 %X Local time12:30:45 %y Year (short version)19 %Y Year (full version)2019 %z UTC offset+0100 %Z TimezoneCST % % Character%

55 Datetime Module The datetime module enables us to create the custom date objects, perform various operations on dates like the comparison, etc. To work with dates as date objects, we have to import the datetime module into the python source code. Built-in functions: Python Programming by Rajesh Kone55 FunctionDescription datetime()Datetime constructor datetime.today()Returns current local date and time datetime.now()Returns current local date and time date() Takes year, month and day as parameter and creates the corresponding date time() Takes hour, min, sec, microseconds and tzinfo as parameter and creates the corresponding date date.fromtimestamp()Converts seconds to return the corresponding date and time timedelta()It is the difference between different dates or times (Duration)


Download ppt "PYTHON PROGRAMMING UNIT – II CONTROL STATEMENTS & DECISION CONTROL STATEMENTS -Rajesh Kone."

Similar presentations


Ads by Google