Python Notes.pdf
Document Details
Uploaded by GentlePlanet2057
NIMS University
Related
- PCSII Depression/Anxiety/Strong Emotions 2024 Document
- A Concise History of the World: A New World of Connections (1500-1800)
- Human Bio Test PDF
- University of Santo Tomas Pre-Laboratory Discussion of LA No. 1 PDF
- Vertebrate Pest Management PDF
- Lg 5 International Environmental Laws, Treaties, Protocols, and Conventions
Full Transcript
STUDENT ADVISORY Dear Students, Please be informed that the notes provided by the institute offer a concise presentation of the syllabus. While these notes are helpful for an overview and quick revision, We would strongly suggest that you refer to the prescribed textbooks / Reference book for a com...
STUDENT ADVISORY Dear Students, Please be informed that the notes provided by the institute offer a concise presentation of the syllabus. While these notes are helpful for an overview and quick revision, We would strongly suggest that you refer to the prescribed textbooks / Reference book for a comprehensive understanding and thorough preparation of all exams and writing in the examination. Best regards, LJ Polytechnic. પ્રિય પ્રિદ્યાર્થીઓ, તમને જાણ કરિામા આિે છે કે સંસ્ર્થા દ્વારા િદાન કરિામાં આિેલી નોંધો અભ્યાસક્રમની સંક્ષિપ્ત િસ્તુપ્રત આપે છે. આ નોંધો પ્રિહંગાિલોકન અને ઝડપી પુનરાિતતન માટે મદદરૂપ હોઈ શકે છે તેમ છતા, અમે ભારપ ૂિતક સ ૂચન કરીએ છીએ કે પ્રિદ્યાર્થી તમામ પરીિાઓ અને પરીિામાં લેખનની વ્યાપક સમજણ અને સંપ ૂણત તૈયારી માટે માત્ર સ ૂચિેલા પાઠ્યપુસ્તકો/સંદભત પુસ્તકનો સંદભત લો. એલજે પોક્ષલટેકપ્રનક. Python Programming Unit-1 Notes CHAPTER 1- Python Introduction What is Python? Python is an open source, dynamic, high-level and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures. It is a general-purpose language; it means that it can be used to create a variety of different programs and isn’t specialized for any specific problems. History of Python Python laid its foundation in 1980s. The implementation of Python was started in December 1989 by Guido Van Rossum at CWI (Centrum Wiskunde & Informatica) in Netherland. In February 1991, Guido Van Rossum published the labeled version 0.9.0 to alt.sources. In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce. In 2000, Python 2.0 was released with new features such as list comprehensions, garbage collection, cycle detecting and Unicode support. On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the fundamental flaw of the language. ABC programming language is said to be the predecessor of Python language, which was capable of Exception Handling. Python Features and Advantages: Easy to Code and Easy to Read Python is easy to learn as compared to other programming languages. Its syntax is straight forward and much the same as the English language. There is no use of the semicolon or curly-bracket. Free and Open-Source Python is developed under an OSI-approved open-source license. Hence, it is completely free to use, even for commercial purposes. It doesn't cost anything to download Python or to include it in your application. Robust Standard Library Python has an extensive standard library available for anyone to use. This means that programmers don’t have to write their code for every single thing unlike other programming languages. There are libraries for image manipulation, databases, unit-testing, expressions and a lot of other functionalities. Interpreted When a programming language is interpreted, it means that the source code is executed line by line, and not all at once. Programming languages such as C++ or Java are not 1 Python Programming Unit-1 Notes interpreted, and hence need to be compiled first to run them. There is no need to compile Python because it is processed at runtime by the interpreter. Portable Python is portable in the sense that the same code can be used on different machines. Suppose you write a Python code on a Mac. If you want to run it on Windows or Linux later, you don’t have to make any changes to it. Object-Oriented and Procedure-Oriented A programming language is object-oriented if it focuses design around data and objects, rather than functions and logic. On the contrary, a programming language is procedure- oriented if it focuses more on functions (code that can be reused). One of the critical Python features is that it supports both object-oriented and procedure-oriented programming. Extensible A programming language is said to be extensible if it can be extended to other languages. Python code can also be written in other languages like C++, making it a highly extensible language. Expressive Language Python can perform complex tasks using a few lines of code. A simple example, the hello world program you simply type print ("Hello World"). It will take only one line to execute, while Java or C takes multiple lines. Support for GUI One of the key aspects of any programming language is support for GUI or Graphical User Interface. A user can easily interact with the software using a GUI. Python offers various toolkits, such as Tkinter, wxPython and JPython, which allows for GUI's easy and fast development. Dynamically Typed Many programming languages need to declare the type of the variable before runtime. With Python, the type of the variable can be decided during runtime. This makes Python a dynamically typed language. High-level Language Python is a high-level programming language because programmers don’t need to remember the system architecture, nor do they have to manage the memory. This makes it super programmer-friendly and is one of the key features of Python. What is use of Python? Python is commonly used for developing websites and software task automation data analysis data visualization etc. 2 Python Programming Unit-1 Notes What can we do with Python? 1) Data analysis and machine learning Python has become a staple in data science, allowing data analysts and other professionals to use the language to conduct complex statistical calculations, create data visualizations, build machine learning algorithms, manipulate and analyze data, and complete other data-related tasks. Python can build a wide range of different data visualizations, like line and bar graphs, pie charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and Keras. 2) Web development Python is often used to develop the back end of a website or application—the parts that a user doesn’t see. Python’s role in web development can include sending data to and from servers, processing data and communicating with databases, URL routing, and ensuring security. Python offers several frameworks for web development. Commonly used ones include Django and Flask. 3) Automation or scripting If you find yourself performing a task over and over again, you could work more efficiently by automating it with Python. Writing code used to build these automated processes is called scripting. In the coding world, automation can be used to check for errors across multiple files, convert files, execute simple math, and remove duplicates in data. 4) Software testing and prototyping In software development, Python can aid in tasks like build control, bug tracking, and testing. With Python, software developers can automate testing for new products or features. Some Python tools used for software testing include Green and Requestium. 5) Everyday tasks Python isn't only for programmers and data scientists. Learning Python can open new possibilities for those in less data-heavy professions, like journalists, small business owners, or social media marketers. Python can also enable non-programmer to simplify certain tasks in their lives. Here are just a few of the tasks you could automate with Python: Keep track of stock market or crypto prices Send yourself a text reminder to carry an umbrella anytime it’s raining Update your grocery shopping list Renaming large batches of files Converting text files to spreadsheets Randomly assign chores to family members Fill out online forms automatically 3 Python Programming Unit-1 Notes Python Interpreter, Extension & Implementations Computers cannot understand code in the way humans write it and hence, you need an interpreter between the computer and the human written code. The job of the interpreter is to convert the code into a format that computers can then understand and process. The interpreter processes the code in the following ways: Processes the Python script in a sequence. Compiles the code into a byte code format which is a lower-level language understood by the computers. The Python Virtual Machine (PVM) perform over the instructions of low-level byte code to run them one by one. The Python script is saved with a.py extension which informs the computer that it is a Python program script. Python Installation Unlike Windows, the Unix based operating systems such as Linux and Mac come with pre- installed Python. Also, the way Python scripts are run in Windows and Unix operating systems differ. Installing Python on Windows takes a series of few easy steps: Step 1 − Select Version of Python to Install Python has various versions available with differences between the syntax and working of different versions of the language. We need to choose the version which we want to use or need. Step 2 − Download Python Executable Installer On the web browser, in the official site of python www.python.org, move to the Download for Windows section. All the available versions of Python will be listed. Select the version required by you and click on Download. Step 3 − Run Executable Installer Run the installer. The installation process will take few minutes to complete. Step 4 − Verify Python is installed on Windows To ensure if python is successfully installed on your system. Follow the given steps − Open the command prompt. Type ‘python’ and press enter. The version of the python which you have installed will be displayed if the python is successfully installed on your windows. Step 5 − Verify Pip was installed Pip is a powerful package management system for Python software packages. Thus, make sure that you have it installed. 4 Python Programming Unit-1 Notes To verify if pip was installed, follow the given steps − Open the command prompt. Enter pip –V to check if pip was installed. The following output appears if pip is installed successfully. Note: For all users, especially Windows OS users, it is highly recommended that you install Anaconda, which can be downloaded from https://www.anaconda.com/ Python Program Execution List out Different ways to run Python Script Here are the ways with which we can run a Python script. 1. Interactive Mode – We have to write code in command prompt line by line. To enter in an interactive mode, you will have to open Command Prompt on your windows machine and type ‘python’ and press Enter. Run the following line one by one in the interactive mode: a=1 b=3 if a > b: print ("a is Greater") else: print ("b is Greater") 5 Python Programming Unit-1 Notes On a Mac system, it is very straight-forward. All you need to do is open Launchpad and search for Terminal, and in the terminal, type Python and boom, it will give you an output with the Python version. Like the Mac system, accessing terminal on a Linux system is also very easy. Right click on the desktop and click Terminal and in terminal type Python and that's all! 2. Command Line – We have to make python file first and save by.py extension. This file you can run in command prompt by write python first and then your filename. Create a file having extension.py Write Python script in created file To run a Python script store in a ‘.py’ file in command line, write ‘python’ keyword before the file name in the command prompt. python hello.py Note: You can write your own file name in place of ‘hello.py’. # File Name: - hello.py # File Path: - C:\Users\Anonymous\Desktop\GfG\hello.py print ("Hello World!") 6 Python Programming Unit-1 Notes 3. Text Editor (Example: Notepad++, VS Code, etc.) 4. IDE (Examples: IDLE, Spyder, Atom, PyCharm, etc.) Values and Types: A value is one of the basic things a program works with, like a letter or a number. A value may be characters i.e. ‘Hello, World!’ or a number like 1, 2.2, 0.9 etc. To print the value print() function is used. Example: >>> print ('Hello, World!') Hello, World! >>> print (1) 1 >>> print (2.2) 2.2 >>> print ('Abc@123') Abc@123 To find the type of given value type() function is used. In python we don’t have to write int, float, char it will automatically understand the type of given value. So, if we want to find particular type of given value, we can use the type function. Example: >>> type ('Hello, World!') >>> type (1) >>> type (2.2) >>> print (''Abc@123'') 7 Python Programming Unit-1 Notes Variables Variables are containers for storing data values. Creating Variables 1. Python has no command for declaring a variable. We just have to write variable name and assign the value in it. 2. A variable is created the moment you first assign a value to it. Example: Output: x=5 y = “LJ Polytechnic” 5 print(x) LJ Polytechnic print(y) 3. Variables do not need to be declared with any particular type, and can even change type after they have been set. If we use the same name, the variable starts referring to a new value and type. Example: Output: x=5 x = “LJ Polytechnic” LJ Polytechnic print(x) 4. Python allows assigning a single value to several variables simultaneously with “=” operators. Example: Output: x = y = z = 100 100 print(y) 5. Assigning different values to multiple variables: Python allows adding different values in a single line with “,” operators. Example: Output: a, b, c = 1, 2.2, 'ABC' 1 print(a) 2.2 print(b) ABC print(c) 6. How does + operator work with variables? Example: Output: a = 10 b = 20 print (a + b) 30 x = 'LJ' LJKU y = 'KU' 8 print (x + y) Python Programming Unit-1 Notes 7. Can + Operator work with different type variable? Example: Output: a = 10 TypeError: unsupported b = 'LJ' operand type(s) for +: 'int' print (a + b) and 'str' Rules for creating variables in Python: 1. A variable name must start with a letter or the underscore character. 2. A variable name cannot start with a number. 3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _). 4. Variable names are case-sensitive (name, Name and NAME are three different variables). 5. The reserved words (keywords) cannot be used to naming the variable. Keywords: The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names. Python reserves 35 keywords: and del from none true continue lambda as elif global nonlocal try def is assert else if not while finally return break except in or with for async class false import pass yield raise wait String: Strings are arrays of bytes representing Unicode characters. String data type is most important data type in python. Python does not have a character datatype, a single character is simply a string with a length of 1. String is not a small. It can also big as million characters. Python has also built in functions and algorithms for string. String is the combination of multiple characters. String index is starting from 0. 9 Python Programming Unit-1 Notes Example: Output: s = 'P' print(s) type(s) P language = 'Python' Python print(language) type(language) String Indexing: P Y T H O N [-6] [-5] [-4] [-3] [-2] [-1] Square brackets can be used to access elements of the string. Example: Output: language = 'Python' letter = language y print(letter) P n print(language) TypeError: string print(language[-1]) indices must be integers print(language[1.5]) Length of a String: To find the length of the string len() function is used. len() is a built-in function that returns the number of characters in a string: Example: language = 'Python' Output: print(len(language)) 6 To get the last letter of a string, you might be tempted to try something like this: Because if you write simply length, then length will start from 0 so it can’t display last digit. Example: Output: x = "Python" length = len(x) y=x[length-1] n print(y) 10 Python Programming Unit-1 Notes String Slices: A segment of a string is called a slice. Selecting a slice is similar to selecting a character: We can specify start, stop and step (optional) within the square brackets as: string[start: stop: step] start: It is the index from where the slice starts. The default value is 0. stop: It is the index at which the slice stops. The character at this index is not included in the slice. The default value is the length of the string. step: It specifies the number of jumps to take while going from start to stop. It takes the default value of 1. Example: s = 'Welcome to LJKU' print(s[0:8]) print(s[11:16]) # By default starting index is "0" and middle index in "length of string" print(s[:]) print(s[0:]) # If we can write same digit at both place then it will not give us any output print(s[3:3]) # Replace any latter with any index of given string. r = 'J' + s[1:] print(r) # If we write -1 at step place it will give output as reverse of string print(s[ : :-1]) # For step jumping print(s[0: :2]) # it will give output as skip 1 character from starting of string print(s[ : :-2]) # it will first reverse the string and skip 1 character after reverse. Output: Welcome LJKU Welcome to LJKU Welcome to LJKU Jelcome to LJKU UKJL ot emocleW Wloet JU 11 UJ teolW Python Programming Unit-1 Notes String Methods: Everything in Python is an object. A string is an object too. Python provides us with various methods to call on the string object. Note: Note that none of these methods alters the actual string. They instead return a copy of the string. This copy is the manipulated version of the string. capitalize() This method is used to capitalize a string. >>> s = 'heLlo pYthOn' >>> s2 = s.capitalize() >>> print(s2) Hello python lower() This method converts all alphabetic characters to lowercase. >>> s = 'heLlo pYthOn' >>> s2 = s.lower() >>> print(s2) hello python upper() This method converts all alphabetic characters to uppercase. >>> s = 'heLlo pYthOn' >>> s2 = s.upper() >>> print(s2) HELLO PYTHON title() This method converts the first letter of each word to uppercase and remaining letters to lowercase. >>> s = 'heLlo pYthOn' >>> s2 = s.title() >>> print(s2) Hello Python 12 Python Programming Unit-1 Notes swapcase([]) This method swaps case of all alphabetic characters. >>> s = 'HeLlo PyThOn' >>> s2 = s.swapcase () >>> print(s2) hElLO pYtHoN count(, , ) This method returns the number of time occurs in string. >>> s = 'Python Programming' >>> s.count('P') 2 >>> s.count('mm') 1 >>> s.count('P',3,10) 1 find(, , ) This method returns the index of the first occurrence of in s. Returns -1 if the substring is not present in the string. >>> s = 'Python Programming' >>> s.find('Pro') 7 >>> s.find('on',3,10) 4 lstrip() This method removes leading characters from a string. Removes leading whitespaces if you don’t provide a argument. >>> s = ' Python ' >>> s.lstrip() 'Python ' rstrip() This method removes trailing characters from a string. Removes trailing whitespaces if you don’t provide a argument. >>> s = ' Python ' 13 >>> s.rstrip() ' Python' Python Programming Unit-1 Notes strip() This method removes leading and trailing characters from a string. Removes leading and trailing whitespaces if you don’t provide a argument >>> s = ' Python ' >>> s.strip() 'Python' join() This method returns the string concatenated with the elements of iterable. >>> s = ('We', 'are', 'coders') >>> s1 = '_'.join(s) print(s1) We are coders split(sep=None, maxsplit=-1) This method splits a string into a list of substrings based on sep. If you don’t pass a value to sep, it splits based on whitespaces. >>> s = 'Python Programming' >>> s.split() ['Python', 'Programming'] >>> s = 'Python Programming' >>> s.split('o') ['Pyth', 'n Pr', 'gramming'] String Concatenation Strings can be concatenated (glued together) with the + operator, and repeated with *: >>>3*'un' 'ununun' >>>'Py''thon' 'Python' >>>'Py'+'thon' 'Python' 14 Python Programming Unit-1 Notes Escape Characters To insert characters that are illegal in a string, use an escape character. An escape character is a backslash (\) followed by the character you want to insert. >>>s = ''we are the so-called ''Vikings'' from the north'' SyntaxError: invalid syntax To fix this problem, use the escape character \" >>>s = ''we are the so-called \''Vikings\'' from the north'' 'we are the so-called ''Vikings'' from the north' List of escape sequences available in Python 3: Code Result Code Result \' Single Quote \t Tab \\ Backslash \b Backspace \n New Line \f Form Feed \r Carriage Return \ooo Octal value \xhh Hex value Numbers There are three numeric types in Python: int float complex Variables of numeric types are created when you assign a value to them: >>>x = 1 #int >>> y = 2.8 #float >>> z = 1j #complex >>>print(type(x)) >>>print(type(y)) >>>print(type(z)) 15 Python Programming Unit-1 Notes Int Integer is a whole number, positive or negative, without decimals, of unlimited length. >>>x = 1 >>>y = 35656222554887711 >>>z = -3255522 >>>print(type(x)) >>>print(type(y)) >>>print(type(z)) Float Float or "floating point number" is a number, positive or negative, containing one or more decimals. Float can also be scientific numbers with an "e" to indicate the power of 10. >>>x = 1.10 >>>x = 35e3 >>>y = 1.0 >>>y = 12E4 >>>z = -35.59 >>>z = -87.7e100 >>>print(type(x)) >>>print(type(x)) >>>print(type(y)) >>>print(type(y)) >>>print(type(z)) >>>print(type(z)) Complex Complex numbers are written with a "j" as the imaginary part: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) 16 Python Programming Unit-1 Notes Type Conversion You can convert from one type to another with the int(), float(), and complex() methods. Example: Output: x = 1 # int y = 2.8 # float z = 1j # complex a = float(x) # convert from int to float 1.0 b = int(y) #convert from float to int c = complex(x) #convert from int to complex 2 print(a) print(type(a)) (1+0j) print(b) print(type(b)) print(c) print(type(c)) Operators Operators in general are used to perform operations on values and variables. These are standard symbols used for the purpose of logical and arithmetic operations. Arithmetic Operators Arithmetic operators are used to performing mathematical operations like addition, subtraction, multiplication, and division. Operator Description Syntax + Addition: adds two operands x+y - Subtraction: subtracts two operands x–y * Multiplication: multiplies two operands x*y / Division (float): divides the first operand by the second x/y // Division (floor): divides the first operand by the second x // y % Modulus: returns the remainder when the first operand is x % y divided by the second ** Power: Returns first raised to power second x ** y 17 Python Programming Unit-1 Notes Example: Output: a = 21 b = 10 c=0 c=a+b print("Addition is:", c) c=a-b print('Subtraction is:', c) c=a*b Addition is: 31 print('Multiplication is:', c) Subtraction is: 11 c=a/b Multiplication is: 210 print('Division is:', c) Division is: 2.1 c=a%b Reminder of a/c is: 1 print("Reminder of a/c is:", c) result of p^q is: 8 p=2 result of a divide b is: 2 q=3 r =p**q print("result of p^q is:", r) x = 11 y=5 z = a//b print("result of a divide b is:", z) Comparison Operators Comparison of Relational operators compares the values. It either returns True or False according to the condition. Operator Description Syntax > Greater than: True if the left operand is greater than the x > y right < Less than: True if the left operand is less than the right x= Greater than or equal to True if the left operand is greater x >= y than or equal to the right > # Examples of Relational Operators >>> a, b = 13, 33 >>> # a > b is False >>> print(a > b) False >>> # a < b is True >>> print(a < b) True >>> # a == b is False >>> print(a == b) False >>> # a != b is True >>> print(a != b) True Logical Operators Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements. Operator Description Syntax and Logical AND: True if both the operands are true x and y or Logical OR: True if either of the operands is true x or y not Logical NOT: True if the operand is false Not x Example: Output: x=5 print(x>3 and x>10) #and False print (x>3 or x>10) #or True print(not(x > 3 and x > 10)) True # returns False because not is used to reverse the result 19 Python Programming Unit-1 Notes Bitwise Operators Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary numbers. Operator Description Syntax & Operator copies a bit to the result if it exists in both x & y Bitwise operands (means 0000 AND 1100) | It copies a bit if it exists in either operand. x | y = 61 Bitwise OR (means 0011 1101) ~ It copies the bit if it is set in one operand but not both. ~x Bitwise NOT ^ It is unary and has the effect of 'flipping' bits. x^y Bitwise XOR >> The left operands value is moved left by the number of bits x>> Bitwise right specified by the right operand. shift ># Examples of Bitwise operators a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c=0 c=a&b # 12 = 0000 1100 print('Answer of a & b is:', c) Answer of a & b is: 12 c=a|b # 61 = 0011 1101 Answer of a | b is: 61 print('Answer of a | b is:', c) Answer of a ^ b is: 49 Answer of ~60 is: -61 c=a^b # 49 = 0011 0001 Answer of a2 is: 15 c = ~a # -61 = 1100 0011 print('Answer of ~60 is:', c) c = a > 2 # 15 = 0000 1111 print('Answer of a>>2 is:-',c) Python Programming Unit-1 Notes Assignment Operators Assignment operators are used to assigning values to the variables. Operator Description Syntax = Assign value of right side of expression to left side operand x=y+z += Add AND: Add right-side operand with left side operand and then assign to a +=b left operand a=a+b -= Subtract AND: Subtract right operand from left operand and then assign to a -=b left operand a=a - b *= Multiply AND: Multiply right operand with left operand and then assign to a *=b left operand a=a * b /= Divide AND: Divide left operand with right operand and then assign to left a /=b operand a=a / b %= Modulus AND: Takes modulus using left and right operands and assign the a %=b result to left operand a=a % b //= Divide(floor) AND: Divide left operand with right operand and then assign a /=b the value(floor) to left operand a=a // b **= Exponent AND: Calculate exponent(raise power) value using operands and a **=b assign value to left operand a=a ** b &= Performs Bitwise AND on operands and assign value to left operand a &=b a=a&b |= Performs Bitwise OR on operands and assign value to left operand a |=b a=a | b ^= Performs Bitwise XOR on operands and assign value to left operand a ^=b a=a ^ b >>= Performs Bitwise right shift on operands and assign value to left operand a >>=b a=a>>b b = 20 >>> c = a >>> print (a is not b) True >>> print (a is c) True Membership Operators in and not in are the membership operators; used to test whether a value or variable is in a sequence. Operator Description in True if value is found in the sequence in not True if value is not found in the sequence Example: Output: #membership_ex.py x = 24 y = 20 list = [10, 20, 30, 40, 50] if (x not in list): x is NOT present in given print("x is NOT present in given list") list else: y is present in given list print("x is present in given list") if (y in list): print("y is present in given list") else: 22 print("y is NOT present in given list") Python Programming Unit-1 Notes Precedence and Associativity of Operators Operator precedence and associativity determine the priorities of the operator. Operator Precedence This is used in an expression with more than one operator with different precedence to determine which operation to perform first. >>> # Precedence of '+' & '*' >>> expr = 10 + 20 * 30 >>> print(expr) 610 >>> # Precedence of 'or' & 'and' >>> name = "Alex" >>> age = 0 >>> if name == "Alex" or name == "John" and age >= 2:... print ("Hello! Welcome.")... else:... print ("Good Bye!!") Hello! Welcome. Operator Associativity If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left. 23 Python Programming Unit-2 Notes CHAPTER 2- Control flow & Function in Python Conditional execution In order to write useful programs, we almost always need the ability to check conditions and change the behaviour of the program accordingly. Conditional statements give us this ability. if statement The if statement is used to test a particular condition and if the condition is true, it executes a block of code known as if-block. The condition of if statement can be any valid logical expression which can be either evaluated to true or false. The syntax of the if-statement is given below. if (condition): #statement1 #extra statements.... #statement2 # Here if the condition is true, if block # will consider only statement1 and extra statements to be inside its block. # statement 2 is outside of if block. Example:- # Python program to illustrate If statement i = 10 if (i>15): print("10 is less than 15") print("I am not in if block") I am not in if As the condition present in the if statement is false. So, the block below the if statement is not executed. if-else The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition. If the condition is true, then the if-block is executed. Otherwise, the else-block is executed. Python Programming Unit-2 Notes if (condition): # Executes this block if # condition is true else: # Executes this block if # condition is false # Python program to illustrate If else statement I = 20 if (I< 15): print("I is smaller than 15") print("I'm in if Block") else: print("I is greater than 15") print("I'm in else Block") print("I'm not in if and not in else Block") I is greater than 15 I'm in else Block I'm not in if and not in else Block The block of code following the else statement is executed as the condition present in the if statement is false after calling the statement which is not in block (without spaces). Nested-if A nested if is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Python allows us to nest if statements within if statements. i.e., we can place an if statement inside another if statement. if (condition1): # Executes when condition1 is true if (condition2): # Executes when condition2 is true # if Block is end here # if Block is end here Python Programming Unit-2 Notes # Python program to illustrate nested If statement i = 10 if (i == 10): # First if statement if (i< 15): print("i is smaller than 15") # Nested - if statement # Will only be executed if statement above # it is true if (i< 12): print("i is smaller than 12 too") else: print("i is greater than 15") i is smaller than 15 i is smaller than 12 too If-elif-else ladder The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if (condition): statement elif (condition): statement.. else: statement # Python program to illustrate if-elif-else ladder i = 15 if (i == 10): print("i is 10") elif (i == 15): print("i is 15") else: print("i is not present") i is 15 Python Programming Unit-2 Notes Looping statements: 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. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. while loop In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed. while (expression) : statement(s) All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. # Python program to illustrate while loop count = 0 while count