
Python Control Flow Concepts
Learn about Python control flow structures including if statements, while loops, for loops, pass statements, functions, return statements, default argument values, and evaluation of default values. Explore examples and understand how to use each of these concepts effectively in Python programming.
Download Presentation

Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.
E N D
Presentation Transcript
If Statements if elif else if (num > 100): elif num < 50: else: elif can appear multiple times Both elif and else are optional 2
While Statement while else while num <= 100: num += 1 else: print wrong number else is optional Only executed when condition becomes false Statement break terminates while loop (else part will not be executed) Statement continue goes to next iteration 3
For Statement Differs from many languages for .. in list1 = [ a , b , c ] for elem in list1: print elem Range() function is handy in many situations range(10) range(5, 10) # list 0 to 9 # list 5 to 9 for i in range(10, 20): print i Break and continue also apply to for statement 4
Pass Statement It does nothing, more like a placeholder if True: pass 5
Python Functions Defined using keyword def Followed by the function name, a pair of parentheses, and optional parameters, and the function body def fibonacci(num): if (num == 0 or num == 1): else: return 1 return fibonacci(num-1) + fibonacci(num-2) See examples/python/p3/Fibonacci_recursive.py 6
Return Statement Can return any data type, such list Return without parameter will return None Similarly, a function without a return statement will also return None when end of function is reached 7
Default Argument Values We can provide default values for an argument def input_a_number(min=0, max=100): See p3/example3.py 8
Default Values Evaluation Default argument values are evaluated at the time of function definition This is very important to be aware of I = 5 Def f(arg=5): I = 6 F() print(arg) See py3/example4.py and example5.py, example5a.py Think in this way, lst is just a name to a list object in the function object 9
Keyword Arguments We can also use keyword arguments when calling a function in form of kwarg = value, for example input_a_number(10, max=50) Keyword arguments follow positional arguments See examples/python/p3/example6.py 10
Variable Number of Parameters Variable number of formal parameters in form of *names Where names will receive all variable number of arguments, beyond positional parameters Which is a tuple Variable number of keyword parameters in form of **names Where names will receive all keyword arguments beyond formal parameters Which is a dictionary **names follows *name if both appear 11
Variable Number of Parameters See the following from the Python Tutorial def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) forarginarguments: print(arg) print("-" * 40) forkwinkeywords: print(kw, ":", keywords[kw]) See examples/python/p3/example7.py 12
Lambda Functions Also called anonymous functions in some languages Using keyword lambda, followed by the formal parameters, and then one single expression (which will be returned) lambda x: x + 10 Passing x, and then return x + 10 We will see more later 13
Sorting in Python Two versions list.sort(*, key=None, reverse=False) works only for list sorted(iterable, *, key=None, reverse=False) works for any iterable In default, sorting in ascending order alist = [10, 30, 20, 40] alist.sort() Alist.sort(reverse=True) adict = {i: test + str(i) for I in range(5)} sorted(adict) See examples/python/p3/example8.py 14
Sorting in Python Using the key parameter to control what is compared in sorting Value of key parameter should be function with one parameter and return the key for comparison Note that this is different from many other languages, where we specify how to compare two elements, as in Python 2 alist = [(1, 10), (2, 30), (3, 20), (4, 40)] sorted(alist, key = lambda e : e[1]) See examples/python/p3/example9.py 15
Sorting by Multiple Criteria How you carry this out depending on the specifics of the problem If all in the same order (ascending or descending), you can just use the element value, or form a new set using the element value Otherwise, you need to either look for creative ways to generate keys to be compared, or sort in multiple rounds, for one each criterion, from last one to the first one Why you can sort in multiple rounds to get the final result? Stable sort See examples/python/p3/example10.py 16